hostess
aws
aws.ec2
EBS_VOLUME_TYPES = ('gp2', 'gp3', 'io1', 'io2', 'st1', 'sc1')
module-attribute
all current-generation EBS volume types
InstanceDescription = dict[str, Union[dict, str]]
module-attribute
concise version of an EC2 API Instance data structure (see https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Instance.html)
InstanceIdentifier = str
module-attribute
stringified IP (e.g. '111.11.11.1' or full instance id
(e.g. 'i-0243d3f8g0a85cb18'), used as an instance identifier by some
functions in this module.
InstanceState = Literal['running', 'stopped', 'terminated', 'stopping', 'pending', 'shutting-down']
module-attribute
valid EC2 instance state names
Cluster
Class offering an interface to multiple EC2 instances at once.
Source code in hostess/aws/ec2.py
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 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 | |
__init__(instances)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instances
|
Collection[Instance]
|
Instance objects to incorporate into this Cluster. |
required |
Source code in hostess/aws/ec2.py
1295 1296 1297 1298 1299 1300 1301 | |
_async_method_call(method_name, *args, **kwargs)
Internal wrapper function: make multithreaded calls to a specified method of all this Cluster's Instances with shared arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method_name
|
str
|
named method of Instance to call on all our Instances |
required |
*args
|
Any
|
args to pass to these method calls |
()
|
**kwargs
|
Any
|
kwargs to pass to these method calls |
{}
|
Returns:
| Type | Description |
|---|---|
list[Any]
|
list containing results of method call from each Instance, including raised Exceptions for failed calls |
Source code in hostess/aws/ec2.py
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 | |
_async_method_map(method, argseq=None, kwargseq=None, max_concurrent=1, task_delay=None, poll=0.03)
Internal wrapper function: make multithreaded calls to a specified method of this Cluster's Instances with arbitrary number and homogeneity of arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
name of method of Instance to call on Instances |
required |
argseq
|
Optional[Union[Sequence[Sequence], cycle]]
|
optional args to pass to these method calls -- one
sequence of args per Instance. either |
None
|
kwargseq
|
Optional[Union[Sequence[Mapping[str, Any]], cycle]]
|
optional kwargs to pass to these method calls -- one
|
None
|
Returns:
| Type | Description |
|---|---|
ServerPool
|
list containing result of method call from each Instance, including raised Exceptions for failed calls |
Source code in hostess/aws/ec2.py
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 | |
_async_transfer_map(method, argseq=None, kwargseq=None)
" Internal wrapper function: make multithreaded calls to a specified file I/O method of all this Cluster's Instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
name of file I/O method of Instance |
required |
argseq
|
Optional[Union[Sequence[Sequence], cycle]]
|
optional args to pass to calls -- one sequence of args,
one sequence of args per Instance, or a |
None
|
kwargseq
|
Optional[Union[Sequence[Mapping[str, Any]], cycle]]
|
optional kwargs to pass to these method calls -- a single
|
None
|
Returns:
| Type | Description |
|---|---|
list[Any]
|
list containing result of method call from each Instance, including raised Exceptions for failed calls |
Source code in hostess/aws/ec2.py
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 | |
_check_exceptions(results, _permissive, _warn)
staticmethod
internal function for selective Exception-raising on async calls.
Source code in hostess/aws/ec2.py
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 | |
_format_map_arguments(argseq, kwargseq)
staticmethod
internal method for preprocessing mapped call arguments
Source code in hostess/aws/ec2.py
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 | |
call_python(module, func=None, payload=None, _permissive=False, _warn=True, **kwargs)
Call a Python function on all this Cluster's Instances. See
Instance.call_python() for further documentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
str
|
name of, or path to, the target module |
required |
func
|
Optional[str]
|
name of the function to call. |
None
|
payload
|
Any
|
object from which to constrct func's call arguments. |
None
|
_permissive
|
bool
|
if False, raise first Exception encountered, if any. |
False
|
_warn
|
bool
|
if True and |
True
|
**kwargs
|
Union[bool, str, CallerCompressionType, CallerSerializationType, CallerUnpackingOperator]
|
kwargs to pass to |
{}
|
Returns:
| Type | Description |
|---|---|
list[Processlike]
|
list containing results of |
Source code in hostess/aws/ec2.py
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 | |
command(command, *args, _permissive=False, _warn=True, **kwargs)
Call a shell command on all this Cluster's Instances. See
Instance.command() for further documentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
command name/string |
required |
_permissive
|
bool
|
if False, raise first Exception encountered, if any. |
False
|
_warn
|
bool
|
if True and |
True
|
*args
|
Union[str, int, float]
|
args to pass to |
()
|
**kwargs
|
bool
|
kwargs to pass to |
{}
|
Returns:
| Type | Description |
|---|---|
list[Union[Processlike, Exception]]
|
list containing result of |
Source code in hostess/aws/ec2.py
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 | |
commandmap(argseq, kwargseq=None, wait=True, max_concurrent=1, task_delay=None)
Map a shell command or commands across this Cluster's Instances,
asynchronously calling Instance.command() with optionally-variable
args and kwargs. This method enables a wide variety of dispatch/map
behaviors, and as such, has a very flexible signature.
Notes
- Unlike
Cluster.command(), this method blocks by default until all tasks have completed. If you do not wish it to block, passwait=False, which will cause it to return aServerPoolyou can later poll or join for output. - If neither
argseqandkwargseqspecify a finite number of tasks (e.g.,argseqis astrandkwargseqisNone), this method will execute the command once on each instance, much as if you had passed the same arguments toCluster.command(). - If both
argseqandkwargseqspecify a finite number of tasks (e.g.,argseqis alistoftuplesandkwargseqis alistofdicts), they must have equal length. - Task order is always preserved in output, but if the number of
tasks is greater than
len(self) * max_concurrent(e.g.,argseqis alistof 30tuples,max_concurrentis 1, and thisClusterhas 4Instances), there is no guarantee that tasks past the firstlen(self) * max_concurrenttasks will execute on any particular instance -- the underlyingServerPoolwill dispatch pending tasks as instances complete older ones. First come, first serves. - This method ignores the
_viewer=Falsemeta-option. It always returns eitherViewersor aServerPoolthat createsViewers. - This method ignores the
_disown=Truemeta-option.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argseq
|
Union[str, Sequence[Any]]
|
Positional argument(s). May be:
|
required |
kwargseq
|
Optional[Union[Mapping[str, Any], Sequence[Mapping[str, Any]]]]
|
Optional keyword argument(s). May be:
|
None
|
wait
|
bool
|
if |
True
|
max_concurrent
|
int
|
maximum number of commands to simultaneously run on each instance. |
1
|
task_delay
|
float | None
|
optional minimum interval, in seconds, between which subsequent tasks may be assigned to any one instance. |
None
|
Returns:
| Type | Description |
|---|---|
Union[list[Viewer], ServerPool]
|
If |
Source code in hostess/aws/ec2.py
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 | |
commands(commands, op='then', _con=False, _permissive=False, _warn=True, **kwargs)
Call a sequence of shell commands on all this Cluster's Instances. See
Instance.commands() for further documentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
commands
|
Sequence[str]
|
command names/strings |
required |
op
|
Literal['and', 'xor', 'then']
|
logical operator to connect commands. |
'then'
|
_con
|
bool
|
run 'console-style', pretty-printing rather than returning output (will look message with lots of Instances) |
False
|
_permissive
|
bool
|
if False, raise first Exception encountered, if any. |
False
|
_warn
|
bool
|
if True and |
True
|
**kwargs
|
bool
|
kwargs to pass to |
{}
|
Returns:
| Type | Description |
|---|---|
list[Union[Processlike, Exception]]
|
list containing result of |
Source code in hostess/aws/ec2.py
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 | |
con(command, *args, _permissive=False, _warn=True, **kwargs)
Run a command 'console-style' on all this cluster's instances. See
Instance.con() for further documentation. Note that this doesn't
perform any kind of managed separation of outputs from different
instances, so it can get pretty visually messy for commands that write
to stdout/stderr multiple times.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
command name/string |
required |
_permissive
|
bool
|
if False, raise first Exception encountered, if any. |
False
|
_warn
|
bool
|
if True and |
True
|
*args
|
Union[str, int, float]
|
args to pass to |
()
|
**kwargs
|
bool
|
kwargs to pass to |
{}
|
Returns:
| Type | Description |
|---|---|
list[Optional[Viewer]]
|
list containing results of |
Source code in hostess/aws/ec2.py
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 | |
connect(maxtries=10, delay=1)
establish SSH connections to all instances, prepping new connections when none currently exist, but not replacing existing ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maxtries
|
int
|
maximum times to re-attempt failed connections |
10
|
delay
|
float
|
how many seconds to wait after failed attempts |
1
|
Source code in hostess/aws/ec2.py
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 | |
from_descriptions(descriptions, **kwargs)
classmethod
Construct a Cluster from InstanceDescriptions, as produced by
ls_instances().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
descriptions
|
Collection[InstanceDescription]
|
InstanceDescriptions to initialize Instances from and subsequently collect into a Cluster. |
required |
**kwargs
|
Union[str, Path, BaseClient, ServiceResource, Session, bool]
|
kwargs to pass to the Instance constructor |
{}
|
Returns:
| Type | Description |
|---|---|
Cluster
|
a Cluster including an Instance for each description. |
Source code in hostess/aws/ec2.py
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 | |
get(source, target, _permissive=False, _warn=True, **kwargs)
copy files from instances to local.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[Sequence[Union[str, Path]], str, Path]
|
path to file (shared between all instances), or a sequence of paths to files on instances, one per instance |
required |
target
|
Union[str, Path, IO, Sequence[Union[str, Path, IO]]]
|
path to local file, or a filelike object (such as
io.BytesIO), or a sequence of such things, one per instance.
if |
required |
_permissive
|
bool
|
if False, raise first Exception encountered, if any. |
False
|
_warn
|
bool
|
if True and |
True
|
**kwargs
|
Any
|
kwargs to pass to underlying get method |
{}
|
Returns:
| Type | Description |
|---|---|
list[Union[dict, Exception]]
|
list of dicts giving transfer metadata: local, remote, host, port, including Exceptions for falled gets if _permissive is True. |
Source code in hostess/aws/ec2.py
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 | |
install_conda(installer_url=CONDA_DEFAULTS['installer_url'], prefix=CONDA_DEFAULTS['prefix'], _permissive=False, _warn=False, **kwargs)
install a Conda Python distribution on all instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
installer_url
|
str
|
url of install script; by default, the latest miniforge3 Linux x86_64 installer. |
CONDA_DEFAULTS['installer_url']
|
prefix
|
str
|
path for Conda installation. If a Conda installation already exists at this path, it will be updated. Defaults to $HOME/miniconda3. |
CONDA_DEFAULTS['prefix']
|
_permissive
|
bool
|
if False, raise first Exception encountered, if any. |
False
|
_warn
|
bool
|
if True and |
False
|
kwargs
|
bool
|
kwargs to pass to |
{}
|
Returns:
| Type | Description |
|---|---|
list[Union[Processlike, Exception]]
|
List containing outputs of |
Source code in hostess/aws/ec2.py
2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 | |
launch(count, template=None, options=None, tags=None, client=None, session=None, wait=True, connect=False, maxtries=40, increment_names=True, verbose=True, **instance_kwargs)
classmethod
Launch a fleet of Instances and collect them into a Cluster. See hostess documentation Notebooks for examples of how to construct options, tags, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int
|
number of instances to launch |
required |
template
|
Optional[str]
|
name of preexisting EC2 launch template to construct instances from. if not specified, will use a 'scratch' template. |
None
|
options
|
Optional[dict]
|
optional dict of specifications for Instances. if not specified, will use default values for everything. Currently, if a template is specified, it will override all values in options. This will change in the future. |
None
|
tags
|
Optional[dict]
|
optional tags to apply to the launched instances and their associated EBS volumes (if any). |
None
|
client
|
Optional[BaseClient]
|
optional preexisting EC2 client. |
None
|
session
|
Optional[Session]
|
optional preexisting boto session. |
None
|
wait
|
bool
|
if True, block after launch until all instances are running. overrides connect=True if False. |
True
|
connect
|
bool
|
if True, block after launch until all instances are connectable. |
False
|
maxtries
|
int
|
how many times to try to connect to the instances if connect=True (waiting 1s between each attempt) |
40
|
increment_names
|
bool
|
if True and count > 1, suffix incrementing integers to the names of each instance in the Cluster, and, if they had Name tags already, add a "ClusterName" tag indicating the base name |
True
|
verbose
|
bool
|
if True, print launch progress to stdout |
True
|
**instance_kwargs
|
Union[str, BaseClient, ServiceResource, Session, Path, bool]
|
kwargs to pass to the Instance constructor. |
{}
|
Returns:
| Type | Description |
|---|---|
Cluster
|
a Cluster created from the newly-launched fleet. |
Source code in hostess/aws/ec2.py
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 | |
put(source, target, *args, literal_str=False, _permissive=False, _warn=True, **kwargs)
write local files or in-memory data to target files on instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path, IO, bytes]
|
filelike object, path to local file, string, or bytestring (shared between all instances), or a sequence of such objects, one per instance. note that if this is a single filelike object, it will be read into memory and closed before sending its contents to the instances. |
required |
target
|
Union[str, Path]
|
write path (shared between all instances), or a sequence of write paths, one per instance. |
required |
_permissive
|
bool
|
if False, raise first Exception encountered, if any. |
False
|
_warn
|
bool
|
if True and |
True
|
args
|
Any
|
additional arguments to pass to underlying put method |
()
|
literal_str
|
bool
|
if True and |
False
|
**kwargs
|
Any
|
kwargs to pass to underlying get method |
{}
|
Returns:
| Type | Description |
|---|---|
list[Union[dict, Exception]]
|
list of dicts giving transfer metadata: local, remote, host, port, including Exceptions for falled puts if _permissive is True. |
Source code in hostess/aws/ec2.py
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 | |
pythonmap(argseq, kwargseq=None, wait=True, max_concurrent=1, task_delay=None)
Map Python calls across this Cluster's Instances, asynchronously
calling Instance.call_python() with optionally-variable args and
kwargs. This method has the same flexible calling conventions as
Cluster.commandmap(); refer to that method's documentation for more
detail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argseq
|
Union[str, Sequence[Any]]
|
Positional argument(s) to |
required |
kwargseq
|
Optional[Union[Mapping[str, Any], Sequence[Mapping[str, Any]]]]
|
Optional keyword argument(s) to |
None
|
wait
|
bool
|
if |
True
|
max_concurrent
|
int
|
maximum number of calls to simultaneously perform on each instance. |
1
|
task_delay
|
float | None
|
optional minimum interval, in seconds, between which subsequent calls may be assigned to any one instance. |
None
|
Returns:
| Type | Description |
|---|---|
Union[list[Union[Viewer, Exception]], ServerPool]
|
If |
Source code in hostess/aws/ec2.py
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 | |
read(source, mode='r', encoding='utf-8', as_buffer=False, concatenate=False, separator=None, _permissive=True, _warn=True, **kwargs)
read files from instances directly into memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[Sequence[Union[str, Path]], str, Path]
|
path to file (same path on all instances), or a sequence of paths to files on instances, one per instance |
required |
mode
|
Union[Literal['r', 'rb'], Sequence[Literal['r', 'rb']]]
|
"r" for text, "rb" for binary, or a sequence of those, one
per instance. must be a single value if |
'r'
|
encoding
|
str
|
encoding for text files. ignored when mode is "rb". |
'utf-8'
|
as_buffer
|
bool
|
if True, return BytesIO/StringIO instead of bytes/str |
False
|
concatenate
|
bool
|
if True, concatenate contents of all files into a single object (preserving order), rather than returning them as a list |
False
|
separator
|
Optional[Union[str, bytes]]
|
if |
None
|
_permissive
|
bool
|
if False, raise the first Exception encountered, if any. When True, and concatenating, simply concatenate only successful reads (meaning Exceptions will be discarded). |
True
|
_warn
|
bool
|
if True and |
True
|
**kwargs
|
Any
|
kwargs to pass to underlying get method |
{}
|
Returns:
| Type | Description |
|---|---|
Union[BytesIO, StringIO, bytes, str, Sequence[Union[BytesIO, StringIO, bytes, str]]]
|
if |
Source code in hostess/aws/ec2.py
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 | |
read_csv(source, encoding='utf-8', add_identifiers=True, reset_index=True, _permissive=False, _warn=False, **csv_kwargs)
read CSV-like files from all instances and concatenate them along the column axis into a pandas DataFrame, optionally adding identifier columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[Sequence[Union[str, Path]], str, Path]
|
path to CSV-like file (same path on all instances), or a sequence of such paths, one per instance |
required |
encoding
|
str
|
text encoding for CSV-like files |
'utf-8'
|
add_identifiers
|
bool
|
if True, add "name" and "id" columns to the returned DataFrame indicating which instances produced which rows. |
True
|
reset_index
|
bool
|
if True, reset index and drop original indices. |
True
|
_permissive
|
bool
|
if False, raise first Exception encountered during
read, if any. When True, simply ignore read Exceptions,
meaning the |
False
|
_warn
|
bool
|
if True and |
False
|
**csv_kwargs
|
Any
|
kwargs to pass to pd.read_csv |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A |
Source code in hostess/aws/ec2.py
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 | |
rebase_ssh_ingress_ip(ip=None, force=False, revoke=True)
Modify all security groups associated with all of this Cluster's
instances to permit SSH access from an IP IMPORTANT: by default,
this method revokes all other inbound access permissions, because it
is good security practice to not slowly whitelist the entire world.
Pass revoke=False if there are permissions you need to retain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ip
|
Optional[str]
|
permit SSH access from this IP. if None, use the caller's external IP. |
None
|
force
|
bool
|
if True, will force modification even of default security groups. |
False
|
revoke
|
bool
|
if True, will revoke all other inbound permissions. |
True
|
Returns:
| Type | Description |
|---|---|
list[None]
|
list of None (since the Instance method doesn't return anything) |
Source code in hostess/aws/ec2.py
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 | |
start(*args, **kwargs)
Start all Instances. See Instance.start() for further documentation,
including valid arguments.
Returns:
| Type | Description |
|---|---|
list
|
list containing results of |
Source code in hostess/aws/ec2.py
1729 1730 1731 1732 1733 1734 1735 1736 1737 | |
stop(*args, **kwargs)
Stop all Instances. See Instance.stop() for further documentation,
including valid arguments.
Returns:
| Type | Description |
|---|---|
list
|
list containing results of |
Source code in hostess/aws/ec2.py
1739 1740 1741 1742 1743 1744 1745 1746 1747 | |
terminate(*args, **kwargs)
Terminate all Instances. See Instance.terminate() for further
documentation / valid arg and kwargs.
Returns:
| Type | Description |
|---|---|
list
|
list containing results of |
Source code in hostess/aws/ec2.py
1749 1750 1751 1752 1753 1754 1755 1756 1757 | |
update()
update basic information for instances.
Source code in hostess/aws/ec2.py
1725 1726 1727 | |
Instance
Interface to an EC2 instance. Enables remote procedure calls, state control, and monitoring.
Attributes:
| Name | Type | Description |
|---|---|---|
session |
Session
|
session for API calls |
client |
BaseClient
|
client for API calls |
resource |
ServiceResource
|
resource for API calls |
instance_ |
Instance
|
underlying boto3 |
instance_id |
str
|
AWS instance id |
instance_type |
str
|
AWS instance type (e.g. 't3a.micro') |
tags |
dict
|
AWS resource tags for instance |
launch_time |
datetime
|
Time instance was launched |
name |
Optional[str]
|
Value of 'Name' tag; None if not present |
zone |
str
|
AWS Availability Zone |
uname |
Optional[str]
|
Username for SSH operations (if known) |
passed_key |
Optional[Path]
|
User-specified path to SSH keyfile, if any |
state |
InstanceState
|
state of instance (e.g. 'running') |
_ssh |
SSH
|
Underlying |
address_type |
Literal['private', 'public']
|
Whether we are using the instance's public or private IP for SSH connections. (Private IP should generally only be used from within AWS). |
ip |
Optional[str]
|
IPv4 address of instance -- its private
IP if |
key |
Optional[str]
|
stringified path to actually-existing SSH keyfile, if found |
key_errstring |
Optional[str]
|
detailed description of what went wrong with our last attempt to find and load an SSH keyfile, if anything |
Source code in hostess/aws/ec2.py
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 | |
__init__(description, *, uname=GENERAL_DEFAULTS['uname'], key=None, client=None, resource=None, session=None, use_private_ip=False, verbose=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
description
|
Union[InstanceIdentifier, InstanceDescription]
|
unique identifier for the instance, either its public / private IP (whichever is accessible from where you're initializing this object), the full instance identifier, or an InstanceDescription as returned by ls_instances(). |
required |
uname
|
str
|
username for SSH access to the instance. |
GENERAL_DEFAULTS['uname']
|
key
|
Optional[Path]
|
path to keyfile. You don't usually need to explicitly specify it. The constructor can find it automatically given the following conditions:
If those aren't both true, you'll need to pass this value to connect to the instance via SSH. |
None
|
client
|
Optional[BaseClient]
|
boto client. creates default client if not given. |
None
|
resource
|
Optional[ServiceResource]
|
boto resource. creates default resource if not given. |
None
|
session
|
Optional[Session]
|
boto session. creates default session if not given. |
None
|
verbose
|
bool
|
if True, print some changes in status to stdout. |
True
|
Source code in hostess/aws/ec2.py
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 | |
_check_unready()
Is the instance obviously not ready for SSH connections?
Returns:
| Type | Description |
|---|---|
Union[str, bool]
|
"state" if it is not running or transitioning to running; comma-separated list of "ip"/"uname"/"key" if any are missing. Otherwise False (meaning it looks ready). |
Source code in hostess/aws/ec2.py
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | |
_drop_ssh()
close an existing SSH connection and attempt to purge it from memory. should only be called by other methods of Instance.
Source code in hostess/aws/ec2.py
638 639 640 641 642 643 644 645 | |
_prep_connection(*, lazy=True, maxtries=5, delay=1)
try to prep, and optionally establish, a SSH connection to the instance. if no closed / latent connection exists, create one; otherwise, use the existing one. if the instance isn't running, automatically replace any existing connection (which will be closed anyway by then, or should be).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lazy
|
bool
|
don't establish the connection immediately; wait until some method needs it. other arguments do nothing if this is True. |
True
|
maxtries
|
int
|
maximum times to re-attempt failed connections |
5
|
delay
|
float
|
how many seconds to wait after subsequent attempts |
1
|
Source code in hostess/aws/ec2.py
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 | |
_update_ssh_info()
update SSH connectability info about Instance. raise an error if required info is not available. automatically remove any existing prepped connection if instance is not running.
Source code in hostess/aws/ec2.py
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 | |
call_python(module, func=None, payload=None, *, compression=None, serialization=None, interpreter=None, env=None, splat='', payload_encoded=False, print_result=True, filter_kwargs=True, **command_kwargs)
call a Python function on the instance. See
hostess.caller.generic_python_endpoint() for more verbose
documentation and technical discussion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
str
|
name of, or path to, the target module |
required |
func
|
Optional[str]
|
name of the function to call. must be a member of the target module (or explicitly imported by that module). |
None
|
payload
|
Any
|
object from which to construct func's call arguments.
must specify appropriate |
None
|
interpreter
|
Optional[str]
|
path to Python interpreter that should be specified in the shell command. |
None
|
env
|
Optional[str]
|
optional name of conda environment. both |
None
|
compression
|
CallerCompressionType
|
compression for payload. 'gzip' or None. |
None
|
serialization
|
CallerSerializationType
|
how to serialize |
None
|
splat
|
CallerUnpackingOperator
|
Operator for splatting the payload into the function call.
|
''
|
payload_encoded
|
bool
|
set to True if you have already
compressed/serialized |
False
|
print_result
|
bool
|
if True, the function call will print its result
to stdout, so it will be available in the |
True
|
filter_kwargs
|
bool
|
Attempt to filter |
True
|
**command_kwargs
|
bool
|
additional kwargs to pass to |
{}
|
Returns:
| Type | Description |
|---|---|
Viewer
|
|
Source code in hostess/aws/ec2.py
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 | |
command(command, *args, _viewer=True, _wait=False, _quiet=True, **kwargs)
run a command in the instance's default interpreter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
command name or full text of command
(see |
required |
*args
|
Union[int, str, float]
|
args to pass to |
()
|
_viewer
|
bool
|
if |
True
|
_wait
|
bool
|
if |
False
|
_quiet
|
bool
|
if |
True
|
**kwargs
|
Union[int, str, float, bool]
|
kwargs to pass to |
{}
|
Returns:
| Type | Description |
|---|---|
Processlike
|
object representing executed process. |
Source code in hostess/aws/ec2.py
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 | |
commands(commands, op='then', _con=False, **kwargs)
Remotely run a multi-part shell command. Convenience method
for constructing long shell instructions like
this && that && theother && etcetera.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
commands
|
Sequence[str]
|
commands to chain together. |
required |
op
|
Literal['and', 'xor', 'then']
|
logical operator to connect commands. |
'then'
|
_con
|
bool
|
run 'console-style', pretty-printing rather than returning output |
False
|
Returns:
| Type | Description |
|---|---|
Optional[Processlike]
|
abstraction representing executed process, or None if _con is True. |
Source code in hostess/aws/ec2.py
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 | |
compile_env()
Source code in hostess/aws/ec2.py
1024 1025 1026 | |
con(command, *args, _poll=0.05, _timeout=None, _return_viewer=False, **kwargs)
pretend you are running a command on the instance while looking at a terminal emulator. pauses for output and pretty-prints it to stdout.
Does not return a process abstraction by default (pass _return_viewer=True if you want one). Fun in interactive environments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
command name or full text of command
(see |
required |
_poll
|
float
|
polling rate for process output, in seconds |
0.05
|
_timeout
|
Optional[float]
|
if not None, raise a TimeoutError if this many seconds pass before receiving additional output from process (or process exit). |
None
|
_return_viewer
|
bool
|
if True, return a Viewer for the process once it exits. Otherwise, return None. |
False
|
**kwargs
|
Union[int, str, float, bool]
|
kwargs to pass to Instance.command(). |
{}
|
Returns:
| Type | Description |
|---|---|
Optional[Viewer]
|
A Viewer if _return_viewer is True; otherwise None. |
Source code in hostess/aws/ec2.py
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 | |
conda_env(env='base')
cached
Find the root directory of a named conda environment on the instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
str
|
name of conda environment |
'base'
|
Returns:
| Type | Description |
|---|---|
str
|
absolute path to root directory of conda environment. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
if environment cannot be found. |
Source code in hostess/aws/ec2.py
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 | |
connect(maxtries=5, delay=1)
establish SSH connection to the instance, prepping a new connection if none currently exists, but not replacing an existing one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maxtries
|
int
|
maximum times to re-attempt failed connections |
5
|
delay
|
float
|
how many seconds to wait after failed attempts |
1
|
Source code in hostess/aws/ec2.py
488 489 490 491 492 493 494 495 496 497 | |
find(identifier=None, states=('running', 'pending', 'stopping', 'stopped'), raw_filters=None, client=None, session=None, long=False, tag_regex=True, uname=GENERAL_DEFAULTS['uname'], *, key=None, resource=None, use_private_ip=False, pick_first=False, verbose=True, **tag_filters)
classmethod
Forwards relevant passed arguments to ls_instances() and returns an
Instance constructed from the first match, passing relevant arguments
to Instance.__init__(). It also accepts one unique argument,
pick_first; if True, it will return the first instance found in
the case of multiple matches; otherwise (default) raise a ValueError.
Arguments passed to ls_instances():
identifier, states, raw_filters, client, session,
long, tag_regex, tag_filters
Arguments passed to Instance.__init__():
uname, key, client, resource, session, use_private_ip,
verbose
See documentation for those functions for full discussion of those arguments.
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If |
Source code in hostess/aws/ec2.py
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 | |
find_package(package, env=None)
cached
Find the location of an installed Python package on the instance using
pip show.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package
|
str
|
name of package (e.g. 'requests') |
required |
env
|
Optional[str]
|
optional name of conda environment. If None, uses whatever
|
None
|
Returns:
| Type | Description |
|---|---|
str
|
Absolute path to parent directory of package (e.g. "/home/ubuntu/miniforge3/lib/python3.12/site-packages") |
Raises:
| Type | Description |
|---|---|
OSError
|
if unable to execute |
FileNotFoundError
|
if package doesn't appear to be installed |
Source code in hostess/aws/ec2.py
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 | |
get(source, target, *args, **kwargs)
copy file from instance to local.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
path to file on instance |
required |
target
|
Union[str, Path, IO]
|
path to local file, or a filelike object (such as io.BytesIO) |
required |
*args
|
Any
|
args to pass to underlying get method |
()
|
**kwargs
|
Any
|
kwargs to pass to underlying get method |
{}
|
Returns:
| Type | Description |
|---|---|
dict
|
dict giving transfer metadata: local, remote, host, port, and this instance's name, if any |
Source code in hostess/aws/ec2.py
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 | |
install_conda(installer_url=CONDA_DEFAULTS['installer_url'], prefix=CONDA_DEFAULTS['prefix'], **kwargs)
install a Conda Python distribution on the instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
installer_url
|
str
|
url of install script; by default, the latest miniforge3 Linux x86_64 installer. |
CONDA_DEFAULTS['installer_url']
|
prefix
|
str
|
path for Conda installation. If a Conda installation already exists at this path, it will be updated. Defaults to $HOME/miniforge3. |
CONDA_DEFAULTS['prefix']
|
kwargs
|
bool
|
kwargs to pass to |
{}
|
Returns:
| Type | Description |
|---|---|
Processlike
|
Output of |
Source code in hostess/aws/ec2.py
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 | |
launch(template=None, options=None, tags=None, client=None, session=None, wait=True, connect=False, maxtries=40, **instance_kwargs)
classmethod
launch a single instance. This is a thin wrapper for
Cluster.launch() with count=1. See that function for full
documentation.
Returns:
| Type | Description |
|---|---|
Instance
|
an Instance associated with a newly-launched EC2 instance. |
Source code in hostess/aws/ec2.py
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 | |
make_ssh_string()
Convenience method that returns a terminal command a local user might
run in a shell, assuming correct system configuration, in order
to start an interactive SSH session on this instance. This performs
no system-level verification that this command will actually work
(for instance, it does not check to see if ssh is locally
installed). This does not imply that Instance executed, or will
execute, this command at any point (it did not and will not).
Returns:
| Type | Description |
|---|---|
str
|
A string that, if run in a local shell, may start an interactive |
str
|
SSH session. |
Source code in hostess/aws/ec2.py
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | |
notebook(**connect_kwargs)
execute a Jupyter Notebook on the instance and establish a tunnel for local access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connect_kwargs
|
Union[int, str, bool]
|
arguments for notebook execution/connection. see
|
{}
|
Returns:
| Type | Description |
|---|---|
NotebookConnection
|
structure containing results of tunneled Notebook execution. |
Source code in hostess/aws/ec2.py
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 | |
put(source, target, *args, literal_str=False, **kwargs)
write local file or in-memory data to target file on instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path, IO, bytes]
|
filelike object or path to local file. note that filelike objects will be closed during put operation. |
required |
target
|
Union[str, Path]
|
write path on instance |
required |
args
|
Any
|
additional arguments to pass to underlying put method |
()
|
literal_str
|
bool
|
if True and |
False
|
kwargs
|
Any
|
additional kwargs to pass to underlying put command |
{}
|
Returns:
| Type | Description |
|---|---|
dict
|
dict giving transfer metadata: local, remote, host, and port |
Source code in hostess/aws/ec2.py
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 | |
read(source, mode='r', encoding='utf-8', as_buffer=False)
read a file from the instance directly into memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
path to file on instance |
required |
mode
|
Literal['r', 'rb']
|
'r' to read file as text; 'rb' to read file as bytes |
'r'
|
encoding
|
str
|
encoding for text, used only if |
'utf-8'
|
as_buffer
|
bool
|
if True, return BytesIO/StringIO; if False, return bytes/str |
False
|
Returns:
| Type | Description |
|---|---|
Union[BytesIO, StringIO, bytes, str]
|
Buffer containing contents of remote file |
Source code in hostess/aws/ec2.py
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 | |
read_csv(source, encoding='utf-8', **csv_kwargs)
read a CSV-like file from the instance into a pandas DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
path to CSV-like file on instance |
required |
encoding
|
str
|
encoding for text |
'utf-8'
|
csv_kwargs
|
Any
|
kwargs to pass to pd.read_csv |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame created from contents of remote CSV file |
Source code in hostess/aws/ec2.py
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 | |
rebase_ssh_ingress_ip(ip=None, force=False, revoke=True, verbose=True)
Modify this instance's security group(s) to permit SSH access from
an IP (by default, the caller's external IP). IMPORTANT: by default,
this method revokes all other inbound access permissions, because it
is good security practice to not slowly whitelist the entire world.
Pass revoke=Falseif there are permissions you need to retain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ip
|
Optional[str]
|
permit SSH access from this IP. if None, use the caller's external IP. |
None
|
force
|
bool
|
if True, will force modification even of default security groups. |
False
|
revoke
|
bool
|
if True, will revoke all other inbound permissions. |
True
|
verbose
|
bool
|
if True, print actions to stdout |
True
|
Source code in hostess/aws/ec2.py
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 | |
reboot(wait=True, hard=False, timeout=65)
Reboot or hard-restart the instance. Note that a hard restart will change the instance's ip unless it has been assigned a static ip. The Instance object will automatically handle this, but other code/processes using it will need to be informed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wait
|
bool
|
if True, block until instance state reaches 'running' again. |
True
|
hard
|
bool
|
if True, perform a 'hard' restart: fully shut the instance down and start it up again. if False, perform a 'soft' restart. Note that AWS will automatically switch to a 'hard' restart if its attempt at a soft restart fails. |
False
|
timeout
|
float
|
seconds to wait for state transitions before timing out. |
65
|
Source code in hostess/aws/ec2.py
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 | |
reconnect(maxtries=5, delay=1)
create and attempt to establish a new SSH connection to the instance, closing any existing one. Note that this will immediately terminate any non-daemonized processes previously executed over the existing connection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maxtries
|
int
|
maximum times to re-attempt failed connections |
5
|
delay
|
float
|
how many seconds to wait after failed attempts |
1
|
Source code in hostess/aws/ec2.py
499 500 501 502 503 504 505 506 507 508 509 510 511 512 | |
rename(name)
Rename the instance. Does not rename volumes or network interfaces. Updates local instance state cache when called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
new name for instance. |
required |
Source code in hostess/aws/ec2.py
343 344 345 346 347 348 349 350 351 352 353 354 | |
restart(wait=True, hard=False, timeout=65)
alias for Instance.reboot().
Source code in hostess/aws/ec2.py
1115 1116 1117 1118 1119 | |
start(return_response=False, wait=True, connect=False, maxtries=40)
Start the instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
return_response
|
bool
|
if True, return API response. |
False
|
wait
|
bool
|
if True, wait until instance is running. |
True
|
connect
|
bool
|
if True, wait until the instance is connectable via SSH
or we have tried to connect |
False
|
maxtries
|
int
|
max number of times to attempt connection (5s delay in between). |
40
|
Returns:
| Type | Description |
|---|---|
Optional[dict]
|
API response if |
Source code in hostess/aws/ec2.py
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 | |
stop(return_response=False)
Stop the instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
return_response
|
bool
|
if True, return API response. |
False
|
Return
API response if return_response is True; otherwise None.
Source code in hostess/aws/ec2.py
840 841 842 843 844 845 846 847 848 849 850 851 852 853 | |
terminate(return_response=False)
Terminate (aka delete) the instance. The royal road to cloud cost management. Please note that this action is permanent and cannot be undone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
return_response
|
bool
|
if True, return the API response. |
False
|
Returns:
| Type | Description |
|---|---|
Optional[dict]
|
API response if |
Source code in hostess/aws/ec2.py
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 | |
tunnel(local_port, remote_port)
create an SSH tunnel between a local port and a remote port.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
local_port
|
int
|
port number for local end of tunnel. |
required |
remote_port
|
int
|
port number for remote end of tunnel. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
signaler |
Callable
|
function to shut down tunnel |
tunnel_metadata |
dict[str, Union[int, str, Path]]
|
dict of metadata about the tunnel |
Source code in hostess/aws/ec2.py
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 | |
update()
Refresh basic state and identification information.
Source code in hostess/aws/ec2.py
1028 1029 1030 1031 1032 1033 1034 | |
wait_on_connection(maxtries)
block until an SSH connection to the instance is established
Source code in hostess/aws/ec2.py
475 476 477 478 479 480 481 482 483 484 | |
wait_until(state, timeout=65)
Pause execution until the instance reaches the specified state.
Automatically updates state and ip attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Literal[InstanceState]
|
name of target instance state |
required |
timeout
|
float
|
how long, in seconds, to wait before timing out |
65
|
Source code in hostess/aws/ec2.py
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 | |
wait_until_running(timeout=65)
Alias for Instance.wait_until('running')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
how long, in seconds, to wait until timing out |
65
|
Source code in hostess/aws/ec2.py
1053 1054 1055 1056 1057 1058 1059 1060 | |
wait_until_started(timeout=65)
Additional alias for Instance.wait_until('running')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
how long, in seconds, to wait until timing out |
65
|
Source code in hostess/aws/ec2.py
1062 1063 1064 1065 1066 1067 1068 1069 | |
wait_until_stopped(timeout=65)
Alias for Instance.wait_until('stopped')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
how long, in seconds, to wait before timing out |
65
|
Source code in hostess/aws/ec2.py
1071 1072 1073 1074 1075 1076 1077 1078 | |
wait_until_terminated(timeout=65)
Alias for Instance.wait_until('terminated')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
how long, in seconds, to wait before timing out |
65
|
Source code in hostess/aws/ec2.py
1080 1081 1082 1083 1084 1085 1086 1087 | |
NoKeyError
Bases: OSError
we're trying to do things over SSH, but can't find a valid keyfile.
Source code in hostess/aws/ec2.py
98 99 | |
_ebs_device_mapping(volume_type, volume_size, index=0, iops=None, throughput=None, device_name=None)
reformat the passed specification as a legal EC2 API LaunchTemplateBlockDeviceMappingRequest object
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume_type
|
str
|
EBS volume type, e.g. 'gp3' |
required |
volume_size
|
int
|
volume size in GB |
required |
index
|
int
|
index of volume among all specified volumes (0 means root) |
0
|
iops
|
Optional[int]
|
I/O operations per second, if other than default and volume type supports IOPS specification |
None
|
throughput
|
Optional[int]
|
throughput in MiB/s, if other than default and volume type supports throughput specification |
None
|
device_name
|
Optional[str]
|
optional block device name; if not specified, will automatically assign one based on index |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
LaunchTemplateBlockDeviceMappingRequest-formatted dict |
Source code in hostess/aws/ec2.py
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 | |
_hostess_placeholder()
create a random hostess placeholder name
Source code in hostess/aws/ec2.py
2685 2686 2687 | |
_instances_from_ids(ids, resource=None, session=None, **instance_kwargs)
helper function for cluster launch.
Source code in hostess/aws/ec2.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | |
_interpret_ebs_args(volume_type=None, volume_size=None, iops=None, throughput=None, volume_list=None)
helper function for create_launch_template(). Parse user-provided volume
specifications into a list of dicts formatted like EC2 API
LaunchTemplateBlockDeviceMappingRequest objects.
This function permits specification of either a volume_list or volume_type + volume_size + (optional) iops + (optional) throughput, which all implicitly refer to a single boot volume.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume_type
|
Optional[Literal['gp2', 'gp3', 'io1', 'io2']]
|
EBS volume type for instance boot volum. |
None
|
volume_size
|
Optional[int]
|
Size in GB for instance boot volume. |
None
|
iops
|
Optional[int]
|
IOPS for instance boot volume, if other than default |
None
|
throughput
|
Optional[int]
|
throughput for instance boot volume, if other than default |
None
|
volume_list
|
Optional[Sequence[dict[str, Union[int, str]]]]
|
sequence of dicts that could be passed as kwargs to this function, giving all volumes that will be attached to the instance at creation. the first one is the boot volume. If specified, volume_type and volume_size must be None. |
None
|
Returns:
| Type | Description |
|---|---|
list[dict]
|
LaunchTemplateBlockDeviceMappingRequest objects from specs |
Source code in hostess/aws/ec2.py
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 | |
_retrieve_instance_type_info(client=None, session=None, reset_cache=False)
Retrieve full descriptions of all instance types available in the client's AWS Region, either from the API or from an on-disk cache, and cache them to disk if retrieved from API.
This is primarily intended to be used as a helper function for higher-level instance type summarization and tabulation functions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Optional[BaseClient]
|
optional preexisting boto ec2 client |
None
|
session
|
Optional[Session]
|
optional preexisting boto session |
None
|
reset_cache
|
bool
|
if True, always retrieve all descriptions from the API, even if 'fresh' cached descriptions are available on disk. If False, do so only if there are no cached descriptions or they are more than 5 days old. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[dict]
|
dicts produced from EC2 InstanceTypeInfo API objects, one for every instance type available in the AWS Region. |
Source code in hostess/aws/ec2.py
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 | |
authorize_ssh_ingress_from_ip(sg, ip=None, force_modification_of_default_sg=False, verbose=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sg
|
SecurityGroup
|
ec2.SecurityGroup object to apply authorization to |
required |
ip
|
Optional[str]
|
ip to authorize |
None
|
force_modification_of_default_sg
|
bool
|
apply modification even to a default security group? |
False
|
verbose
|
bool
|
if True, print actions to stdout |
True
|
Source code in hostess/aws/ec2.py
3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 | |
connectwrap(func)
Decorator for methods of Instance that require an SSH connection to work. Causes them to check for an open connection, and, if they do not find one, to attempt to open one.
Source code in hostess/aws/ec2.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
create_ec2_key(key_name=None, save_key=True, resource=None, session=None)
Create a new EC2 SSH key pair in the caller's AWS account. Optionally also save the key material to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_name
|
Optional[str]
|
optional name for key pair (if not specified, a name is randomly assigned) |
None
|
save_key
|
bool
|
if True, save the key material to disk in ~/.ssh, in a .pem file with the same filename stem as the key pair |
True
|
resource
|
Optional[ServiceResource]
|
optional preexisting boto ec2 resource |
None
|
session
|
Optional[Session]
|
optional preexisting boto session |
None
|
Returns:
| Type | Description |
|---|---|
KeyPair
|
a boto3 KeyPair resource providing an interface to the newly-created key pair. |
Source code in hostess/aws/ec2.py
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 | |
create_launch_template(template_name=None, instance_type=EC2_DEFAULTS['instance_type'], volume_type=None, volume_size=None, image_id=None, iops=None, throughput=None, volume_list=None, instance_name=None, security_group_name=None, tags=None, key_name=None, client=None, session=None, verbose=True)
Create a new EC2 launch template in the caller's AWS account (see https://docs.aws.amazon.com/autoscaling/ec2/userguide/launch-templates.html).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template_name
|
Optional[str]
|
optional name for template. if none is specified, a random name is assigned. |
None
|
instance_type
|
str
|
instance type name (e.g. 'm6i.large') |
EC2_DEFAULTS['instance_type']
|
volume_type
|
Optional[Literal['gp2', 'gp3', 'io1', 'io2']]
|
EBS volume type for boot volume (e.g. 'gp3'). If not
specified and |
None
|
volume_size
|
Optional[int]
|
volume size in GB for boot volume. If not specified and
|
None
|
image_id
|
Optional[str]
|
ID for Amazon Machine Image (AMI) to create instance from. if not specified, uses the most recently-released Ubuntu Server LTS AMI. |
None
|
iops
|
Optional[int]
|
I/O operations per second for boot volume, if other than default and volume type supports IOPS specification; ignored if volume_list passed |
None
|
throughput
|
Optional[int]
|
throughput in MiB/s for boot volume, if other than default and volume type supports throughput specification; ignored if volume_list passed |
None
|
volume_list
|
Optional[list[dict]]
|
alternative to specifying volume_type/volume_size (and optional iops/throughput). a list of dicts with 'volume_type', 'volume_size', and optionally 'iops' and 'throughput' keys. Each of these dicts specifies a separate EBS volume for the instance; the first will be the boot volume. It must not be passed along with volume_size or volume_type. |
None
|
instance_name
|
Optional[str]
|
optional name for instances created from template |
None
|
security_group_name
|
Optional[str]
|
optional name of preexisting security group. if not specified, a new security group will be created. |
None
|
tags
|
Optional[dict]
|
optional dict like {tag name: tag value} specifying resource tags for instances and volumes created from this template. |
None
|
key_name
|
Optional[str]
|
optional name of preexisting EC2 key pair object known to AWS. if not specified, a new EC2 key pair will be created and a corresponding key file will be saved to disk in ~/.ssh. |
None
|
client
|
Optional[BaseClient]
|
optional preexisting boto ec2 client |
None
|
session
|
Optional[Session]
|
optional preexisting boto session |
None
|
verbose
|
bool
|
if True, print launch template decision process to stdout |
True
|
Returns:
| Type | Description |
|---|---|
dict
|
dict created from an AWS LaunchTemplate API response. |
Source code in hostess/aws/ec2.py
2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 | |
create_security_group(name=None, description=None, client=None, resource=None, session=None)
Create a new EC2 security group in the caller's AWS account with default hostess settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
Optional[str]
|
optional name for new security group. If not specified, will randomly assign a name. |
None
|
description
|
Optional[str]
|
optional description for new security group. will give a default description. |
None
|
client
|
Optional[BaseClient]
|
optional preexisting boto ec2 client |
None
|
resource
|
Optional[ServiceResource]
|
optional preexisting boto ec2 resource |
None
|
session
|
Optional[Session]
|
optional preexisting boto session |
None
|
Returns:
| Type | Description |
|---|---|
SecurityGroup
|
A boto3 SecurityGroup resource providing an interface to the newly- created security group. |
Source code in hostess/aws/ec2.py
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 | |
describe_instance_type(instance_type, pricing=True, ec2_client=None, pricing_client=None, session=None)
Retrieve a succinct description of an EC2 instance type.
NOTE: this function will report i386 architecture for the very limited number of instance types that support both i386 and x86_64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance_type
|
str
|
instance type name, e.g. 'm6i.large' |
required |
pricing
|
bool
|
if True, also retrieve pricing information |
True
|
ec2_client
|
Optional[BaseClient]
|
optional preexisting boto ec2 client |
None
|
pricing_client
|
Optional[BaseClient]
|
optional preexisting boto pricing client |
None
|
session
|
Optional[Session]
|
optional preexisting boto session |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
dict containing summary information for this instance type |
Source code in hostess/aws/ec2.py
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 | |
get_canonical_images(architecture='x86_64', client=None, session=None)
fetch the subset of official (we refuse to make the obvious pun) Ubuntu Amazon Machine Images from Canonical that we might plausibly want to offer as defaults to users. This will generally return hundreds of images and take > 1.5 seconds because of the number of unsupported daily builds available, so we cache the results with a one-week shelf life.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
architecture
|
Literal['x86_64', 'arm64', 'i386']
|
get images for this system architecture |
'x86_64'
|
client
|
Optional[BaseClient]
|
optional preexisting boto client |
None
|
session
|
Optional[Session]
|
optional preexisting boto session |
None
|
Returns:
| Type | Description |
|---|---|
list[dict]
|
list of metadata dictionaries for all matching Canonical AMIs |
Source code in hostess/aws/ec2.py
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 | |
get_stock_ubuntu_image(architecture='x86_64', client=None, session=None)
retrieve image ID of the most recent officially-supported Canonical Ubuntu Server LTS AMI for the provided architecture.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
architecture
|
Literal['x86_64', 'arm64', 'i386']
|
get images for this system architecture |
'x86_64'
|
client
|
Optional[BaseClient]
|
optional preexisting boto client |
None
|
session
|
Optional[Session]
|
optional preexisting boto session |
None
|
Returns:
| Type | Description |
|---|---|
str
|
AWS image ID for most recent matching Ubuntu Server LTS AMI. |
Source code in hostess/aws/ec2.py
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 | |
instance_catalog(family=None, client=None, session=None)
Construct a catalog of available instance types, including their technical specifications and on-demand pricing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
family
|
Optional[str]
|
optional name of instance family, e.g. 'm6i'. If not specified, catalog includes all available instance types. |
None
|
client
|
Optional[BaseClient]
|
optional preexisting boto ec2 client |
None
|
session
|
Optional[Session]
|
optional preexisting boto session |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Instance catalog DataFrame. |
Source code in hostess/aws/ec2.py
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 | |
ls_instances(identifier=None, states=('running', 'pending', 'stopping', 'stopped'), raw_filters=None, client=None, session=None, long=False, tag_regex=True, **tag_filters)
ls for EC2 instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identifier
|
Optional[InstanceIdentifier]
|
string specifying a particular instance. may be a stringified IP address or instance id. |
None
|
states
|
Sequence[str]
|
strings specifying legal states for listed instances. |
('running', 'pending', 'stopping', 'stopped')
|
raw_filters
|
Optional[Sequence[Mapping[str, str]]]
|
search filters to pass directly to the EC2 API. |
None
|
client
|
Optional[BaseClient]
|
optional boto3 Client object |
None
|
session
|
Optional[Session]
|
optional boto3 Session object |
None
|
long
|
bool
|
if not True, return InstanceDescriptions, including only the most regularly-pertinent information, flattened, with succinct field names. Otherwise, return a flattened version of the full API response. |
False
|
tag_regex
|
bool
|
regex patterns for tag matching. |
True
|
tag_filters
|
str
|
filters to interpret as tag name / value pairs before passing to the EC2 API. |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[Union[InstanceDescription, dict]]
|
tuple of records describing all matching EC2 instances owned by caller. |
Source code in hostess/aws/ec2.py
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 | |
revoke_ingress(sg, force_modification_of_default_sg=False, ports=(22,), protocols=('tcp',), verbose=True)
Remove inbound permission rules from a security group. The default settings revoke permissions on the default SSH port.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sg
|
SecurityGroup
|
boto3 SecurityGroup resource object |
required |
force_modification_of_default_sg
|
bool
|
if True, modify rules even if
|
False
|
ports
|
Collection[int]
|
revoke only those rules granting ingress on one of these ports |
(22,)
|
protocols
|
Collection[Literal['tcp', 'udp', 'icmp']]
|
revoke only those rules granting ingress via one of these protocols |
('tcp',)
|
verbose
|
bool
|
if True, print actions to stdout |
True
|
Source code in hostess/aws/ec2.py
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 | |
summarize_instance_description(description)
convert a dictionary produced from an EC2 API Instance object to a more
concise format. Likely sources for this dictionary include boto3 or
parsing JSON responses from the AWS CLI or HTTP API.
Source code in hostess/aws/ec2.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
summarize_instance_type_response(response)
extract a series of EC2 InstanceTypeInfo from a boto3-wrapped DescribeInstanceTypes or DescribeInstanceTypeOfferings call and produce succinct summaries of them
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
dict
|
boto3-wrapped DescribeInstanceType* API response |
required |
Returns:
| Type | Description |
|---|---|
tuple[dict]
|
summaries of each described instance type |
Source code in hostess/aws/ec2.py
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 | |
summarize_instance_type_structure(itinfo)
summarize an EC2 InstanceTypeInfo object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itinfo
|
dict
|
dict created from an InstanceTypeInfo structure, as returned
by boto3 functions like |
required |
Returns:
| Type | Description |
|---|---|
dict
|
succinct version of InstanceTypeInfo structure |
Source code in hostess/aws/ec2.py
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 | |
aws.pricing
HOURS_PER_MONTH = 730
module-attribute
canonical hours-to-month conversion used in AWS rate quotes
get_ec2_basic_price_list(region=None, client=None, session=None, reset_cache=False)
on-demand rates are USD / instance-hour. EBS volume is USD / GB-month. EBS throughput is USD / Gibps-month. EBS IOPS is USD / IOPS-month. CPU credits are too complicated to explain in this margin.
Source code in hostess/aws/pricing.py
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 | |
get_on_demand_price(instance_type, region=None, client=None, session=None)
fetch on-demand pricing information for a specific instance type.
Source code in hostess/aws/pricing.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | |
aws.s3
This module provides managed operations on AWS S3 objects. Its centerpiece is a Bucket object providing a high-level interface to operations on a single S3 bucket. This module was originally motivated by the need to quickly construct pandas DataFrames containing inventories of large buckets.
Much of this module wraps lower-level methods of boto3, so it is in some sense an alternative implementation of boto3's own high-level managed S3 methods and objects, designed for cases in which deeper indexing, more response introspection, or more flexible I/O stream manipulation are required. We also like the syntax better.
AZ_IDPAT = re.compile('[a-z]{3}\\d-az(?P<number>\\d)')
module-attribute
Legal AZ id
AZ_NAMEPAT = re.compile('[a-z]{2}-[a-z]{3,10}-\\d(?P<letter>[a-z])')
module-attribute
Legal AZ name
BUCKET_NAMEPAT = re.compile('[a-z0-9-.]{3,63}')
module-attribute
Legal name for general-purpose bucket
BUCKET_TYPE = Literal['general', 'directory']
module-attribute
Pull account ID of owner out of directory bucket ARN
DIRECTORY_BUCKET_NAMEPAT = re.compile('[a-z0-9-.]{1,45}--[a-z]{3}\\d-az\\d--x-s3')
module-attribute
Legal name for zonal directory bucket
Puttable = Union[str, Path, IOBase, bytes, None]
module-attribute
type alias for Python objects Bucket will write to S3
Bucket
Interface to and representation of an S3 bucket.
Note
Bucket supports only general-purpose and directory buckets, not table buckets.
Source code in hostess/aws/s3.py
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 | |
_buckethead
cached
property
Cached response to HeadBucket call against this bucket. Not currently formatted in an interesting way for public use.
bucket_type
cached
property
Top-level type of bucket, 'general' or 'directory'. Does not distinguish directory bucket subtypes.
tags
cached
property
Bucket tags represented as a dict. If there are no tags, returns an empty dict.
__init__(bucket_name, client=None, resource=None, session=None, config=None, n_threads=4)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bucket_name
|
str
|
name of bucket |
required |
client
|
Optional[BaseClient]
|
optional boto3 s3 Client. if not specified, creates a default client. |
None
|
resource
|
Optional[ServiceResource]
|
optional boto3 s3 Resource. if not specified, creates a default resource. |
None
|
session
|
Optional[Session]
|
optional boto3 Session. if not specified, creates a default session. |
None
|
config
|
Optional[TransferConfig]
|
optional boto3 TransferConfig. if not specified, creates a default config. |
None
|
n_threads
|
Optional[int]
|
if not None, automatically multithread some operations.
note that this is not a hard cap on the number of threads used
by a single bucket operation. it provides a cap on concurrency
across operations on multiple objects, not on concurrency on
operations per object. if you wish to cap concurrency within
operations on individual objects, modify the |
4
|
Source code in hostess/aws/s3.py
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 | |
_maybe_write_ls_cache(page, cache)
staticmethod
helper function for Bucket.ls()
Source code in hostess/aws/s3.py
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 | |
_put_stream_chunk(blob, download_cache, parts, multipart, upload_numerator, config, exc, verbose=False, flush=False)
helper function for Bucket.put_stream()
Source code in hostess/aws/s3.py
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 | |
_s3c_kwargs()
Produces a dict containing kwargs s3control actions want.
Source code in hostess/aws/s3.py
1251 1252 1253 1254 1255 | |
abort_multipart_upload(multipart)
Abort a multipart upload operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
multipart
|
Mapping
|
API response received when multipart upload operation was created |
required |
Returns:
| Type | Description |
|---|---|
dict
|
API response |
Source code in hostess/aws/s3.py
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 | |
append(obj, key, literal_str=False, offset=None)
Write data at an offset to an S3 Express One Zone object. If no offset is specified, appends data to the end of the object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Puttable
|
string, Path, bytes, or filelike / buffer object to write.
If None and |
required |
key
|
str
|
key of S3 object in this bucket to write |
required |
literal_str
|
bool
|
if True and |
False
|
offset
|
int | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Cautions
append() does not currently perform managed multipart uploads.
This means that if obj is > 5 GB, the operation will fail, and
also that append() is generally inefficient for large writes.
In its current state, it is primarily intended for tasks like
tail-writes to logs. This may change in the future.
Source code in hostess/aws/s3.py
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 | |
chunk_putter_factory(key, upload_threads=4, download_threads=None, verbose=False)
construct a callable chunk uploader. this can be used in relatively direct ways or passed to complex pipelines as a callback.
Source code in hostess/aws/s3.py
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 | |
complete_multipart_upload(multipart, parts)
Notify S3 that all parts of an object have been uploaded and it may close the multipart upload operation and actually create the object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
multipart
|
Mapping
|
API response received when multipart upload was created |
required |
parts
|
Mapping
|
API responses received after uploading each part |
required |
Returns:
| Type | Description |
|---|---|
dict
|
API response |
Source code in hostess/aws/s3.py
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 | |
cp(source, destination=None, destination_bucket=None, config=None, **extra_args)
Copy S3 object(s) to another location on S3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Sequence[str]]
|
key(s) of object(s) to copy (fully-qualified 'path(s)') |
required |
destination
|
Union[Optional[str], Sequence[Optional[str]]]
|
key(s) to copy object(s) to (by default, uses source key(s)) |
None
|
destination_bucket
|
Optional[str]
|
bucket to copy object(s) to. if not specified, uses source bucket. this means that if destination and destination_bucket are both None, it overwrites the object inplace. this is useful for things like storage class changes. |
None
|
config
|
Optional[TransferConfig]
|
optional transfer config |
None
|
extra_args
|
str
|
ExtraArgs for boto3 bucket object |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
uri |
Union[str, list[Union[str, Exception]]]
|
S3 URI of newly-created copy, or, for multi-copy, a list containing an S3 URI for each successful copy and an Exception for each failed |
Source code in hostess/aws/s3.py
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 | |
create(name, client=None, session=None, *, bucket_type='general', az=None, tags=None, bucket_config=None, **bucket_kwargs)
classmethod
Create a new bucket on S3 and return it as a Bucket object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of bucket. If creating a directory bucket, do not
include the AZ suffix (e.g. pass "something" instead of
"something--use1-az4--x-s3"). |
required |
client
|
BaseClient | None
|
optional boto3 s3 Client. if not specified, creates a default client. |
None
|
session
|
Session
|
optional boto3 Session. if not specified, creates a default session. |
None
|
bucket_type
|
BUCKET_TYPE
|
"general" (default, meaning a general-purpose bucket) or "directory" (meaning a directory bucket). Note that this method only supports zonal directory buckets. |
'general'
|
az
|
str | int | None
|
Name, letter, ID, or number of the Availability Zone (AZ) in
which to create a directory bucket. For instance, if This argument is ignored for general-purpose buckets. Note that not all AZs support directory buckets, and there is no mechanism to discover which do and do not via the API (other than actually attempting to create one). See: https://docs.aws.amazon.com/AmazonS3/latest/userguide/endpoint-directory-buckets-AZ.html |
None
|
tags
|
dict[str, str] | None
|
Keys and values of bucket tags to set after successful bucket creation. If not None, there must be at least one item in this dict. Note that directory buckets do not support tags; this method will raise a ValueError if provided tags for a directory bucket. |
None
|
bucket_config
|
Mapping | None
|
passed to the botocore |
None
|
bucket_kwargs
|
passed directly to |
{}
|
Caution
In all regions other than us-east-1, the S3 API returns a
'bucket aready exists and is owned by you' error if a user
attempts to create a bucket with the same name as a bucket they
already own. In us-east-1, it instead returns a standard success
response and silently erases all ACLs associated with that bucket.
We are unwilling to spring this on users, and for this reason,
Bucket.create() behaves slightly differently in us-east-1. It
checks the user already owns a bucket with the requested name,
and raises an exception if so. This means that an account must
have the ListBuckets permission to use Bucket.create() in
us-east-1.
Source code in hostess/aws/s3.py
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 | |
create_multipart_upload(key)
Prepare an S3 multipart upload. Note that this is not itself an upload operation! It merely sets up an upload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
upload target key (fully-qualified 'path' from bucket root) |
required |
Returns:
| Type | Description |
|---|---|
dict
|
API response |
Source code in hostess/aws/s3.py
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 | |
delete()
Delete this bucket.
Notes
S3 will not delete a bucket that contains any objects, and
hostess does not provide a 'force'-type operation that
auto-empties a bucket before deletion.
Source code in hostess/aws/s3.py
653 654 655 656 657 658 659 660 661 662 | |
df()
Construct a manifest of all known objects in bucket as a pandas DataFrame. If update_contents() has never been called, greedily scan the contents of the bucket rather than returning an empty DataFrame.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Manifest of all known objects in bucket. |
Source code in hostess/aws/s3.py
722 723 724 725 726 727 728 729 730 731 732 733 | |
freeze(key, storage_class='DEEP_ARCHIVE')
Modify the storage class of an object or objects. Intended primarily for moving objects from S3 Standard to one of the Glacier classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Union[str, Sequence[str]]
|
object key(s) (fully-qualified 'path' relative to bucket root) |
required |
storage_class
|
str
|
target storage class |
'DEEP_ARCHIVE'
|
Returns:
| Name | Type | Description |
|---|---|---|
uri |
Union[str, list[Union[str, Exception]]]
|
URI of frozen object, or list containing URI of each frozen object if its freeze succeeded and an Exception if not |
Source code in hostess/aws/s3.py
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 | |
get(key, destination=None, config=None, start_byte=None, end_byte=None, **extra_args)
write S3 object(s) into file(s) or filelike object(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Union[str, Sequence[str]]
|
object key(s) (fully-qualified 'path(s)' from root) |
required |
destination
|
Union[Union[str, Path, IOBase, None], Sequence[Union[str, Path, IOBase, None]]]
|
where to write the retrieved object(s). May be path(s) or filelike object(s). If not specified, constructs new BytesIO buffer(s). |
None
|
config
|
Optional[TransferConfig]
|
optional transfer config |
None
|
start_byte
|
Optional[int]
|
Byte index at which to begin read. None (default) or
0 means the first byte of the object. Negative integers are
interpreted as Python-style negative slice indices. e.g.,
|
None
|
end_byte
|
Optional[int]
|
Byte index at which to end read. None (default) means the last byte of the object. |
None
|
extra_args
|
str
|
passed directly to |
{}
|
Returns: outpath: the path, string, or buffer we wrote the object to, or, for multi-get, a list containing one such outpath for each successful write and an Exception for each failed write
Caution
This does not currently support specifying different byte ranges for different objects. In other words, this is not legal:
Bucket.get(
[k1, k2], [f1, f2], start_byte=[s1, s2], end_byte=[e1, e2]
)
If specified in a multi-object call to get(), start_byte and
end_byte will fetch the same range from each object.
This may change in the future.
Source code in hostess/aws/s3.py
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 | |
head(key)
Get basic information about S3 objects in a nicely formatted dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Union[str, Sequence[str]]
|
object key(s) (fully-qualified 'path(s)' from bucket root) |
required |
Returns:
| Type | Description |
|---|---|
Union[dict[str, str], list[Union[dict[str, str], Exception]]]
|
dict containing a curated selection of object headers, or, for |
Union[dict[str, str], list[Union[dict[str, str], Exception]]]
|
a multi-object call, a list containing a dict for each |
Union[dict[str, str], list[Union[dict[str, str], Exception]]]
|
successful head and an Exception for each failed |
Source code in hostess/aws/s3.py
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 | |
ls(prefix=None, recursive=False, formatting='simple', cache=None, start_after=None, cache_only=False, fetch_owner=False)
list objects in a bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
Optional[str]
|
prefix ('folder') to list (if not specified, defaults to bucket root) |
None
|
recursive
|
bool
|
recursively list all objects in tree rooted at prefix? |
False
|
formatting
|
Literal['simple', 'contents', 'df', 'raw']
|
how to format list results * "simple": tuple containing object names only * "contents": tuple of dicts containing object names, modification times, etc. * "df": pandas DataFrame produced from contents * "raw": API response as reported by boto3 |
'simple'
|
cache
|
Union[str, Path, IOBase, None]
|
optional file or filelike object to write results to. |
None
|
start_after
|
Optional[str]
|
if specified, begin listing objects only "after" this prefix. intended principally for sequential calls. |
None
|
cache_only
|
bool
|
only write results into the specified cache; do not retain them in memory. intended mainly for cases in which the full list would be larger than available memory. |
False
|
fetch_owner
|
bool
|
if True, include owner of objects in output. Not enabled by default due to permissioning and performance issues. |
False
|
Returns:
| Type | Description |
|---|---|
Union[tuple, DataFrame, None]
|
Manifest of contents, format dependent on |
Source code in hostess/aws/s3.py
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 | |
ls_multipart()
List all multipart uploads associated with this bucket.
Returns:
| Type | Description |
|---|---|
dict
|
API response |
Source code in hostess/aws/s3.py
1548 1549 1550 1551 1552 1553 1554 1555 | |
put(obj=b'', key=None, literal_str=False, config=None, checksum=None, **extra_args)
Upload files or buffers to an S3 bucket
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Union[Puttable, Sequence[Puttable]]
|
An individual str, Path, or filelike / buffer object to upload, or a sequence of such objects |
b''
|
key
|
Optional[Union[str, Sequence[str]]]
|
S3 key (fully-qualified 'path' from bucket root); or, if |
None
|
literal_str
|
bool
|
If True, and |
False
|
config
|
Optional[TransferConfig]
|
boto3.s3.transfer.TransferConfig; bucket's default if None |
None
|
checksum
|
Optional[Union[str, Sequence[str]]]
|
Optional base64-encoded raw 4-byte CRC32 checksum of object, or sequence of such checksums for each object. Used for full-object S3 checksum verification. Other checksum types and algorithms are not supported. |
None
|
extra_args
|
str
|
ExtraArgs for boto3 bucket object |
{}
|
Returns:
| Type | Description |
|---|---|
Union[None, list[Optional[Exception]]]
|
None, or, for multi-upload, a list containing None for each successful put and an Exception for each failed one |
Source code in hostess/aws/s3.py
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 | |
put_stream(obj, key, config=None, upload_threads=4, verbose=False, explicit_length=None, chunksize=None)
Create an S3 object from a byte stream via a managed multipart upload. Intended primarily for intermittent streams, incremental writes of larger-than-memory data, direct streams from remote resources, and streams of unknown length. If you are just uploading on-disk files or discrete in-memory objects, Bucket.put() is usuallygh preferable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Union[Iterator, IO, str, Path]
|
source of stream to upload. May be a path, a URL, a filelike
object, or any iterator that yields |
required |
key
|
str
|
key of object to create from stream (fully-qualified 'path' relative to bucket root) |
required |
config
|
Optional[TransferConfig]
|
optional transfer config |
None
|
upload_threads
|
Optional[int]
|
number of subprocesses to use for upload (None means upload serially) |
4
|
verbose
|
bool
|
print and log progress of streaming upload |
False
|
explicit_length
|
Optional[int]
|
optional explicit length specification, for streams of known length |
None
|
chunksize
|
Optional[int]
|
size of individual upload chunks; overrides any setting in config. if stream length is explicitly specified or inferred to be less than chunksize, this function will fall back to a simple put operation. |
None
|
Returns:
| Type | Description |
|---|---|
Optional[dict]
|
API response to multipart upload completion, or None if stream length < chunksize and we fell back to simple upload |
Source code in hostess/aws/s3.py
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 | |
read(key, mode='r', return_buffer=False, start_byte=None, end_byte=None)
Read an S3 object into memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
fully-qualified 'path' to object |
required |
mode
|
Literal['r', 'rb']
|
'r' to read as text, 'rb' as bytes |
'r'
|
return_buffer
|
bool
|
if True, return object as a StringIO/BytesIO; if False, return it as str/bytes |
False
|
start_byte
|
Optional[int]
|
if not None, start reading at this byte |
None
|
end_byte
|
Optional[int]
|
if not None, stop reading at this byte |
None
|
Returns:
| Type | Description |
|---|---|
Union[bytes, str, BytesIO, StringIO]
|
Contents of object, in format specified by |
Source code in hostess/aws/s3.py
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 | |
restore(key, tier='Bulk', days=5)
Issue a request to temporarily restore one or more objects from S3 Glacier Flexible Retrival or Deep Archive to S3 Standard. Note that object restoration is not instantaneous. Depending on retrieval tier and storage class, AWS guarantees retrieval times ranging from 5 minutes to 48 hours. See https://docs.aws.amazon.com/AmazonS3/latest /userguide/restoring-objects-retrieval-options.html for details.
You can check the progress of restore requests using Bucket.head().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Union[str, Sequence[str]]
|
key(s) of object(s) to restore (fully-qualified 'paths') |
required |
tier
|
Literal['Expedited', 'Standard', 'Bulk']
|
retrieval tier. In order of speed and expense, high to low, options are "Expedited", "Standard", and "Bulk". "Expedited" is not available for Deep Archive. |
'Bulk'
|
days
|
int
|
number of days object(s) should remain restored before reverting to Glaciered state |
5
|
Returns:
| Type | Description |
|---|---|
Union[dict, list[Union[dict, Exception]]]
|
RestoreObject API response, or list of responses and/or Exceptions |
Source code in hostess/aws/s3.py
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 | |
rm(key)
Delete an S3 object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
key of object to delete (fully-qualified 'path' from root) |
required |
Returns:
| Type | Description |
|---|---|
Union[None, list[Optional[None]]]
|
None, or, for multi-delete, a list containing None for successful deletes and Exceptions for failed |
Source code in hostess/aws/s3.py
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 | |
set_tags(*, replace_all=False, **tags)
Set tags for this bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
replace_all
|
bool
|
if True, removes all existing tags along with
setting passed tag values (this is the default behavior of the
PutBucketTagging API operation). If False, leaves existing
tags unchanged unless they are redefined in |
False
|
**tags
|
str
|
Argument names are tag keys; argument values are tag values. At least one tag must be defined. |
{}
|
Returns:
| Type | Description |
|---|---|
|
API response for PutBucketTagging operation. |
Source code in hostess/aws/s3.py
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 | |
tail(key, destination, start_pos=None, poll=1, text_mode=True, permit_missing=False)
Provides asynchronous tail -f-like functionality for S3 objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
object key (fully-qualified 'path' from root) |
required |
destination
|
MutableSequence | BinaryIO | TextIO | IOBase | Path | str
|
where to write the tail chunks. If a sequence, appends each chunk as a new item. |
required |
start_pos
|
int | None
|
start reading from where? If None, start at the length
of the object when |
None
|
poll
|
float
|
poll rate in seconds |
1
|
text_mode
|
bool
|
if True, decode each chunk as utf-8 text |
True
|
permit_missing
|
bool
|
if True, don't raise an error if the object doesn't exist; instead, periodically check to see if the object comes into existence, and if it does, start tailing it. |
False
|
Returns:
| Type | Description |
|---|---|
|
A |
Notes
Exclusive of egress costs, running this for a full day at the default 1-second poll rate on a single S3 Standard object costs approximately $0.07. On a SEOZ object, it costs approximately $0.005. Egress costs in this application should be equal to egress for (size of object when tailing ends) minus (the smaller of start_pos or size of object when tailing starts)
Source code in hostess/aws/s3.py
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 | |
update_contents(prefix=None, cache=None, fetch_owner=False)
recursively scan the contents of the bucket and store the result in self.contents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
Optional[str]
|
prefix at which to begin scan. if not passed, scans the entire bucket. |
None
|
cache
|
Optional[Union[str, Path, IOBase]]
|
optional file or filelike object to write scan results to in addition to storing them in self.contents. |
None
|
fetch_owner
|
bool
|
if True, include owner of objects in response. |
False
|
Source code in hostess/aws/s3.py
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 | |
_clean_putter_process_records(records, block=True, threshold=1, poll_delay=0.05)
helper function for multithreaded put_stream()
Source code in hostess/aws/s3.py
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 | |
_dtstr(thing)
convert thing to its isoformat() if it's a datetime, otherwise return its string representation. helper function for Bucket.ls() in cached mode.
Source code in hostess/aws/s3.py
480 481 482 483 484 485 486 487 | |
check_az(az, region_name)
Validate existence of an AvailabilityZone in a particular region, and return its canonical Zone ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
az
|
str | int
|
identifier for Availability Zone. May be its Zone Name, Zone ID, number, or letter. |
required |
region_name
|
str
|
canonical, unabbreviated region name (e.g. 'us-east-1') |
required |
Returns:
| Type | Description |
|---|---|
|
Unabbreviated Zone ID for referenced Availability Zone. |
Source code in hostess/aws/s3.py
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 | |
split_optional_kwargs(bound, splittable, split_len)
Remove splittable kwargs from bound and return an iterator of per-call kwarg patches.
Scalar values repeat. Sequence values split item-by-item. Missing values remain missing, so normal defaults still work.
Source code in hostess/aws/s3.py
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 | |
splitwrap(*, seq_arity, splittable=())
splitwrap(*, seq_arity: Literal[1], splittable: Iterable[str] = ()) -> Callable[[BMethOne], BMethOneList]
splitwrap(*, seq_arity: Literal[2], splittable: Iterable[str] = ()) -> Callable[[BMethTwo], BMethTwoList]
Decorator for methods of Bucket that permits them to accept either single source and/or destination arguments or sequences of them. Automatically maps sequences into a thread pool, unless instructed to run serially, and returns all results in a list. Fails gracefully, returning Exceptions raised by any individual function call rather than raising them.
Extra named arguments listed in splittable may be either scalar or sequence. Scalars are repeated for every split call. Sequences are split item-by-item.
Source code in hostess/aws/s3.py
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 | |
aws.utilities
_check_cached_results(path, prefix, max_age=5)
check for a 'fresh' cached API call by string-matching against filename prefix and our standardized in-filename timestamp format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
path to check for results |
required |
prefix
|
str
|
filename prefix for results |
required |
max_age
|
float
|
age, in days, after which a result is no longer 'fresh' |
5
|
Returns:
| Type | Description |
|---|---|
Optional[Path]
|
Path for first matching result, if it is 'fresh'. None if it is not fresh or there is no matching result. |
Source code in hostess/aws/utilities.py
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 | |
_clear_cached_results(folder, pre)
quick way to delete all files in folder whose names begin with pre.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder
|
Path
|
folder to clear. |
required |
pre
|
str
|
filename prefix that triggers deletion. |
required |
Source code in hostess/aws/utilities.py
406 407 408 409 410 411 412 413 414 415 | |
autopage(client, operation, agg=None, **api_kwargs)
Perform an AWS API call that returns paginated results, greedily page through all of them, and return the aggregated results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
BaseClient
|
boto Client object to make API call |
required |
operation
|
str
|
name of API call to perform |
required |
agg
|
Optional[Union[str, Sequence[str], Callable]]
|
optional special aggregator. If |
None
|
**api_kwargs
|
Any
|
kwargs to pass to the API call. |
{}
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of aggregated responses, format depending on |
Source code in hostess/aws/utilities.py
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 | |
clarify_region(region=None, boto_obj=None)
attempt to determine the AWS region associated with an object (presumably some kind of boto object).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
region
|
Optional[str]
|
if not None, this acts as a strict override: the function
simply returns |
None
|
boto_obj
|
Any
|
object whose AWS region to determine. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
name of AWS region (e.g. 'us-east-2'). |
Raises:
| Type | Description |
|---|---|
AttributeError
|
if |
Source code in hostess/aws/utilities.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
crc32_base64(path)
Checksum a file the way S3 likes: base64-encoded 32-bit CRC32 bytes, MSB.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[Path, str]
|
Path to file to checksum. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Base64-encoded raw CRC32 bytes, suitable for passing as |
str
|
|
Source code in hostess/aws/utilities.py
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | |
init_client(service, client=None, session=None, **client_kwargs)
Utility function used throughout hostess.aws to selectively initialize
boto clients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service
|
str
|
service to produce client for (e.g. "ec2") |
required |
client
|
Optional[BaseClient]
|
if not None, simply return |
None
|
session
|
Optional[Session]
|
if not None and |
None
|
client_kwargs
|
passed to make_boto_client() or boto client constructor |
{}
|
Returns:
| Type | Description |
|---|---|
BaseClient
|
boto client for |
Source code in hostess/aws/utilities.py
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 | |
init_resource(service, resource=None, session=None)
Utility function used throughout hostess.aws to selectively initialize
boto resources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service
|
str
|
service to produce resource for (e.g. "ec2") |
required |
resource
|
Optional[ServiceResource]
|
if not None, simply return |
None
|
session
|
Optional[Session]
|
if not None and |
None
|
Returns:
| Type | Description |
|---|---|
ServiceResource
|
boto resource for |
Source code in hostess/aws/utilities.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
make_boto_client(service, profile=None, credential_file=None, region=None, **client_kwargs)
Create a new boto client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service
|
str
|
service to create client for, e.g. "ec2" |
required |
profile
|
Optional[str]
|
optional name of AWS profile to use (default profile if not specified) |
None
|
credential_file
|
Optional[Union[str, Path]]
|
optional path to credential file (looks in default credential path if not specified) |
None
|
region
|
Optional[str]
|
optional name of AWS region, e.g. "us-east-1". (uses profile's default region if not specified) |
None
|
client_kwargs
|
passed directly to botocore client constructor |
{}
|
Returns:
| Type | Description |
|---|---|
BaseClient
|
boto client for service. |
Source code in hostess/aws/utilities.py
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 | |
make_boto_resource(service, profile=None, credential_file=None, region=None, **resource_kwargs)
Create a new boto resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service
|
str
|
service to create resource for, e.g. "ec2" |
required |
profile
|
Optional[str]
|
optional name of AWS profile to use (default profile if not specified) |
None
|
credential_file
|
Optional[Union[str, Path]]
|
optional path to credential file (looks in default credential path if not specified) |
None
|
region
|
Optional[str]
|
optional name of AWS region, e.g. "us-east-1". (uses profile's default region if not specified) |
None
|
resource_kwargs
|
passed directly to boto resource constructor |
{}
|
Returns:
| Type | Description |
|---|---|
ServiceResource
|
boto resource for service. |
Source code in hostess/aws/utilities.py
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 | |
make_boto_session(profile=None, credential_file=None, region=None, **session_kwargs)
Create a new boto session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profile
|
Optional[str]
|
name of AWS profile to use (default profile if not specified) |
None
|
credential_file
|
Optional[Union[str, Path]]
|
path to credential file (looks in default credential path if not specified) |
None
|
region
|
Optional[str]
|
name of AWS region, e.g. "us-east-1". (uses profile's default region if not specified) |
None
|
session_kwargs
|
passed directly to botocore Session constructor |
{}
|
Returns:
| Type | Description |
|---|---|
Session
|
boto session. |
Source code in hostess/aws/utilities.py
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 | |
parse_aws_identity_file(path, profile=None)
Parse an AWS config, credentials, or downloaded IAM secrets file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
path to file |
required |
profile
|
Optional[str]
|
if specified, look for settings for this profile specifically. Otherwise, use the first profile in the file. Ignored if file appears to be an IAM secrets file. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
|
Raises:
| Type | Description |
|---|---|
OSError
|
if |
Source code in hostess/aws/utilities.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
tagfilter(description, filters, regex=True)
Simple predicate function that permits resource matching based on Arrays of Tags in API responses related to that resource. See https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Tag.html.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
description
|
dict[str, Any]
|
dict produced from an AWS API response. |
required |
filters
|
dict[str, str]
|
dict of {tag_name: tag_value}. All tag names must be present, and their values must match the associated tag_values. |
required |
regex
|
bool
|
if True, treat the values of |
True
|
Returns:
| Type | Description |
|---|---|
bool
|
True if all filters pass; False if any fail. Note that a filter will always fail if the API response lacks a Tags/tags array, but also that this function will always return True if filters has length 0. |
Source code in hostess/aws/utilities.py
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 | |
whoami(client=None, session=None)
Make an STS GetCallerIdentity request and return just the essentials from the response.
Note that every AWS account is allowed to make this request: attempts to deny access to the sts:GetCallerIdentity action don't do anything. That means that if other AWS operations are failing, you can call this function to rule out a couple of very basic failure modes. If it fails, it means that either your credentials for the account are invalid or you can't connect to AWS at all (your network is down or blocking access to the API endpoint).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Optional[BaseClient]
|
optional STS client. |
None
|
session
|
Optional[Session]
|
optional boto Session. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
|
Source code in hostess/aws/utilities.py
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 | |
caller
ad-hoc RPC functionality
CallerCompressionType = Literal['gzip', None]
module-attribute
code for payload compression method
CallerSerializationType = Literal['json', 'pickle', None]
module-attribute
code for payload serialization method
CallerUnpackingOperator = Literal['', '*', '**']
module-attribute
string representation of unpacking operator, if any, used to insert reconstructed payload into called function
_check_mode(serialization, compression)
should we think of our output as in text or binary mode?
Source code in hostess/caller.py
208 209 210 211 212 213 214 | |
_check_reconstructable(typeobj, serialization, compression)
Raise an error if we are attempting to transfer a compressed, unserialized in-memory object with no stable binary representation, which is, for our purposes, anything but a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
typeobj
|
type
|
type of payload object |
required |
serialization
|
CallerSerializationType
|
name of serialization method used |
required |
compression
|
CallerCompressionType
|
name of compression method used |
required |
Source code in hostess/caller.py
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 | |
encode_payload(obj, serialization, compression, b64)
encode the 'payload' of a remote procedure call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
object to encode |
required |
serialization
|
CallerSerializationType
|
serialization method for obj |
required |
compression
|
CallerCompressionType
|
how to compress the serialized object (None means uncompressed) |
required |
b64
|
bool
|
base64-encode 'binary' objects? |
required |
Returns:
| Type | Description |
|---|---|
Union[str, bytes]
|
string or bytes containing encoded payload. |
Source code in hostess/caller.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
format_decompressor(serialized, serialization, compression, b64)
create decompression section of RPC script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
serialized
|
Union[str, bytes]
|
serialized payload |
required |
serialization
|
CallerSerializationType
|
name of serialization method used |
required |
compression
|
CallerCompressionType
|
name of compression method used |
required |
b64
|
bool
|
are we expecting a base64-encoded payload? |
required |
Returns:
| Type | Description |
|---|---|
str
|
decompression source code block |
Source code in hostess/caller.py
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 | |
format_deserializer(serialization)
create deserialization section of RPC script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
serialization
|
CallerSerializationType
|
serialization method used |
required |
Returns:
| Type | Description |
|---|---|
str
|
deserialization source code block |
Source code in hostess/caller.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
format_importer(module, func)
formatting function for import section of RPC script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Optional[str]
|
name of or path to module |
required |
func
|
str
|
name of function in module |
required |
Returns:
| Type | Description |
|---|---|
str
|
import source code block |
Source code in hostess/caller.py
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 | |
format_kwarg_filter(filter_kwargs, splat)
generate kwarg filter section of RPC script, if necessary and requested
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filter_kwargs
|
bool
|
should we filter unwanted kwargs or not? |
required |
splat
|
CallerUnpackingOperator
|
unpacking operator we're using. if it's not '**', never generate this block -- it's unnecessary. |
required |
Returns:
| Type | Description |
|---|---|
str
|
kwarg-filtering source code block. |
Source code in hostess/caller.py
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
format_returner(return_result, return_compression, return_serialization, b64, sep)
format return section of RPC script.
Source code in hostess/caller.py
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 | |
generic_python_endpoint(module, func=None, payload=None, *, compression=None, serialization=None, splat='', payload_encoded=False, return_result=True, filter_kwargs=False, interpreter=None, for_bash=True, literal_none=False, return_serialization=None, return_compression=None, b64=True, sep=None)
dynamically construct a Python source code snippet that imports a module and calls a function from it with a given 'payload' (effectively, an argument or arguments, possibly in serialized and/or compressed form). by default, wrap it in a shell script that executes the snippet from bash. this can be used to perform remote procedure calls, inject code into existing applications, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
str
|
name of, or path to, the target module |
required |
func
|
Optional[str]
|
name of the function to call. must be a member of the target
module (or explicitly imported by that module). If not specified,
the generated code simply imports |
None
|
payload
|
Any
|
object from which to construct func's call arguments. In many
cases, this can simply be a Python object or objects you'd like
to pass to |
None
|
compression
|
CallerCompressionType
|
how to compress the payload. 'gzip' or None. 'gzip' is good for jamming larger payloads into a shell command without breaking the shell. |
None
|
serialization
|
CallerSerializationType
|
how to serialize |
None
|
splat
|
CallerUnpackingOperator
|
Operator for splatting |
''
|
payload_encoded
|
bool
|
set to True if you have already serialized and/or compressed the payload using the specified methods, so the generated script should decode it, but this function should not re-encode it. |
False
|
return_result
|
bool
|
if True, the generated script also prints the return
value of the called function to stdout, with encoding and
compression specified by |
True
|
filter_kwargs
|
bool
|
if True, the generated script will attempt to filter
func-inappropriate kwargs from the payload. Not guaranteed to work
on functions with complex signatures. Does nothing if
|
False
|
interpreter
|
Optional[str]
|
path to Python interpreter that should be specified in
the shell command. can either be a fully-qualified path or
any name you expect to be on the calling user's $PATH -- e.g., if
you expect there to be a system Python and want to use it, just
'python'. If None, assume the path to the desired interpreter is
the same as the path to the interpreter that is running this
function. Does nothing if |
None
|
for_bash
|
bool
|
if True (the default), return a bash command that runs the Python script in the specified interpreter. otherwise, simply return the generated script. |
True
|
literal_none
|
bool
|
if False (the default), interpret |
False
|
return_serialization
|
CallerSerializationType
|
serialization for return value. does nothing if
|
None
|
return_compression
|
CallerCompressionType
|
compression for return value. does nothing if
|
None
|
b64
|
bool
|
if True, base64-encode any 'binary' values. For insertion into
|
True
|
sep
|
Optional[str]
|
if not None, generated script prints this string prior to printing the return value, to facilitate parsing return values from scripts that might generate other output while running. |
None
|
Returns:
Bash command that executes function call in specified interpreter,
or, if for_bash is False, just Python source code for function call.
Source code in hostess/caller.py
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 | |
make_python_endpoint_factory(module, func=None, **endpoint_kwargs)
factory function for endpoint factory functions. use this to create callables that generate shell scripts that call either a specific Python function or Python functions from a specific named module, using specific application-correct configurations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
str
|
name of, or path to, module to use as quasi-namespace of endpoint factory. |
required |
func
|
Optional[str]
|
optional name of function from module. If this is None, the returned function can be used to call any function from module. |
None
|
endpoint_kwargs
|
Union[bool, str, CallerCompressionType, CallerSerializationType, CallerUnpackingOperator]
|
kwargs to partially evaluate / bind to the endpoint factory. see generic_python_endpoint() for a full description of options. |
{}
|
Returns:
| Type | Description |
|---|---|
Union[Callable[[str, Any], str], Callable[[Any], str]]
|
a function that, when called, produces shell scripts. If the |
Source code in hostess/caller.py
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 | |
to_heredoc(heredoc_content, addition='', identifier='__BOUNDARYTAG__')
create a bash heredoc statement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
heredoc_content
|
str
|
content of the heredoc. |
required |
addition
|
str
|
optional additional statement between heredoc identifier and body |
''
|
identifier
|
str
|
heredoc delimiting identifier. |
'__BOUNDARYTAG__'
|
Returns:
| Type | Description |
|---|---|
str
|
bash heredoc statement. |
Source code in hostess/caller.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
config
config.config
config.user_config
settings in this module override settings in config.py, and may also be used to define settings that do not exist in config.py, none of which are currently imagined.
directory
utilities for indexing and summarizing filesystems
LSFrame = pd.DataFrame
module-attribute
DataFrame suitable for use by several functions in this module. typically produced by calling the DataFrame constructor on a list of LSRecords.
LSRecord = dict[str, Union[str, float, bool, dt.datetime]]
module-attribute
a record containing identifying information about a file. produced by
lsdashl and used by other functions in this module. has keys:
- "path": str (string version of relative path)
- "size": float (file size in MB, rounded to 3 places)
- "excluded": bool (placeholder for exclusions, always False)
- "directory": bool (is it a directory?)
- "suffix": str (last filename suffix)
- "atime", "mtime", "ctime": datetime (UNIX file times)
TreeFrame = pd.DataFrame
module-attribute
DataFrame containing hierarchical 'tree' information. Produced by calling
make_treeframe on an LSFrame.
_make_levelframe(group, squish)
helper function for make_treeframe()
Source code in hostess/directory.py
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
_parse_fileinfo(magic_viewer)
parses stdout from the POSIX file utility.
Source code in hostess/directory.py
140 141 142 143 144 145 146 147 148 149 150 | |
_squishlevels(join, levels)
helper function for _make_levelframe()
Source code in hostess/directory.py
185 186 187 188 189 190 191 192 193 | |
check_inclusion(record, skip_directories=())
simple prefiltering function. sets an LSRecord's "excluded" value to True
if the record represents a directory and the directory name matches any
of the regex patterns in skip_directories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
LSRecord
|
record to prefilter |
required |
skip_directories
|
Collection[Union[str, Pattern]]
|
list of regex expressions that define exclusions |
()
|
Source code in hostess/directory.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | |
do_magic(manifest, log=zero)
Adds 'magic' info from the POSIX file utility to a DataFrame of
file / directory listings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
LSFrame
|
dataframe of file information, probably produced via
|
required |
log
|
Callable[[str], Any]
|
logger function (by default just throws log info away) |
zero
|
Returns:
| Type | Description |
|---|---|
LSFrame
|
|
Source code in hostess/directory.py
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 | |
index_breadth_first(root)
Recursively index all directories under root.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
Union[str, Path]
|
top directory of index |
required |
Returns:
| Type | Description |
|---|---|
list[LSRecord]
|
list of LSRecords describing contents of all directories under and
including |
Source code in hostess/directory.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
lsdashl(directory, include_directories=True)
a kind of ls -l. returns a list of records containing identifying
information about the contents of directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
Union[str, Path]
|
directory to list |
required |
include_directories
|
bool
|
include or omit subdirectories |
True
|
Source code in hostess/directory.py
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 | |
make_level_table(treeframe)
Make a DataFrame of summary information about directory sizes, file count, etc. from a TreeFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
treeframe
|
TreeFrame
|
dataframe containing path information created using
|
required |
Source code in hostess/directory.py
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | |
make_treeframe(manifest, squish=False)
Takes a DataFrame of file and directory listings and produces a new DataFrame with additional columns representing hierarchical components of the contents' paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
LSFrame
|
file/directory DataFrame |
required |
squish
|
bool
|
squish levels together in output? |
False
|
Source code in hostess/directory.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | |
mtimes(stat)
Formats filesystem timestamps into a dictionary of datetimes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stat
|
stat_result
|
os.stat_result object (typically from |
required |
Returns:
| Type | Description |
|---|---|
dict[str, datetime]
|
dictionary whose values are datetimes and whose keys are 'atime', 'mtime', and 'ctime'. |
Source code in hostess/directory.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | |
monitors
tracking, logging, and synchronization objects
DEFAULT_TICKER = Ticker()
module-attribute
convenient shared Ticker
AbstractMonitor
Bases: ABC
base monitor class
Source code in hostess/monitors.py
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 | |
__init__(*, digits=None, qualities=None, instrument=constant(0), formatter=identity, name=None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
digits
|
Optional[int]
|
number of digits to round output to. if None, don't round. |
None
|
qualities
|
Optional[Mapping[str, str]]
|
dictionary of subtypes of monitored quantity. if None, the Monitor only measures one thing. |
None
|
instrument
|
Callable[[], Union[float, int, Mapping]]
|
function used to perform monitoring. |
constant(0)
|
formatter
|
Callable[[float], float]
|
function used to format |
identity
|
name
|
Optional[str]
|
default name of the monitor. |
None
|
Source code in hostess/monitors.py
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 | |
_display_plural(register, which)
internal formatting function
Source code in hostess/monitors.py
276 277 278 279 280 281 282 | |
_display_simple(_which)
internal formatting function
Source code in hostess/monitors.py
266 267 268 269 270 | |
_display_single(value, which)
internal formatting function
Source code in hostess/monitors.py
272 273 274 | |
_round(val)
round a measurement if set to do so.
Source code in hostess/monitors.py
178 179 180 181 182 183 184 | |
_unpack_reading(reading)
unpack an instrument reading. for monitors with multiple qualities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reading
|
Union[tuple, Mapping]
|
a named tuple or a Mapping containing measurements for various qualities. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
formatted dictionary of readings for each quality |
Source code in hostess/monitors.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
_update_plural(reading, lap)
update registers for each quality from a reading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reading
|
Union[tuple, Mapping]
|
instrument output |
required |
lap
|
bool
|
record this as a 'lap/split' (i.e., reset interval)? |
required |
Source code in hostess/monitors.py
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 | |
_update_single(reading, lap)
update registers from a reading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reading
|
float
|
instrument output |
required |
lap
|
bool
|
record this as a 'lap/split' (i.e., reset interval)? |
required |
Source code in hostess/monitors.py
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | |
click()
shorthand for self.update(True)
Source code in hostess/monitors.py
344 345 346 | |
clickpeek(which=None, say=False, simple=False)
click the lap button and look at the monitor. managed shorthand for self.update(True) followed by self.display().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
which
|
Optional[str]
|
register to look at (default default_click, "all" for all) |
None
|
say
|
bool
|
include name of register in output? |
False
|
simple
|
bool
|
format output tersely? |
False
|
Source code in hostess/monitors.py
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | |
display(which=None, say=False, simple=False)
return string displaying the contents of one or all registers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
which
|
str
|
which register to print, or "all" for all. None prints register defined in self.default_display |
None
|
say
|
bool
|
include name of register in output? |
False
|
simple
|
bool
|
format output tersely? |
False
|
Source code in hostess/monitors.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
pause()
pause the monitor.
Source code in hostess/monitors.py
392 393 394 395 | |
peek(which=None, say=False, simple=False)
peek at one or all registers. managed shorthand for self.update() followed by self.display().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
which
|
Optional[str]
|
which register (default self.default_click, "all" for all) |
None
|
say
|
bool
|
include name of register in output? |
False
|
simple
|
bool
|
format output tersely? |
False
|
Source code in hostess/monitors.py
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
rec(which=None)
return value of one or all registers in numeric form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
which
|
Optional[str]
|
name of register. self.default_display by default. "all" for all. |
None
|
Source code in hostess/monitors.py
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
restart()
restart the monitor.
Source code in hostess/monitors.py
397 398 399 | |
start(restart=False)
start the monitor. unpauses if monitor is paused.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
restart
|
bool
|
if monitor is already started, restart it, clearing all entries? |
False
|
Source code in hostess/monitors.py
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | |
update(lap=False)
update the monitor, starting it if necessary. ignored if monitor is paused.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lap
|
bool
|
record this update as a 'lap/split' (i.e., reset interval)? |
False
|
Source code in hostess/monitors.py
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | |
Bouncer
Bases: FakeBouncer
simple blocking rate-limiter.
Source code in hostess/monitors.py
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 | |
__init__(ratelimit=0.1, window=1, blockdelay=None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ratelimit
|
float
|
how many events to permit within a single window |
0.1
|
window
|
float
|
size of window in seconds |
1
|
blockdelay
|
Optional[float]
|
poll rate when blocking (default window/ratelimit) |
None
|
Source code in hostess/monitors.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | |
block()
block until there are now longer too many events within window
Source code in hostess/monitors.py
87 88 89 90 91 92 | |
clean()
clean the list of events
Source code in hostess/monitors.py
80 81 82 83 84 85 | |
click(block=True)
record an event; optionally block
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
bool
|
if True, call block() after recording event |
True
|
Source code in hostess/monitors.py
94 95 96 97 98 99 100 101 102 103 104 105 | |
CPU
Bases: AbstractMonitor
simple CPU monitoring device
Source code in hostess/monitors.py
438 439 440 441 442 443 444 445 446 447 448 449 | |
CPUTime
Bases: AbstractMonitor
simple CPU time monitoring device
Source code in hostess/monitors.py
452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
DiskIO
Bases: AbstractMonitor
simple Disk io monitor
Source code in hostess/monitors.py
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | |
FakeBouncer
fake blocking rate-limiter. Placeholder for a Bouncer in functions that
don't actually want to debounce.
Source code in hostess/monitors.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
Load
Bases: AbstractMonitor
simple CPU load monitoring device
Source code in hostess/monitors.py
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 | |
LogMB
simple text logger/printer for aggregate data volume
Source code in hostess/monitors.py
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 | |
__call__(bytes_amount)
Record a write/transfer/whatever. If this causes running volume to cross a multiple of self._threshold, print and log the running volume.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bytes_amount
|
int
|
number of bytes just written/transferred |
required |
Source code in hostess/monitors.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
__init__(threshold_mb=25)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold_mb
|
float
|
at what interval of MB to log/print |
25
|
Source code in hostess/monitors.py
111 112 113 114 115 116 117 118 119 120 | |
NetworkIO
Bases: AbstractMonitor
simple network I/O monitor
Source code in hostess/monitors.py
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | |
RAM
Bases: AbstractMonitor
simple memory monitoring device
Source code in hostess/monitors.py
426 427 428 429 430 431 432 433 434 435 | |
Recorder
wrapper class for arbitrary callable. makes its interface compatible
with make_stat_records().
Source code in hostess/monitors.py
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 | |
Stopwatch
Bases: AbstractMonitor
simple timekeeping device
Source code in hostess/monitors.py
415 416 417 418 419 420 421 422 423 | |
TimeSwitcher
little object that tracks changing times
Source code in hostess/monitors.py
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 | |
__init__(start_time=None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_time
|
Optional[str]
|
optional start time for the timer, in any format recognized by dateutil. |
None
|
Source code in hostess/monitors.py
694 695 696 697 698 699 700 701 702 703 | |
check_time(string)
if the passed value is parseable as a time, append it to self.times.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string
|
str
|
stringified time (maybe) |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if |
Source code in hostess/monitors.py
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 | |
Usage
Bases: AbstractMonitor
simple disk usage monitor
Source code in hostess/monitors.py
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 | |
__init__(*, digits=3, path='/')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
digits
|
Optional[int]
|
number of digits (as in AbstractMonitor) |
3
|
path
|
Union[str, Path]
|
root directory to monitor |
'/'
|
Source code in hostess/monitors.py
471 472 473 474 475 476 477 478 479 480 481 482 | |
log_factory(stamper, stat, log_fields, logfile)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stamper
|
Callable[[], Any]
|
line identifier function (i.e., a timestamper) |
required |
stat
|
Callable[[], Any]
|
statistic-generating function |
required |
log_fields
|
Sequence[str]
|
expected kwargs to log function -- this provides an ordering for columns in the output CSV |
required |
logfile
|
Union[str, Path]
|
where to write the log |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Any, ...], None]
|
a function that, when called, creates, prints, and writes a comma-separated log line. |
Source code in hostess/monitors.py
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 | |
make_monitors(*, digits=3)
make a default set of monitors
Source code in hostess/monitors.py
543 544 545 546 547 548 549 550 551 552 553 | |
make_stat_printer(monitors)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
monitors
|
Mapping[str, AbstractMonitor]
|
dictionary of AbstractMonitors |
required |
Returns:
| Type | Description |
|---|---|
Callable[[bool, bool, Any, ...], Union[str, Mapping[str, AbstractMonitor]]]
|
a function that holds when called, and if |
Source code in hostess/monitors.py
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 | |
make_stat_records(monitors)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
monitors
|
MutableMapping[str, Union[AbstractMonitor, Callable[[Any, ...], float]]]
|
dictionary of AbstractMonitors and/or functions that return floats. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[bool, bool, Any, ...], Union[Mapping[str, Union[AbstractMonitor, Recorder]], dict[str, Union[dict, float]]]]
|
a stat-recording function that works much the function produced by
|
Source code in hostess/monitors.py
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 | |
memory()
alias for psutil.Process().memory_info().rss
Returns:
| Type | Description |
|---|---|
int
|
current process's real set size in bytes |
Source code in hostess/monitors.py
27 28 29 30 31 32 33 34 | |
ticked(func, label, ticker)
Modify func so that it records a tick on ticker whenever it's called. To use with @ syntax, do something like:
@ticked(label='login', ticker=DEFAULT_TICKER)
def handle_login(...
Args: func: function to modify label: label to use for tick ticker: Ticker to tick
Returns:
| Type | Description |
|---|---|
Callable
|
modified version of |
Source code in hostess/monitors.py
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 | |
profilers
profiling and introspection utilities
DEFAULT_PROFILER = Profiler({'time': Stopwatch()})
module-attribute
convenient shared Profiler that measures execution times for code blocks.
IdentifyResult = dict[str, Union[int, type, str]]
module-attribute
record representing information about a Python object, as produced by
identify and functions that call it.
ScopeName = Literal['locals', 'globals', 'builtins']
module-attribute
string that gives the name of a Python scope, not including enclosing/nonlocal scope.
PContext
simple context manager for profiling. typically instantiated via a Profiler's context() method, though this is not mandatory.
Source code in hostess/profilers.py
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 | |
__init__(profiler, label='')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profiler
|
Profiler
|
associated Profiler; readings generated by this PContext will be stored in that Profiler's labels data structure. |
required |
label
|
str
|
optional label for this PContext's profiling results. |
''
|
Source code in hostess/profilers.py
139 140 141 142 143 144 145 146 147 | |
_save_reading(monitor, reading)
internal function called on context block exit. saves profiling results to the associated Profiler.
Source code in hostess/profilers.py
159 160 161 162 163 164 165 166 167 168 | |
Profiler
simple profiling object for specific sections of code.
Examples:
>>> from array import array
>>> from hostess.monitors import RAM, Stopwatch
>>> from hostess.profilers import Profiler
>>> prof = Profiler({'time': Stopwatch(), 'memory': RAM()})
>>> with prof.context("f"):
>>> var1 = array("B", [0 for _ in range(1024**2 * 100)])
>>> with prof.context("g"):
>>> var2 = array("B", [0 for _ in range(1024**2 * 250)])
>>> print(prof)
general form of expected output (exact results are system-dependent):
Profiler
f
time: 2.935
memory: 105.47
g
time: 7.171
memory: 261.76
Source code in hostess/profilers.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
__init__(monitors)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
monitors
|
MutableMapping[str, AbstractMonitor]
|
dictionary of AbstractMonitor objects (see hostess.monitors for examples) |
required |
Source code in hostess/profilers.py
66 67 68 69 70 71 72 73 74 75 76 77 | |
_newcaches()
internal data structure initialization function.
Source code in hostess/profilers.py
109 110 111 112 113 114 115 116 117 | |
context(label='')
create a context manager that profiles a section of code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
label for the code section, possibly shared between multiple sections. useful when it is desirable to distinguish specific steps of a pipeline, 'categories' of activity, etc. |
''
|
Source code in hostess/profilers.py
94 95 96 97 98 99 100 101 102 103 | |
pause()
pause all the monitors.
Source code in hostess/profilers.py
84 85 86 87 | |
reset()
clear this Profiler, removing all existing readings.
Source code in hostess/profilers.py
105 106 107 | |
restart()
restart all the monitors.
Source code in hostess/profilers.py
89 90 91 92 | |
start()
start all the monitors.
Source code in hostess/profilers.py
79 80 81 82 | |
RefAlarm
Simple reference / dereference alarm.
Source code in hostess/profilers.py
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 | |
__init__(getstack=False, verbosity='print', warn_new=False, ignore_dunder=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
getstack
|
bool
|
if True, check entire stack above frame that initializes self.context(); if False, just that frame |
False
|
verbosity
|
Literal['warn', 'print', 'quiet']
|
"warn" means issue RefAlarmWarnings; "print" means
call |
'print'
|
warn_new
|
bool
|
warn / print newly-assigned variables? does nothing
if |
False
|
ignore_dunder
|
bool
|
ignore variables with "dunder" names? |
True
|
Source code in hostess/profilers.py
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 | |
context(name='default')
Produce a context manager related to this object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
name for this context, used for verbose reports and
|
'default'
|
Returns:
| Type | Description |
|---|---|
_RefAlarmContext
|
A |
Source code in hostess/profilers.py
825 826 827 828 829 830 831 832 833 834 835 836 | |
receive_context_report(results, name)
receive a context report. called by _RefAlarmContexts produced
by this object's context() method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
list[dict]
|
|
required |
name
|
str
|
name of context |
required |
Source code in hostess/profilers.py
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 | |
RefAlarmWarning
Bases: UserWarning
warning issued by RefAlarms with "warn" verbosity
Source code in hostess/profilers.py
753 754 | |
_RefAlarmContext
context manager for reference counting. should be initialized only by RefAlarm.context().
Source code in hostess/profilers.py
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 | |
_add_varnames(obj, sdict, rec, scopename)
helper function for yclept(). creates records describing the variables in a given scope.
Source code in hostess/profilers.py
419 420 421 422 423 424 425 426 427 | |
_filter_history(refs, globals_, lids)
helper function for analyze_references(). attempts to remove references to ipython/jupyter history variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
refs
|
list
|
list of reference objects |
required |
globals_
|
Optional[dict]
|
optional specified globals dictionary. if not given, uses the globals of the parent frame of the caller. |
required |
lids
|
Collection[int]
|
ids of all known copies of other frames' locals dicts. |
required |
Returns:
| Type | Description |
|---|---|
list
|
filtered list of references. |
Source code in hostess/profilers.py
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 | |
_filter_ids(refs, permit, exclude, lids)
helper function for analyze_references(). provides blocklist/allowlist behavior based on object ids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
refs
|
list
|
list of reference objects |
required |
permit
|
Collection[int]
|
list of allowed ids. if any are given, this functions as a strict allowlist. |
required |
exclude
|
Collection[int]
|
list of excluded ids |
required |
lids
|
Collection[int]
|
ids of all known copies of other frames' locals dicts |
required |
Returns:
| Name | Type | Description |
|---|---|---|
filtered_refs |
list[Any]
|
filtered list of references |
refnoms |
list[Refnom]
|
Refnom dicts for each member of filtered_refs |
Source code in hostess/profilers.py
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 | |
_filter_types(refs, permit, exclude, lids)
helper function for analyze_references(). provides blocklist/allowlist behavior based on object types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
refs
|
list
|
list of referencing objects |
required |
permit
|
Collection[type]
|
types to explicitly permit. if there is at least one type, this functions as a strict allowlist. |
required |
exclude
|
Collection[type]
|
types to explicitly exclude. |
required |
lids
|
Collection[int]
|
ids of all known copies of other frames' |
required |
Returns:
| Type | Description |
|---|---|
list
|
filtered list of references. |
Source code in hostess/profilers.py
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 | |
_get_referencing_scopedicts(obj, existing_ids)
check for obj in the globals and locals dicts of all stack frames above
the caller's. return all dicts in which obj has a name or names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
object to check for |
required |
existing_ids
|
Collection[int]
|
ids of scopedicts that should be ignored |
required |
Returns:
| Type | Description |
|---|---|
list[dict]
|
list of locals and globals dicts that reference obj |
Source code in hostess/profilers.py
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 | |
_maybe_release_locals(localdict, frame)
Possibly purge a dictionary, depending on the name of frame's code.
Tedious description of technical rationale:
the locals dict of the top-level module frame is the same as its
globals dict. retrieving it from a frame gives us the actual globals
dict, not a copy of it. we do NOT want to casually delete all members
of the top-level module while pretending to merely inspect it.
conversely, locals dicts retrieved from lower frames are only copies.
modifying them will not affect the actual namespaces of those frames.
HOWEVER, references to everything in those copies will hang around forever
until that frame fully dies, which, in most programs, will badly confuse
the Python garbage collector and cause horrible memory leaks. clearing the
copies is the only reliable way to prevent that from happening.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
localdict
|
MutableMapping
|
a dict that might be a copy of |
required |
frame
|
FrameType
|
frame |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if we cleared |
Note
Always skipped in Python>=3.13, as the introduction of FrameLocalsProxy makes it unnecessary.
Source code in hostess/profilers.py
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 | |
_yclept_framerec(frame)
return terse information about a frame's name and contents. for yclept.
Source code in hostess/profilers.py
392 393 394 395 396 397 398 399 400 401 | |
analyze_references(obj, method, *, filter_primitive=True, filter_history=True, filter_scopedict=True, filter_reflexive=True, exclude_ids=frozenset(), exclude_types=frozenset(), permit_ids=frozenset(), permit_types=frozenset(), globals_=None, return_objects=False)
analyze 'references' to or from obj. designed for, but not limited to, analyzing references tracked by the Python garbage collector.
careful use is required to avoid memory leaks
TAKE SPECIAL CARE WHEN DECORATING THIS FUNCTION OR CALLING IT FROM A LAMBDA FUNCTION OR GENERATOR EXPRESSION, NO MATTER HOW HARMLESS- LOOKING. These operations may add references that are difficult to recognize or interpret. Calls that do not add context are much safer.
Notes
-
All 'exclude', 'permit', and 'filter' operations are implicitly connected by boolean AND. Represented as a predicate:
(~PRIMITIVE(REF) | ~FILTER_PRMITIVE) & (~HISTORY(REF) | ~FILTER_HISTORY) & (~SCOPEDICT(REF) | ~FILTER_SCOPEDICT) & ((ID(REF) != ID(OBJ)) | ~FILTER_REFLEXIVE) & ~(ID(REF) ∈ EXCLUDE_IDS) & (ID(REF) ∈ PERMIT_IDS | PERMIT_IDS = ∅) & ~(TYPE(REF) ∈ EXCLUDE_TYPES) & (TYPE(REF) ∈ PERMIT_TYPES | PERMIT_TYPES = ∅) -
References from obj to itself are never included. This may change in the future.
- This function is only completely compatible with CPython.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
object of referential analysis |
required |
method
|
Callable[[Any], Collection]
|
Function whose return values define 'references' of obj. gc.get_referents and gc.get_referrers are the intended and tested values. |
required |
filter_primitive
|
bool
|
ignore 'primitive' (str, bool, &c) objects? |
True
|
filter_history
|
bool
|
attempt to ignore ipython 'history' objects? filter_scopedict: ignore direct references to the locals, globals, and builtins dicts of all frames in stack (not the values of these dictionaries?) |
True
|
filter_reflexive
|
bool
|
ignore references from obj to itself? |
True
|
exclude_ids
|
Collection[int]
|
denylist of reference ids. |
frozenset()
|
exclude_types
|
Collection[type]
|
denylist of reference types. |
frozenset()
|
permit_ids
|
Collection[int]
|
allowlist of reference ids. |
frozenset()
|
permit_types
|
Collection[type]
|
allowlist of reference types. |
frozenset()
|
return_objects
|
bool
|
return objects in set of references, or only descriptions of those objects? |
False
|
globals_
|
Optional[dict[str, Any]]
|
optional dictionary of globals to use in filtering. currently only used in history filtering. If this argument is None, history filtering uses the globals of the calling frame. |
None
|
Source code in hostess/profilers.py
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 | |
def_lineno(obj)
Returns the line number where the object was defined, if available.
Source code in hostess/profilers.py
326 327 328 329 330 331 | |
describe_frame_contents(frame=None)
describe the contents of a frame
Source code in hostess/profilers.py
373 374 375 376 377 378 379 380 381 382 383 384 | |
describe_stack_contents()
describe the contents of the stack
Source code in hostess/profilers.py
387 388 389 | |
di(obj_id)
backwards id. Use with care! Can segfault.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_id
|
int
|
id of desired object, as returned by |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Object corresponding to |
Source code in hostess/profilers.py
725 726 727 728 729 730 731 732 733 734 735 | |
history_filter(glb)
generate a predicate function that attempts to filter jupyter/ipython history-related objects in the context of a particular global namespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
glb
|
dict[str, Any]
|
relevant globals dict |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Any], bool]
|
function that returns False if its single argument looks like it's an ipython/jupyter history-related object or internal, and True if not. |
Source code in hostess/profilers.py
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 | |
identify(obj, maxlen=25, getsize=False)
identify an object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
object to identify |
required |
maxlen
|
int
|
maximum length of string representation of |
25
|
getsize
|
bool
|
if True, attempt to determine the size of |
False
|
Returns:
| Type | Description |
|---|---|
IdentifyResult
|
dict giving id, type, string representation (possibly truncated), size in MB (if requested), and, if available, name, qualname, and module, and line number. |
Source code in hostess/profilers.py
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 | |
lineno()
Returns the current line number in our program.
Source code in hostess/profilers.py
321 322 323 | |
namespace_ids(frames=None, include_frame_ids=False)
find ids of all top-level objects in the combined namespace(s) of a frame or frames.
Source code in hostess/profilers.py
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | |
refcounts(getstack=False, stepback=1)
get refcounts of named variables in one or all frames in the stack.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
getstack
|
bool
|
check all frames in the stack above the starting frame? |
False
|
stepback
|
int
|
number of frames to step back from the frame of this function before counting |
1
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Union[str, dict[str, int]]]]
|
A list of dicts, one for each counted frame (always length 1 if
|
Source code in hostess/profilers.py
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 | |
scopedict_ids(frames=None, *, getstack=False, scopenames=('locals', 'globals', 'builtins'), distinguish_locals=True)
return ids of all 'scopedicts' (locals, globals, builtins) in frames (by default, just the caller's frame.) uses include: distinguishing references held by namespaces from references held by other objects; avoiding accidental 'direct' manipulation of namespaces.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
Union[FrameType, Collection[FrameType], None]
|
a single frame, a collection of frames, or None. if None, get ids of scopedicts of the caller's frame. |
None
|
getstack
|
bool
|
if True, ignore the frames argument and instead look at all levels of the stack above the caller's frame. |
False
|
scopenames
|
Sequence[ScopeName]
|
names of scopes to fetch. |
('locals', 'globals', 'builtins')
|
distinguish_locals
|
bool
|
if True, return a tuple whose elements are: [0] all ids [1] just local-scope ids below top level |
True
|
Source code in hostess/profilers.py
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 | |
scopedicts(frame, scopes=('locals', 'globals', 'builtins'))
fetch specified scopes from a frame and return them in a tuple. the elements of the tuple should be equivalent to the results of calling, e.g., locals() within the passed frame.
WARNING: caller is responsible for clearing references to locals, etc. calling this function with no cleanup deep in a call stack may lead to undesired dangling references.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
FrameType
|
frame (as generated by, e.g., inspect.currentframe()) from which to fetch scopes. |
required |
scopes
|
Sequence[ScopeName]
|
names of scopes to fetch from frame. |
('locals', 'globals', 'builtins')
|
Returns:
| Type | Description |
|---|---|
tuple[dict, ...]
|
tuple of dictionaries representing the specified scopes of frame; their keys are variable names and their values are the associated objects. |
Source code in hostess/profilers.py
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 | |
val_ids(mapping)
get ids of all values in mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Mapping[Hashable, Any]
|
mapping whose values are the objects to id. |
required |
Returns:
| Type | Description |
|---|---|
set[int]
|
set of ids of all objects in mapping's values. |
Source code in hostess/profilers.py
200 201 202 203 204 205 206 207 208 209 210 | |
val_refs(refmap)
produce dict containing refcounts of all values in refmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
refmap
|
Mapping[str, Any]
|
dict to count. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
|
Source code in hostess/profilers.py
738 739 740 741 742 743 744 745 746 747 748 749 750 | |
yclept(obj, terse=True, stepback=1)
Find basic identifiers for obj, along with any names for obj in all frames in stack, starting stepback frames back from the frame of this function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
object to name |
required |
terse
|
bool
|
exclude extended information from output? |
True
|
stepback
|
int
|
how many frames to step back (from the frame of this function) before looking for obj? |
1
|
Source code in hostess/profilers.py
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 | |
serverpool
ServerPool
Abstraction for a pool of asynchronous workers with hostess-compatible
interfaces. Intended primarily for distributing tasks across remote hosts.
Many alternatives are more appropriate for local tasks, such as the Python
Standard Library's concurrent.futures.ThreadPoolExecutor and
multiprocessing.Pool.
Source code in hostess/serverpool.py
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 | |
available
property
Available hosts.
Returns:
| Type | Description |
|---|---|
dict[Hashable, Union[Instance, RunCommand]]
|
|
next_available
property
First available host, if any, preferring hosts that have not recently been assigned a task.
Returns:
| Type | Description |
|---|---|
Optional[tuple[Hashable, Union[Instance, RunCommand]]]
|
|
running
property
Returns:
| Type | Description |
|---|---|
tuple[Viewer]
|
All currently-running tasks. |
__init__(hosts, max_concurrent=1, poll=0.03, task_delay=None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hosts
|
Sequence[Union[Instance, RunCommand]]
|
An object that has at least one method that returns a
|
required |
max_concurrent
|
int
|
Maximum number of tasks a single host may run
concurrently. The maximum number of threads spawned by this
object is thus |
1
|
poll
|
float
|
Polling rate, in seconds, for checking pending/running tasks. |
0.03
|
Source code in hostess/serverpool.py
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 | |
__poll_loop()
Process poll loop. Should only be called by self.__start().
Source code in hostess/serverpool.py
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 | |
__start()
Launch process polling loop, if necessary. Should only be called by
self.apply().
Source code in hostess/serverpool.py
272 273 274 275 276 277 278 | |
_rectify_call(kwargs)
helper function for self.apply(). don't allow new tasks when closed;
don't let callers forbid Viewers or disown processes.
Raises:
| Type | Description |
|---|---|
ValueError
|
if pool is closed. |
Source code in hostess/serverpool.py
179 180 181 182 183 184 185 186 187 188 189 190 191 | |
apply(method, args=(), kwargs=None)
Submit a task to the host pool. Execute it immediately if a host is
available; otherwise queue it for execution. Unlike some task pool
methods of this type, ServerPool.apply() does not return a
futurelike object, but instead relies on ServerPool's automated
lifecycle management. ServerPool moves unexecuted tasks to
ServerPool.pending as tuples; executed tasks to
ServerPool.taskmap as futurelike ServerTask objects, and completed
tasks to ServerPool.completed as Viewers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Name of method of host to call with |
required |
args
|
Sequence
|
Args to pass to the named method. |
()
|
kwargs
|
Mapping
|
kwargs to pass to the named method. |
None
|
Source code in hostess/serverpool.py
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 | |
close()
Close the pool, preventing submission of new tasks.
Source code in hostess/serverpool.py
330 331 332 | |
gather()
Block until all pending and running tasks are complete, then terminate
self, then return the results of all completed tasks in a list. Useful
for 'under-the-hood' uses of ServerPool.
Returns:
| Type | Description |
|---|---|
list[Viewer]
|
A |
Source code in hostess/serverpool.py
348 349 350 351 352 353 354 355 356 357 358 359 360 | |
join()
Block until all pending and running tasks are complete.
Source code in hostess/serverpool.py
334 335 336 337 | |
terminate()
Terminate the ServerPool. This will cancel all pending tasks, kill
all running tasks, and prevent submission of new tasks.
Source code in hostess/serverpool.py
339 340 341 342 343 344 345 346 | |
ServerTask
Simple future-like object. It is primarily intended to be instantiated
by ServerPool as an abstraction for a process running on a remote host.
Source code in hostess/serverpool.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | |
done
property
Aliases self.viewer.done. Always False if self.viewer is None.
err
property
Aliases self.viewer.err. Always [] if self.viewer is None.
out
property
Aliases self.viewer.out. Always [] if self.viewer is None.
running
property
Aliases self.viewer.running. Always False if self.viewer is None.
__init__(host, method, args, kwargs, defer=False, poll=0.03)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
Union[Instance, RunCommand]
|
An object whose |
required |
method
|
str
|
Name of a method of |
required |
args
|
Sequence
|
Args to pass to |
required |
kwargs
|
Mapping
|
Kwargs to pass to |
required |
defer
|
bool
|
If |
False
|
poll
|
float
|
Polling rate, in seconds, for |
0.03
|
Source code in hostess/serverpool.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
get()
Block until self.viewer is finished.
Returns:
| Type | Description |
|---|---|
Union[Viewer, Exception]
|
A Viewer to a finished process, or an Exception if |
Raises:
| Type | Description |
|---|---|
ValueError
|
If this object has not yet executed its task. |
TypeError
|
If task execution failed. |
Source code in hostess/serverpool.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | |
kill()
Aliases self.viewer.kill(). Does nothing if self.viewer is None.
Source code in hostess/serverpool.py
86 87 88 89 | |
run()
Execute the task.
Source code in hostess/serverpool.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | |
shortcuts
shortcuts for composing shell commands. relies on some bournelike idioms, so output will likely function best in bash.
chain(cmds, op='then')
create a multi-part shell command.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmds
|
Sequence[str]
|
commands to chain together. |
required |
op
|
Literal['and', 'xor', 'then']
|
logical operator to chain them with. |
'then'
|
Returns:
| Type | Description |
|---|---|
str
|
multi-part shell command as a string. |
Source code in hostess/shortcuts.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |
ssh_agent(key)
construct a shell command that starts an ssh-agent session and adds a keyfile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
path to SSH keyfile |
required |
Returns:
| Type | Description |
|---|---|
str
|
string form of shell command. |
Source code in hostess/shortcuts.py
74 75 76 77 78 79 80 81 82 83 84 85 | |
sub(cmd)
shorthand for f"$({cmd})", i.e., instruction to run cmd in a subshell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str
|
string form of shell command to wrap in subshell instruction |
required |
Returns:
| Type | Description |
|---|---|
str
|
instruction to run cmd in a subshell |
Source code in hostess/shortcuts.py
27 28 29 30 31 32 33 34 35 36 37 | |
ternary(if_, then_, else_=None)
construct a bash command that serves as a ternary operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
if_
|
str
|
argument to the shell command "test" to use as predicate (see the manpage for test for details) |
required |
then_
|
str
|
shell command to run if predicate is truthy |
required |
else_
|
Optional[str]
|
shell command to run if predicate is falsy |
None
|
Returns:
| Type | Description |
|---|---|
str
|
string form of ternary shell command |
Source code in hostess/shortcuts.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
truthy(cmd)
construct a shell command that tests a predicate and echoes "True" if it's truthy and "False" if it's falsy. This is intended as an easy way to do tests in bash that output the string representation of a Python bool literal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str
|
predicate to test. will be used as an argument to the shell command "test" (see manpage for test for details) |
required |
Returns:
| Type | Description |
|---|---|
str
|
string form of truthiness-printing shell command |
Source code in hostess/shortcuts.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
ssh
NotebookConnection = tuple[str, Callable, dict, Processlike, Callable[[], None]]
module-attribute
structure containing results of a tunneled Jupyter Notebook execution.
- URL for Jupyter server
- function that shuts down tunnel
- SSH tunnel metadata
- Jupyter execution process
- Callable for gracefully shutting down Notebook
SSH
Bases: RunCommand
callable interface to an SSH connection to a remote host. basically a wrapper for a fabric.connection.Connection object with additional functionality for managed command execution. NOTE: supports only keyfile authentication.
Examples:
>>> ssh = SSH.connect(
... "1.11.11.111", 'remote_user', '/home/user/.ssh/keyfile.pem'
... )
>>> ssh("echo hi > a.txt")
>>> tail = ssh("tail -f a.txt")
>>> for n in range(5):
... ssh(f"echo {n} >> a.txt")
>>> print(','.join([s.strip() for s in tail.out]))
>>> ssh.con('ls -l / | grep dev')
expected output:
hi, 0, 1, 2, 3
drwxr-xr-x 15 root root 3320 Nov 12 01:50 dev
Source code in hostess/ssh.py
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 | |
__call__(*args, _quiet=True, _viewer=True, _wait=False, **kwargs)
run a shell command in the remote host's default interpreter. See
RunCommand.__call__() for details on calling conventions and options.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Union[int, float, str]
|
args to use to construct the command. |
()
|
_viewer
|
bool
|
if |
True
|
_wait
|
bool
|
if |
False
|
_quiet
|
bool
|
if |
True
|
**kwargs
|
Union[int, float, str, bool]
|
kwargs to pass to command execution. kwarg
names beginning with '_' specify execution meta-parameters;
others will be inserted directly into the command as |
{}
|
Returns:
| Type | Description |
|---|---|
Processlike
|
object representing executed process. |
Source code in hostess/ssh.py
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 | |
__init__(command=None, conn=None, key=None, **kwargs)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
Optional[str]
|
optional shell command to 'curry' into this object. may be omitted if commands will be provided later, or if this particular object is not intended to execute commands. |
None
|
conn
|
Optional[Connection]
|
Fabric |
None
|
key
|
Optional[str]
|
path to keyfile; may be provided after instantiation, but must be provided before command is actually executed. |
None
|
**kwargs
|
Union[int, float, str, bool]
|
RunCommand init kwargs (see RunCommand documentation) |
{}
|
Source code in hostess/ssh.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | |
con(*args, _poll=0.05, _timeout=None, _return_viewer=False, **kwargs)
pretend you are running a command on the remote host while looking at a terminal emulator. pauses for output and pretty-prints it to stdout.
Does not return a process abstraction by default (pass _return_viewer=True if you want one). Fun in interactive environments.
Only arguments unique to con() are described here; others are as SSH.call().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Union[int, float, str]
|
additional args to pass to self.call. |
()
|
_poll
|
float
|
polling rate for process output, in seconds |
0.05
|
_timeout
|
Optional[float]
|
if not None, raise a TimeoutError if this many seconds pass before receiving additional output from process (or process exit). |
None
|
_return_viewer
|
bool
|
if True, return a Viewer for the process once it exits. Otherwise, return None. |
False
|
**kwargs
|
Union[int, float, str, bool]
|
additional kwargs to pass to self.call. |
{}
|
Returns:
| Type | Description |
|---|---|
Optional[Viewer]
|
A Viewer if _return_viewer is True; otherwise None. |
Source code in hostess/ssh.py
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 | |
connect(host, uname=GENERAL_DEFAULTS['uname'], key=None)
classmethod
constructor that creates a connection to the remote host and uses it
to instantiate the SSH object. convenient in cases when an appropriate
Connection object does not already exist or should not be reused.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
ip of remote host |
required |
uname
|
str
|
user name on remote host |
GENERAL_DEFAULTS['uname']
|
key
|
str
|
path to keyfile |
None
|
Returns:
| Type | Description |
|---|---|
SSH
|
an SSH object with a newly-generated |
Source code in hostess/ssh.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
get(source, target, *args, **kwargs)
copy file from remote to local.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
path to file on remote host |
required |
target
|
Union[str, Path, IO]
|
path to local file, or a filelike object (such as io.BytesIO) |
required |
*args
|
Any
|
args to pass to underlying get method |
()
|
**kwargs
|
Any
|
kwargs to pass to underlying get method |
{}
|
Returns:
| Type | Description |
|---|---|
dict
|
dict giving transfer metadata: local, remote, host, and port |
Source code in hostess/ssh.py
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 | |
put(source, target, *args, literal_str=False, **kwargs)
write local file or object to target file on remote host.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path, IO, bytes]
|
filelike object or path to local file |
required |
target
|
Union[str, Path]
|
write path on remote host |
required |
args
|
Any
|
additional arguments to pass to underlying put method |
()
|
literal_str
|
bool
|
if True and |
False
|
kwargs
|
Any
|
additional kwargs to pass to underlying put command |
{}
|
Returns:
| Type | Description |
|---|---|
dict
|
dict giving transfer metadata: local, remote, host, and port |
Source code in hostess/ssh.py
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 | |
read(source, mode='r', encoding='utf-8', as_buffer=False)
read a file from the remote host directly into memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
path to file on remote host. |
required |
mode
|
Literal['r', 'rb']
|
'r' to read file as text; 'rb' to read file as bytes |
'r'
|
encoding
|
str
|
encoding for text, used only if |
'utf-8'
|
as_buffer
|
bool
|
if True, return BytesIO/StringIO; if False, return bytes/str |
False
|
Returns:
| Type | Description |
|---|---|
Union[BytesIO, StringIO, bytes, str]
|
contents of remote file as str, bytes, or IO |
Source code in hostess/ssh.py
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 | |
read_csv(source, encoding='utf-8', **csv_kwargs)
read a CSV-like file from the remote host into a pandas DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
path to CSV-like file on remote host |
required |
encoding
|
str
|
encoding for text |
'utf-8'
|
csv_kwargs
|
Any
|
kwargs to pass to pd.read_csv |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame created from contents of remote CSV file |
Source code in hostess/ssh.py
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | |
tunnel(local_port, remote_port)
create an SSH tunnel between a local port and a remote port; store an abstraction for the tunnel process, along with metadata about the tunnel, in self.tunnels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
local_port
|
int
|
port number for local end of tunnel. |
required |
remote_port
|
int
|
port number for remote end of tunnel. |
required |
Source code in hostess/ssh.py
329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
find_conda_env(cmd, env=None)
find location of a named conda environment. intended primarily for use on remote hosts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
RunCommand
|
instance of RunCommand or one of its subclasses; most likely an SSH instance. |
required |
env
|
str
|
name of conda environment. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
absolute path to root directory of conda environment. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
if environment cannot be found. |
Source code in hostess/ssh.py
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 | |
find_ssh_key(keyname, paths=None)
look for private SSH keyfile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keyname
|
str
|
full or partial name of keyfile |
required |
paths
|
Optional[Collection[Union[str, Path]]]
|
paths in which to search for key file. if not specified, look in hostess.config.GENERAL_DEFAULTS['secrets_folders'] |
None
|
Returns:
| Type | Description |
|---|---|
Union[Path, None]
|
path to keyfile |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
if no key found |
Source code in hostess/ssh.py
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 | |
get_jupyter_token(command, jupyter_executable, port)
Get the access token of a Jupyter server running on the specified port.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
RunCommand
|
an instance of RunCommand or one of its subclasses, likely an SSH object. |
required |
jupyter_executable
|
str
|
path to Jupyter executable. |
required |
port
|
int
|
port on which Jupyter server is running. |
required |
Returns:
| Type | Description |
|---|---|
str
|
the Jupyter server's access token. |
Source code in hostess/ssh.py
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 | |
jupyter_connect(ssh, local_port=22222, remote_port=8888, env=None, get_token=True, kill_on_exit=False, working_directory=None, lab=False, **command_kwargs)
Launch a Jupyter server on a remote host over an SSH tunnel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ssh
|
SSH
|
|
required |
local_port
|
int
|
port number for local end of tunnel |
22222
|
remote_port
|
int
|
port number for remote Jupyter server / remote end of tunnel |
8888
|
env
|
Optional[str]
|
conda env from which to launch Jupyter server; if none is
specified, use the remote host's default |
None
|
get_token
|
bool
|
get the access token from the server? |
True
|
kill_on_exit
|
bool
|
attempt to kill the Jupyter server when the
|
False
|
working_directory
|
Optional[str]
|
working directory for jupyter server |
None
|
lab
|
bool
|
launch JupyterLab instead of Jupyter Notebook |
False
|
**command_kwargs
|
Union[int, str, bool]
|
additional kwargs to pass to |
{}
|
Returns:
| Type | Description |
|---|---|
NotebookConnection
|
structure containing results of tunneled notebook execution, including a callable to terminate the Notebook and another to close the tunnel |
Source code in hostess/ssh.py
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 | |
launch_tunnel_thread(host, uname, keyfile, local_port, remote_port, signalbuf=None)
launch an SSH tunnel. primarily intended as a helper function
for open_tunnel(), but can be used on its own. blocks until
it hits an exception or it receives a signal, so should generally
be run in a thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
hostname of tunnel target |
required |
uname
|
str
|
username on remote host |
required |
keyfile
|
str
|
path to local SSH key file |
required |
local_port
|
int
|
port for proximal end of tunnel |
required |
remote_port
|
int
|
port for distal end of tunnel |
required |
signalbuf
|
Optional[list]
|
list to receive close-tunnel signal |
None
|
Returns:
| Type | Description |
|---|---|
Union[tuple[Connection, Exception], Any]
|
signal received if closed gracefully; tuple of the Connection |
Union[tuple[Connection, Exception], Any]
|
object and the Exception if it hits an exception. |
Source code in hostess/ssh.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
merge_csv(ssh_dict, fn, **csv_kwargs)
merges data from CSV files on multiple remote hosts into a single pandas DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ssh_dict
|
Mapping[Hashable, SSH]
|
mapping whose keys are identifiers for remote hosts and whose values are SSH objects connected to those hosts. |
required |
fn
|
str
|
path to file (must be the same on all remote hosts) |
required |
csv_kwargs
|
Any
|
kwargs to pass to pd.read_csv() |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
a DataFrame containing merged data from all remote CSV files, |
DataFrame
|
including a "server" column that labels the source hosts using the |
DataFrame
|
keys of |
Source code in hostess/ssh.py
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 | |
open_tunnel(host, uname, keyfile, local_port, remote_port)
launch a thread that maintains an SSH tunnel. NOTE: supports only keyfile authentication.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
remote host ip |
required |
uname
|
str
|
user name on remote host |
required |
keyfile
|
Union[str, Path]
|
path to keyfile |
required |
local_port
|
int
|
port on local end of tunnel |
required |
remote_port
|
int
|
port on remote end of tunnel |
required |
Returns:
| Name | Type | Description |
|---|---|---|
signaler |
Callable[[Any], None]
|
function that shuts down tunnel |
tunnel_metadata |
dict[str, Union[int, str, Path]]
|
dict of metadata about the tunnel |
Source code in hostess/ssh.py
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 | |
stop_jupyter_factory(command, jupyter, port)
Create a function that shuts down a Jupyter server when some other task or process completes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
RunCommand
|
an instance of RunCommand or one of its subclasses, likely an SSH object. |
required |
jupyter
|
str
|
absolute path to jupyter executable |
required |
port
|
int
|
port on which jupyter server is running |
required |
Returns:
| Type | Description |
|---|---|
Callable
|
function that, when passed anything with a |
Source code in hostess/ssh.py
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 | |
unpack_transfer_result(result)
summarize a fabric transfer Result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
Result
|
Result of a get, put, or similar SSH operation. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
dict giving local and remote transfer targets, hostname, and port. |
Source code in hostess/ssh.py
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 | |
station
station.actors
concrete implementations of Actor and Sensor base classes, along with some helper functions.
NODE_ACTION_FIELDS = frozenset({'id', 'start', 'stop', 'status', 'result'})
module-attribute
keys a dict must have to count as a valid "actiondict" in a Node's actions list
DirWatch
Bases: FileSystemWatch
like FileSystemWatch, but its target property should be a folder, not a
file, and its patterns property matches newly-appearing filenames.
Source code in hostess/station/actors.py
436 437 438 439 440 441 442 443 444 445 | |
FileSystemWatch
Bases: Sensor
simple Sensor for watching contents of a filesystem. offers an interface for changing target path and regex match patterns. this base class tails a file. see DirWatch for a subclass that diffs a directory.
Source code in hostess/station/actors.py
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 | |
logfile = property(_get_logfile, _set_logfile)
class-attribute
instance-attribute
where does this Sensor log its matches?
patterns = property(_get_patterns, _set_patterns)
class-attribute
instance-attribute
what patterns does this Sensor look for in the file?
target = property(_get_target, _set_target)
class-attribute
instance-attribute
what file does this Sensor watch?
FileWriter
Bases: Actor
Simple Actor that writes to a file.
Source code in hostess/station/actors.py
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 | |
file = property(_get_file, _set_file)
class-attribute
instance-attribute
file this Actor writes to
mode = property(_get_mode, _set_mode)
class-attribute
instance-attribute
mode this Actor writes in -- one of 'w', 'wb', 'a', or 'ab'.
FuncCaller
Bases: Actor
Versatile Actor that handles Instructions to call Python functions.
A Station typically makes these using handlers.make_function_call().
Source code in hostess/station/actors.py
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 | |
InstructionFromInfo
Bases: DispatchActor
skeleton Info-handling Actor for Stations. Checks, based on configurable criteria, whether an object unpacked from an Info message included in an Update indicates that the Station should assign a task to some handler Delegate, and, if it does, create an Instruction from that object based on an instruction-making function.
Note that this Actor is basically abstract by default; its criteria and
instruction_maker properties must be assigned to make it do anything.
Source code in hostess/station/actors.py
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 | |
criteria = None
class-attribute
instance-attribute
predicate functions that define what objects this Actor can handle. if any of these functions return True when passed an object, the Actor matches that object.
instruction_maker = None
class-attribute
instance-attribute
function that generates an Instruction from an object
LineLogger
Bases: Actor
Simple Actor that logs all strings passed to it. intended to be attached to Sensors that need to generate their own logs rather than writing to their parent Delegate's primary log.
Source code in hostess/station/actors.py
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
match(line, **_)
match only strings
Source code in hostess/station/actors.py
282 283 284 285 286 | |
PipeActorPlaceholder
Bases: Actor
pipeline execution actor. resubmits individual steps of pipelines as Instructions to the calling node. we haven't implemented this, so it doesn't do anything.
Source code in hostess/station/actors.py
136 137 138 139 140 141 142 143 144 145 146 147 148 | |
ReportStringMatch
Bases: Actor
Actor that checks whether a string matches any of a sequence of regex patterns. Intended to be used by Sensors that work by tailing a file or other data stream.
This Actor's execute() inserts the string into the parent Delegate's
list of actionable events, annotated with a list of all patterns that
matched the string, and, optionally, with a string denoting the
string's source. the Delegate will use this to construct an Info Message
it will include in an Update to its Station.
Source code in hostess/station/actors.py
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 | |
SysCaller
Bases: Actor
Versatile Actor that handles Instructions to run OS-level shell commands.
Source code in hostess/station/actors.py
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 | |
conclude_execution(result, status=None, actiondict=None)
conclude a "regular" 'do'-type action, inserting relevant data into its
associated actiondict. Intended primarily as a component function of the
reported() decorator.
Note that individual Actors, even if they use reported(), often define
additional cleanup steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
Any
|
return value of, or Exception raised by, an Actor's execute() method. |
required |
status
|
Optional[str]
|
optional status code. if not specified, status will always be
"success" unless |
None
|
actiondict
|
Optional[MutableMapping[str, Any]]
|
element of parent Node's |
None
|
Source code in hostess/station/actors.py
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 | |
init_execution(node, instruction, key, noid)
perform setup for a "regular" 'do'-type Instruction. Intended primarily as
a component function of the reported() decorator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
Node
|
Actor's parent Node (usually a Delegate) |
required |
instruction
|
Message
|
'do'-type Instruction |
required |
key
|
Optional[Hashable]
|
name of / identifier for Instruction's Action. if not specified, generates a random integer. |
required |
noid
|
bool
|
don't insert the Instruction's id into the generated actiondict. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
action |
Action
|
Action from action field of Instruction, or full Instruction if it contains only a description of the action |
actiondict |
dict
|
data/metadata dict for the action that this function
generated function and inserted into the parent Node's |
key |
Hashable
|
identifier for action |
Source code in hostess/station/actors.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | |
reported(executor)
decorator for bound execute() methods of Actors that handle 'do'-type Instructions in a "normal" fashion. Provides standardized setup and conclusion behaviors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
executor
|
Callable
|
bound execute() method of associated Actor. |
required |
Returns:
| Type | Description |
|---|---|
Callable
|
version of execute() method with added setup and conclusion steps. |
Source code in hostess/station/actors.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
station.bases
base classes and helpers for Delegates, Stations, Sensors, and Actors.
Actor
Bases: ABC
abstract base class enabling conditional responses to events. Actors should generally only be instantiated from methods of a parent Matcher.
Source code in hostess/station/bases.py
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 | |
execute(node, event, **kwargs)
This method defines what an Actor does with objects it matches. Must be implemented in concrete subclasses of Actor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
Node
|
parent Node of this Actor. In normal operation, this
argument will never be explicitly passed, but instead
partially evaluated into this method in |
required |
event
|
Any
|
object to do something with. |
required |
**kwargs
|
Any
|
placeholder for kwargs defined in a subclass. |
{}
|
Source code in hostess/station/bases.py
424 425 426 427 428 429 430 431 432 433 434 435 436 | |
match(event, **_)
Determine if this Actor can / should handle a given event. Must be implemented in concrete subclasses of Actor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
Any
|
event to match. |
required |
**_
|
Any
|
placeholder for kwargs defined in a subclass. |
{}
|
Returns:
| Type | Description |
|---|---|
bool
|
True if this Actor can handle |
Raises:
| Type | Description |
|---|---|
NoMatch
|
if this Actor cannot handle |
Source code in hostess/station/bases.py
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
AllBusy
Bases: Exception
A Station, possibly via one of its Actors, attempted to dispatch an Instruction to one of its Delegates, but all appropriate Delegates for the Instruction were busy.
Source code in hostess/station/bases.py
558 559 560 561 562 563 | |
AttrConsumer
Mix-in class that provides functionality for "consuming" attributes of other objects. Designed to permit Nodes and similar objects to promote interface properties of attached elements into their own interfaces as pseudo-attributes.
Source code in hostess/station/bases.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | |
__dir__()
add the pseudo-attributes in attrefs to this object's directory so that they look real.
Source code in hostess/station/bases.py
100 101 102 103 104 105 106 | |
__getattr__(attr)
if normal attribute lookup fails, attempt to refer it to a property of an associated object.
Source code in hostess/station/bases.py
76 77 78 79 80 81 82 83 84 | |
__setattr__(attr, value)
refer assignments to pseudo-attributes defined in self.proprefs to the properties of the underlying objects.
Source code in hostess/station/bases.py
86 87 88 89 90 91 92 93 94 95 96 97 98 | |
consume_property(obj, attr, newname=None)
consume an attribute of another object into this object's interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
object from which to consume attribute |
required |
attr
|
str
|
name of attribute to consume |
required |
newname
|
Optional[str]
|
optional name of referencing attribute of |
None
|
Source code in hostess/station/bases.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
ConsumedAttributeError
Bases: AttributeError
An AttrConsumer's attempt to set a consumed attribute failed.
Source code in hostess/station/bases.py
44 45 46 47 | |
DispatchActor
Bases: Actor, ABC
abstract class for Actors intended to dispatch Instructions from Stations to Nodes.
Source code in hostess/station/bases.py
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 | |
target_actor = None
class-attribute
instance-attribute
if set, dispatch only to Delegates that have an Actor named target_actor.
target_name = None
class-attribute
instance-attribute
if set, dispatch only to Delegates named exactly target_name.
target_picker = None
class-attribute
instance-attribute
function that can be used to define more complex Delegate selection behaviors.
pick(station, instruction, **_)
Pick which of a Station's Delegates to send an Instruction to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station
|
'Station'
|
Parent Station. in normal operation, will never be explicitly passed. |
required |
instruction
|
Message
|
Instruction Message to dispatch. |
required |
**_
|
Any
|
placeholder for kwargs defined in concrete subclasses. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Name of selected Delegate. |
Raises:
| Type | Description |
|---|---|
NoMatchingDelegate
|
if no Delegate matches rules defined by this Actor's target_name, target_picker, or target_actor attributes, including if the Station has no Delegates. |
TypeError
|
if this Actor's target_name, target_picker, and target_actor attributes are all None. |
Source code in hostess/station/bases.py
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 | |
DoNotUnderstand
Bases: ValueError
This Delegate does not know how to interpret this Instruction.
Source code in hostess/station/bases.py
515 516 | |
Matcher
Bases: AttrConsumer, ABC
Abstract mix-in class for Node and Sensor. Provides functionality for matching objects against Actors.
Source code in hostess/station/bases.py
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 | |
add_element(cls, name=None)
instantiate an Actor or Sensor and associate it with this object, consuming its interface properties and making it available for matching or sensor looping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
Union[type[Actor], type[Sensor]]
|
Actor or Sensor type to instantiate and associate |
required |
name
|
Optional[str]
|
optional custom name for element that will be used to identify it in this object's configuration dictionary and properties interface. If not specified, uses the name of the element's class, suffixing incrementing numbers if that name would collide with an already-associated element. |
None
|
Source code in hostess/station/bases.py
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 | |
explain_match(event, category=None, **kwargs)
Introspection function for matching process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
Any
|
object to match Actors against |
required |
category
|
Optional[str]
|
optional category of Actors to match |
None
|
**kwargs
|
Any
|
kwargs for |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Union[str, bool]]
|
dict whose keys are the names of Actors and whose values are
the output of each actor's |
Source code in hostess/station/bases.py
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 | |
filter_actors_by_category(actortype)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
actortype
|
Optional[str]
|
optional string denoting a category of Actor |
required |
Returns:
| Type | Description |
|---|---|
list[Actor]
|
A list containing all of this object's Actors whose |
Source code in hostess/station/bases.py
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
match(event, category=None, **kwargs)
Check the Matcher's Actors to see which, if any, can handle an event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
Any
|
object to match Actors against |
required |
category
|
Optional[str]
|
optional category of Actor to check; if specified,
attempt to match |
None
|
**kwargs
|
Any
|
kwargs to pass to Actor.match |
{}
|
Returns:
| Type | Description |
|---|---|
list[Actor]
|
list of all Actors that matched |
Raises:
| Type | Description |
|---|---|
NoActorForEvent
|
if no Actors matched |
Source code in hostess/station/bases.py
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 | |
NoActorForEvent
Bases: DoNotUnderstand
This Matcher has no Actor that matches this Event.
Source code in hostess/station/bases.py
519 520 | |
NoConfigError
Bases: DoNotUnderstand
This Delegate received a 'configure' Instruction, but the Instruction did not specify what to configure.
Source code in hostess/station/bases.py
530 531 532 533 534 | |
NoInstructionType
Bases: DoNotUnderstand
This Delegate received an Instruction that did not specify what type of Instruction it was.
Source code in hostess/station/bases.py
537 538 539 540 541 | |
NoMatch
Bases: Exception
This Actor does not match an event passed to its check() method. This
Exception is used primarily for control flow.
Source code in hostess/station/bases.py
544 545 546 547 548 | |
NoMatchingDelegate
Bases: Exception
A Station, possibly via one of its Actors, attempted to dispatch an Instruction to one of its Delegates, but found no appropriate Delegate.
Source code in hostess/station/bases.py
551 552 553 554 555 | |
NoTaskError
Bases: DoNotUnderstand
This Delegate received a 'do' Instruction, but the Instruction included neither an Action Message or a description of a task to perform.
Source code in hostess/station/bases.py
523 524 525 526 527 | |
Node
Bases: Matcher, ABC
Abstract base class for Delegates and Stations. Defines core behavior like running Sensors, spooling events to Actors, managing a TCPTalk server, constructing an interface, starting up, shutting down, and logging.
Source code in hostess/station/bases.py
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 | |
_ackcheck = None
class-attribute
instance-attribute
optional function used as Node.server's ackcheck argument; can be used
to implement response spooling, dispatching, etc.
config = property(_get_config)
class-attribute
instance-attribute
dict with items 'interface' and 'cdict', describing settable/gettable properties and configurable parameters respectively
exc = None
class-attribute
instance-attribute
shared thread pool for main loop, Sensor loops, some types of Actor execution, and TCP server io and select threads. Note that attached Actors and Sensors that launch threads are not required to launch them in this object. Always None if Node not yet started.
inbox = None
class-attribute
instance-attribute
Optional Mailbox for incoming protobuf Messages.
locked = property(_is_locked, _set_locked)
class-attribute
instance-attribute
is this Node locked?
logfile
instance-attribute
path to log file
server = None
class-attribute
instance-attribute
optional hostess.station.talkie.TCPTalk server.
state = 'stopped'
class-attribute
instance-attribute
Node state description
threads = None
class-attribute
instance-attribute
dict of currently-running or not-yet-cleaned threads running in this
Node's exc pool. Always None if Node is not yet started.
_get_config()
getter for config property
Source code in hostess/station/bases.py
898 899 900 901 902 903 904 905 906 907 908 909 | |
_get_n_threads()
getter for n_threads property
Source code in hostess/station/bases.py
911 912 913 | |
_log(event, **extra_fields)
construct a JSON object from an event and write it into this Node's log file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
Any
|
object to format as JSON object and write to log. this function will try to unnest dicts and protobuf Messages, and is also very happy with simple objects like strings, but will try its best to make a decent JSON representation of anything you pass it. nevertheless, large or complex objects are less likely to produce good results. |
required |
**extra_fields
|
Any
|
extra stuff to write into JSON object. kwarg names specify named fields of the object. Special formatting is available for Exceptions. These arguments should not be large or nested objects. |
{}
|
Source code in hostess/station/bases.py
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 | |
_main_loop()
Implementations of Node must define what they actually do when they're
running. Should only be executed in a thread, and only by
Node._start().
Source code in hostess/station/bases.py
762 763 764 765 766 767 768 | |
_set_logfile()
concrete subclasses must define rules for constructing log filenames.
Source code in hostess/station/bases.py
698 699 700 701 702 | |
_set_n_threads(n_threads)
setter for n_threads property
Source code in hostess/station/bases.py
915 916 917 918 919 920 | |
_shutdown(exception=None)
Implementations of Node must define specific shutdown behavior.
Source code in hostess/station/bases.py
770 771 772 | |
_start()
private method to start the Node. should only be executed by
Node.start().
Returns:
| Type | Description |
|---|---|
Optional[Exception]
|
Unhandled Exception that stopped the Node's main loop, if any. None on intentional shutdown. |
Source code in hostess/station/bases.py
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 | |
add_element(cls, name=None)
Instantiate an Actor or Sensor and associate it with this Node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
Union[type[Actor], type[Sensor]]
|
type of Actor or Sensor to instantiate and associate. |
required |
name
|
Optional[str]
|
optional name for Actor or Sensor used to identify it in this Node's interface/config. name of its class will be used if not specified, plus a numerical suffix if it would collide with the name of an already-attached element. |
None
|
Source code in hostess/station/bases.py
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 | |
busy()
are we too busy to do new stuff?
Source code in hostess/station/bases.py
753 754 755 756 757 758 759 760 | |
identify_elements(element_type=None)
create a dict with names and classes of node's attached elements.
intended as lightweight monitoring information; used to help format
state for the situation app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
element_type
|
Optional[Literal['actors', 'sensors']]
|
"actors" or "sensors" to describe only Actors or Sensors. if None, describe both. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
dict whose keys are actor and sensor names and whose values are
the outputs of |
Source code in hostess/station/bases.py
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 | |
nodeid()
get basic identifying information for this Node.
Returns:
| Type | Description |
|---|---|
dict[str, Union[str, int]]
|
dict whose keys are "name", "pid", and "host". |
Source code in hostess/station/bases.py
718 719 720 721 722 723 724 725 726 727 728 729 | |
restart_server()
(re)start the node's TCPTalk server (if it is supposed to have one).
Source code in hostess/station/bases.py
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 | |
shutdown(exception=None)
Shut down the Node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception
|
Optional[Exception]
|
Unhandled Exception that stopped the Node's main loop, if any. Should be None if called explicitly or as part of a graceful shutdown workflow. |
None
|
Source code in hostess/station/bases.py
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 | |
start()
Start the Node's main loop and, if it is supposed to have one, its TCPTalk server.
Source code in hostess/station/bases.py
704 705 706 707 708 709 710 711 712 713 714 715 716 | |
Sensor
Bases: Matcher, ABC
abstract base class for Node elements that 'watch' some data source. semi-autonomous; runs asynchronously from its parent Node and uses its own Actors to watch the data source and decide what to bother the Node about.
Sensors should generally only be instantiated by methods of a parent Node.
Source code in hostess/station/bases.py
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 | |
actions = ()
class-attribute
instance-attribute
default Actors associated with this class. Sensor.__init__()
instantiates and attaches an Actor of each specified type.
checker
instance-attribute
data-fetching function called by self.check(). Must be defined in
implementations of this class.
loggers = ()
class-attribute
instance-attribute
same, but for logging-only Actors.
poll = property(_get_poll, _set_poll)
class-attribute
instance-attribute
when this Sensor is running in a Node's sensor_loop() function, this
sets interval in seconds between subsequent calls to self.check(). If
not set, it defaults to the poll rate of the parent Node.
_log(*args, **kwargs)
call owning Node's log function. automatically include the fact that this Sensor generated the log entry.
Source code in hostess/station/bases.py
299 300 301 302 303 304 | |
add_element(cls, name=None)
use special Sensor association behavior, and don't permit Sensor mise en abyme.
Source code in hostess/station/bases.py
290 291 292 293 294 295 296 297 | |
associate_actor(cls, name=None)
instantiate an Actor and associate it with this Sensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type[Actor]
|
type of Actor to instantiate and associate |
required |
name
|
Optional[str]
|
optional name for Actor; used to identify it in this Sensor's interface and config. If not specified, defaults to the class name, suffixed with incrementing numbers if it would collide with the name of an already-attached Actor |
None
|
Source code in hostess/station/bases.py
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | |
check(node, **check_kwargs)
Main pointy-end function for Sensor.
Use this Sensor's checker() method to look for new events and, if
there are any, match them against this Sensor's Actors
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
Node
|
Node to inform about any matching events. In normal
operation, this argument will never be explicitly passed: it
will always be this Sensor's owning Node, and will always be
partially evaluated into this method during |
required |
**check_kwargs
|
Any
|
kwargs to pass to |
{}
|
Source code in hostess/station/bases.py
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 | |
element_dict(elements)
Actor/Sensor title formatter for identify_elements() or similar
introspection methods.
Source code in hostess/station/bases.py
585 586 587 588 589 590 591 592 593 | |
inc_name(name, config)
If a string would duplicate an existing key of a dictionary, add a numerical suffix to it to prevent collisions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
key caller would like to add to |
required |
config
|
Mapping[str]
|
mapping caller would like to use |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in hostess/station/bases.py
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | |
validate_instruction(instruction)
First-pass Instruction validation function. Called by Delegates on Instruction receipt; can also be used as an independent validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instruction
|
Message
|
Instruction to validate. |
required |
Raises:
| Type | Description |
|---|---|
NoInstructionType
|
if |
NoConfigError
|
if a 'configure' Instruction does not specify a config. |
NoTaskError
|
if a 'do' instruction does not specify a task to perform. |
Source code in hostess/station/bases.py
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 | |
station.comm
simple, robust protocol for messaging and serialized data transfer.
CODE_TO_MTYPE = MPt({0: 'none', 1: 'Update', 2: 'Instruction', 3: 'PythonObject'})
module-attribute
one-byte-wide codes for Message type of comm body. "none" means the comm body is not a serialized protobuf Message.
HEADER_STRUCT = struct.Struct('<8sBL')
module-attribute
struct specification for hostess comm header.
HOSTESS_ACK = b'\x06hostess'
module-attribute
hostess acknowledgement code
HOSTESS_EOM = b'\x03hostess'
module-attribute
hostess end-of-message code
HOSTESS_SOH = b'\x01hostess'
module-attribute
hostess start-of-header code
make_comm(body)
create a hostess comm from a buffer or a protobuf Message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
body
|
Union[bytes, Message]
|
byte string or hostess Message to use as comm body |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
hostess comm as |
Source code in hostess/station/comm.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | |
read_comm(buffer, unpack_proto=False)
read a hostess comm from a byte string. if the comm's header says its body contains a hostess Message protobuf, attempt to decode it as a Message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
bytes
|
|
required |
unpack_proto
|
bool
|
if True and the comm contains a protobuf, unpack it into a dictionary rather than returning a 'raw' Message. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Union[dict, bytes, Message, str]]
|
a dict containing the decoded header, the (possibly decoded) body, |
dict[str, Union[dict, bytes, Message, str]]
|
and any errors. |
Source code in hostess/station/comm.py
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 | |
read_header(buffer)
read a hostess header from the first 13 bytes of buffer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
bytes
|
a |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Union[str, bool, int]]
|
dict with keys: "mtype": name of body's hostess Message type as given in header; "none" if the header says the body is not a serialized Message "length": body length as given in header |
Source code in hostess/station/comm.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | |
station.delegates
Delegate
Bases: Node
Source code in hostess/station/delegates.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 | |
__init__(station_address, name, elements=(), n_threads=4, poll=0.08, timeout=10, update_interval=10, start=False, loginfo=MPt({}), _is_process_owner=False)
configurable remote processor for hostess network. can gather data and/or execute actions based on the elements attached to it. should typically be instantiated via the launch_delegate() method of the supervising Station.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_address
|
tuple[str, int]
|
(hostname, port) of supervising Station |
required |
name
|
str
|
identifying name for delegate |
required |
n_threads
|
int
|
max threads in executor |
4
|
elements
|
tuple[Union[type[Sensor], type[Actor]]]
|
Sensors or Actors to add to delegate at creation. |
()
|
poll
|
float
|
delay, in seconds, for polling loops |
0.08
|
timeout
|
int
|
timeout, in s, for intra-hostess communications |
10
|
update_interval
|
float
|
interval, in s, for check-in Updates to supervising Station |
10
|
Source code in hostess/station/delegates.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
_base_message(**fields)
construct a basic Update message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**fields
|
Union[Message, str, Sequence[Message], int]
|
dict of Update field names + values to add to the base Update. |
{}
|
Returns:
| Type | Description |
|---|---|
Update
|
a pro.Update message suitable for sending to the Station. Contains delegate id, timestamp, delegate state, running actions, and anything passed in **fields. |
Source code in hostess/station/delegates.py
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 | |
_check_actions()
check running actions (threads launched as part of a 'do' instruction). if any have crashed or completed, log them and report them to the Station, then remove them from the thread cache.
Source code in hostess/station/delegates.py
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 | |
_check_in()
send heartbeat Update to the Station.
Source code in hostess/station/delegates.py
318 319 320 321 | |
_execute_task_with_actors(actors, instruction, key, noid)
helper function for execute_do_instruction(). run each matching Actor in sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
actors
|
Sequence[Actor]
|
matching actors (output of _match_task_instruction()) |
required |
instruction
|
Instruction
|
"do" Instruction |
required |
key
|
Optional[Hashable]
|
instruction id or randomly-generated key |
required |
noid
|
bool
|
True if the instruction didn't come with an id (should never happen), False normally |
required |
Source code in hostess/station/delegates.py
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
_handle_instruction(instruction)
interpret, reply to, and execute (if relevant) an Instruction. should only be called as part of the main loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instruction
|
Instruction
|
Instruction received from Station. |
required |
Source code in hostess/station/delegates.py
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 | |
_insert_state(message)
insert the Delegate's current state information into an Update.
Called immediately before every attempt to send an Update to the Station.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Update
|
Update to update. |
required |
Returns:
| Type | Description |
|---|---|
Update
|
the updated Update. |
Source code in hostess/station/delegates.py
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 | |
_interpret_response(response)
interpret a response from the Station. If it contains an Instruction, append it to this Delegate's instruction_queue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
bytes
|
bytes containing a hostess com received from the Station. |
required |
Returns:
| Type | Description |
|---|---|
str
|
"err" if the comm failed to decode properly, "ok" if the comm decoded properly but did not contain an Instruction (like a simple acknowledgment comm), "instruction" if the comm contained an Instruction. |
Source code in hostess/station/delegates.py
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 | |
_match_task_instruction(instruction)
wrapper for self.match that specifically checks for actors that can execute a task described in an Instruction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instruction
|
Instruction
|
Instruction containing a task. |
required |
Returns:
| Type | Description |
|---|---|
list[Actor]
|
list of this Delegate's Actors that match the Instruction. |
Raises:
| Type | Description |
|---|---|
NoActorForEvent
|
if none of this Delegate's Actors match. |
Source code in hostess/station/delegates.py
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
_reply_to_instruction(instruction, status, err=None)
send a reply Update to an Instruction informing the Station that we will or won't do the thing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instruction
|
Instruction
|
received Instruction |
required |
status
|
Literal['bad_request', 'wilco']
|
"wilco" if we'll do it, "bad_request" if we won't/can't |
required |
err
|
Optional[Any]
|
Object -- a code or Exception, usually -- explaining a "bad_request" status. None if status is "wilco". |
None
|
Source code in hostess/station/delegates.py
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 | |
_report_on_action(action)
report to Station on completed/failed action. should only be called as part of the main loop, specifically from _check_on_actions().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
dict
|
a value of this delegate's |
required |
Source code in hostess/station/delegates.py
304 305 306 307 308 309 310 311 312 313 314 315 316 | |
_running_actions_message()
helper function for constructing Updates.
Returns:
| Type | Description |
|---|---|
list[TaskReport]
|
list of TaskReport Messages, one for each currently-running action. |
Source code in hostess/station/delegates.py
558 559 560 561 562 563 564 565 566 567 568 | |
_send_exit_report(exception=None)
send Update to Station informing it that Delegate is exiting (and why).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception
|
Optional[Exception]
|
unhandled Exception that caused Delegate's main loop to exit. None on intentional shutdown. |
None
|
Source code in hostess/station/delegates.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | |
_send_info()
construct an Update based on everything in the actionable_events cache and send it to the Station, then clear actionable_events.
Source code in hostess/station/delegates.py
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
_sensor_loop(sensor)
continuously check a Sensor. this function must be launched in its own thread or it will block and be useless. NOTE: should only be called from _start().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sensor
|
Sensor
|
Sensor to poll. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Union[str, Optional[int], Optional[Exception]]]
|
dict with keys: name: name of sensor signal: signal sent to terminate this function (if any) exception: exception that terminated this function (if any) |
Source code in hostess/station/delegates.py
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 | |
_set_logfile()
internal function to set path to log file.
Source code in hostess/station/delegates.py
95 96 97 98 99 100 101 | |
_shutdown(exception=None)
internal shutdown handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception
|
Optional[Exception]
|
Exception that terminated Delegate's main loop, if any. should be None on a 'graceful' shutdown. |
None
|
Source code in hostess/station/delegates.py
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 | |
_trysend(message)
try to send a message to the Station. Sleep if it doesn't work -- or if we're shut down, just assume the Station is dead and leave.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
Message to send to station. |
required |
Source code in hostess/station/delegates.py
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 | |
add_actionable_event(event, category=None)
Queue an actionable event, usually received from a Sensor, for transmission to the Station. This method is most often called by an Actor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
Any
|
object we'd like Station to know about |
required |
category
|
Optional[Union[str, Sensor]]
|
optional label for type of event or originating Sensor, used to update self.infocount |
None
|
Source code in hostess/station/delegates.py
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 | |
check_on_action(instruction_id)
check whether one of this delegate's Actions completed. if it crashed,
set its status and exception keys appropriately in this delegate's
actions dict. typically called as part of the main Delegate loop,
specifically from _check_on_actions().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instruction_id
|
int
|
numerical identifier of Action to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
exception |
Optional[Exception]
|
None if the Action terminated successfully or hasn't yet terminated; the Exception the Action raised if it didn't terminate successfully. |
done |
bool
|
True if the Action has terminated; False if not. |
Source code in hostess/station/delegates.py
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 | |
execute_do_instruction(instruction)
identify matching Actors and execute a "do" Instruction (an Instruction specifying an action). typically called from the _handle_instruction() workflow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instruction
|
Instruction
|
Instruction to match and execute. |
required |
Source code in hostess/station/delegates.py
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 | |
talk_to_station(message)
send a Message to the Station and queue any returned Instruction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
hostess protobuf Message to send to the Station |
required |
Returns:
| Type | Description |
|---|---|
Union[str, bytes]
|
status code for exchange: "ok" if successful but no Instruction received (simple acknowledgement comm received); "timeout" or "connection refused" for failed connections; "err" for receipt of bytes we could not decode as a comm; "instruction" if successful and comm contained an Instruction |
Source code in hostess/station/delegates.py
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 | |
HeadlessDelegate
Bases: Delegate
simple Delegate implementation that just does stuff on its own. mostly for testing/prototyping but could easily be useful.
Source code in hostess/station/delegates.py
672 673 674 675 676 677 678 679 680 681 682 683 684 | |
launch_delegate(station_address, name, delegate_module='hostess.station.delegates', delegate_class='Delegate', elements=None, is_local=False, **init_kwargs)
hook for launching a delegate, designed to be easily called either locally or from an interpreter running in a separate process. Designed to be called as part of the Station.launch_delegate() workflow, but may be used in other ways.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_address
|
tuple[str, int]
|
address of supervising Station |
required |
name
|
str
|
name to assign to Delegate instance |
required |
delegate_module
|
str
|
name of, or path to, module in which the desired Delegate subclass is defined |
'hostess.station.delegates'
|
delegate_class
|
str
|
name of Delegate subclass |
'Delegate'
|
elements
|
tuple[tuple[str, str]]
|
specifications for Actors and Sensors to attach to Delegate instance |
None
|
is_local
|
bool
|
is this Delegate being instantiated in the process of the calling Station (or other launcher) or not? if this is False, consider this process "owned by" the instantiated Delegate; terminate it when the Delegate shuts down. |
False
|
Returns:
| Type | Description |
|---|---|
Optional[Delegate]
|
the instantiated Delegate if is_local is not False; None otherwise. |
Source code in hostess/station/delegates.py
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 | |
station.handlers
shared helper functions for Station objects
SKIPKEYS = frozenset({'delegateid', 'state', 'running', 'arguments', 'localcall', 'data', 'result', 'config'})
module-attribute
keys of Node-internal data structures that we don't generally want to write into logs, either because they often have huge values or because they're generally redundant.
flatten_for_json(event, maxlen=128, maxdepth=3, skipkeys=SKIPKEYS)
simple log-formatting function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
Union[Message, dict]
|
protobuf Message or dict to flatten |
required |
maxlen
|
int
|
maximum length for stringified values of flattened dict |
128
|
maxdepth
|
int
|
maximum depth to dig into |
3
|
skipkeys
|
Collection[str]
|
keys / Message field of |
SKIPKEYS
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
flattened version of |
Source code in hostess/station/handlers.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
json_sanitize(value, maxlen=128, maxdepth=1, skipkeys=SKIPKEYS, depth=0, skip=False)
Attempt to make an object representable in JSON, with standardized
formatting conventions that include automated skipping, truncation, etc.
Primarily intended as a helper function for flatten_for_json().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
object to make representable |
required |
maxlen
|
int
|
maximum length of string representations of elements of sanitized object |
128
|
maxdepth
|
int
|
maximum depth to dig into nested objects. |
1
|
skipkeys
|
Collection[str]
|
keys or fields to omit from output. |
SKIPKEYS
|
depth
|
int
|
current dig depth. automatically incremented in recursive calls to this function. |
0
|
skip
|
bool
|
if True, just return the literal string ' |
False
|
Returns:
| Type | Description |
|---|---|
Union[str, int, float, list[str], dict[str, Union[str, dict[str, str]]]]
|
JSON-sanitized version of |
Source code in hostess/station/handlers.py
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 | |
make_actiondict(action)
construct a standardized dict for recording the results of an action
described by action.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
Action
|
a pro.Action message |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
a dict initialized from basic identifying information in |
Source code in hostess/station/handlers.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
make_function_call(action)
parse an Action Message containing specifications for a function call and create a "deferred" version of a call that matches those specifications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
Action
|
hostess Action Message that specifies a function call. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
caches |
dict[str, list]
|
dict of lists the deferred call will write its stdout, stderr, and return values into |
deferred |
Callable
|
partially-evaluated and wrapped function constructed from
the function call specification in |
Source code in hostess/station/handlers.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
tail_file(position, *, path=None, **_)
simple file-tail function for use in Sensors that watch a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
position
|
Optional[int]
|
byte offset from start of file at which to begin reading. if None, start at the beginning of the file. |
required |
path
|
Optional[Path]
|
path to file. Typically partially evaluated into the function by the Sensor, not explicilty passed. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
end |
Optional[int]
|
position of last read byte of file, or None if the file doesn't exist. |
lines |
list[str]
|
all lines of file between |
'
Source code in hostess/station/handlers.py
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 | |
unpack_callargs(arguments)
unpack PythonObject Messages into a dict of kwargs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arguments
|
Sequence[PythonObject]
|
sequence of PythonObject Messages |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict constructed from deserialized content of |
Source code in hostess/station/handlers.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
watch_dir(contents, *, path=None, **_)
simple ls-like diff for use by Sensors intended that watch a directory.
Source code in hostess/station/handlers.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
station.messages
utilities for interpreting and constructing hostess protobuf Messages.
Mailbox
manager class for lists of messages
Source code in hostess/station/messages.py
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 | |
Msg
Helper class for hostess protobuf Messages. Allows hostess classes to (usually) abstract away protobuf-specific qualities of Messages. Also Improves efficiency of internal Node operations by caching encode/decode operations.
Although Msg is not actually immutable, it should be treated as if it were immutable due to its aggressive caches. If the 'content' of a Msg needs to change, you should always construct a new one rather than modifying it inplace.
Source code in hostess/station/messages.py
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 | |
comm
cached
property
self.message serialized into a hostess comm.
__init__(message)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
protobuf Message, preferably a hostess-specific protobuf Message. |
required |
Source code in hostess/station/messages.py
395 396 397 398 399 400 401 402 | |
unpack(field=None)
cached
Source code in hostess/station/messages.py
409 410 411 412 413 414 415 416 417 418 419 420 | |
byteorder()
format system byteorder for inclusion in a struct.Struct format string.
Returns:
| Type | Description |
|---|---|
str
|
"<" on little-endian platforms, ">" on big-endian platforms. |
Source code in hostess/station/messages.py
45 46 47 48 49 50 51 52 | |
default_arg_packing(kwargs)
convert a dict that represents kwargs for a function call into a list of pro.PythonObjects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
dict[str, Any]
|
|
required |
Returns:
| Type | Description |
|---|---|
list[PythonObject]
|
list of pro.PythonObject Messages giving names and serialized values
of |
Source code in hostess/station/messages.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
dict2msg(mapping, proto_class, mtypes=(dict, MPt), proto_module=pro, pack_objects=True)
construct a protobuf from a dict, filtering any keys that are not fields
of proto_class and recursively diving into nested dicts.
Source code in hostess/station/messages.py
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 | |
format_message(unpacked, maxlen=256)
default string formatter for unpacked message. TODO: more sophisticated behavior.
Source code in hostess/station/messages.py
621 622 623 624 625 626 627 628 629 630 631 632 | |
make_action(description=None, **fields)
construct a default pro.Action message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
description
|
Optional[dict[str, str]]
|
optional dict to use as "description" field of Action. For terse task descriptions to agents that may only need to hear a single name or number to know what to do. |
None
|
**fields
|
Union[bool, Mapping[str, str], Message, int, str]
|
kwargs to interpret as fields of Action Message. Must include "call" if description is None. |
{}
|
Returns:
| Type | Description |
|---|---|
Action
|
a pro.Action Message. |
Raises:
| Type | Description |
|---|---|
TypeError
|
if you specified neither a description or a call. |
Source code in hostess/station/messages.py
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 | |
make_function_call_action(func, module=None, kwargs=MPt({}), context='thread', **action_fields)
make a pro.Action Message specifying a Python function call.
Source code in hostess/station/messages.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | |
make_instruction(instructiontype, **kwargs)
Standardized factory function for Instruction Messages. This is generally
the most convenient and reliable way to create an Instruction for a
Station to send to a Delegate. Station uses it by default to create
'configure' and 'shutdown'-type Instructions, and it is an essential
component of most InstructionFromInfo.instruction_maker functions.
Automatically adds a timestamp and a random id to the Instruction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instructiontype
|
str
|
type of instruction to make, typically 'do', 'configure', or 'stop'. |
required |
kwargs
|
Union[int, Message, Mapping[str, str], Sequence[Message]]
|
Message fields and values to include in Instruction. |
{}
|
Returns:
| Type | Description |
|---|---|
Instruction
|
a hostess Instruction protobuf Message. |
Source code in hostess/station/messages.py
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 | |
obj2scanf(obj)
construct a struct / scanf format string for obj, along with a code for
the 'string' type if it is str, bytes, or NoneType (struct strings
represent all these types with 's', so an additional code is required for
recipients to reconstruct them as the correct Python type).
This function accepts most primitive Python types, as well as lists or tuples of primitive types. Does not accept sequences of mixed 'string' types.
Note that this function is generally not useful for lists or tuples containing mixed data types or many distinct strings/bytestrings. It will in general be more efficient to serialize them some other way, because the struct string itself will often be long enough to negate the benefits of terse binary packing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Union[int, float, None, str, bytes, tuple[Union[int, float], tuple[None], tuple[str], tuple[bytes], list[Union[int, float]], list[None], list[str], list[bytes]]]
|
object for which to construct format string |
required |
Returns:
| Name | Type | Description |
|---|---|---|
format_string |
str
|
format string for |
string_code |
Optional[str]
|
"none" if |
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
Source code in hostess/station/messages.py
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 | |
pack_obj(obj, name='')
default function for serializing an in-memory object as a pro.PythonObject
Message. If obj is "scalar", serialize it using simple struct formatting;
if it is a np.ndarray of non-object type, use its ndarray.tobytes()
representation; otherwise, serialize it using dill. This is a good
function for general-purpose object passing, and is used extensively in
internal Node behaviors. However, it may in some cases be more efficient
to implement serialization functions optimized for specific data formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
object to serialize as a |
required |
name
|
str
|
optional name for |
''
|
Returns:
| Type | Description |
|---|---|
PythonObject
|
|
Source code in hostess/station/messages.py
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 | |
scalarchar(scalar)
Determine an appropriate format code and, if necessary, byte string type identifier for a 'scalar' object, to be used as a component of a struct.Struct format string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scalar
|
Union[str, bytes, int, float, list, tuple, bool, None]
|
object for which to determine code / identifier |
required |
Returns:
| Name | Type | Description |
|---|---|---|
code |
str
|
format code for |
string_identifier |
Optional[str]
|
"none" if scalar is |
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
Source code in hostess/station/messages.py
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 | |
task_msg(actiondict, steps=None)
construct a hostess TaskReport Message from an actiondict (a dict of
the format produced by make_actiondict() and expected by Delegates as
values of their actions attribute). Delegates call this function to
help construct Updates to a Station describing the results of a completed
task (whether successful or failed).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
actiondict
|
dict
|
dict containing data from and metadata about a completed
task (see |
required |
steps
|
Sequence[dict]
|
Placeholder for 'pipeline' behavior. Not currently implemented; must always be None. |
None
|
Returns:
| Type | Description |
|---|---|
TaskReport
|
A hostess TaskReport that can be used as the "completion" field of a hostess Update. |
Source code in hostess/station/messages.py
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 | |
unpack_obj(obj)
Default deserialization function for pro.PythonObject Messages. Used extensively in internal Node behaviors and by stock Actors. Good for general-purpose object passing, although it may in some cases be more efficient to implement fancier deserialization optimized for a specific application's data models or formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
PythonObject
|
hostess PythonObject Message. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
object deserialized from |
Source code in hostess/station/messages.py
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 | |
station.proto_utils
utilities for dealing with the protobuf format. Not intended for hostess-specific messages -- these are more generic utilities.
PROTO_TYPES = MPt({(getattr(FieldDescriptor, k)): (k.replace('TYPE_', '')) for k in (dir(FieldDescriptor)) if k.startswith('TYPE')})
module-attribute
mapping from protobuf type codes to types
m2d = google.protobuf.json_format.MessageToDict
module-attribute
alias for google.protobuf.json_format.MessageToDict
enum(message, field)
get the string or int value of an enum field in a protobuf Message. (If you directly access the field with the Python API, you will get the enum key instead of its value, which is generally less useful.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
protobuf Message containing an enum field |
required |
field
|
str
|
name of enum field |
required |
Returns:
| Type | Description |
|---|---|
Union[str, int]
|
enum value of |
Source code in hostess/station/proto_utils.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
make_duration(delta)
create a Duration Message from a float or a dt.timedelta object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta
|
Union[timedelta, float]
|
total duration -- if a float, always represents seconds. |
required |
Returns:
| Type | Description |
|---|---|
Duration
|
a protobuf Duration Message specifying the same timespan as |
Source code in hostess/station/proto_utils.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | |
make_timestamp(datetime=None)
create a Timestamp Message from either the current time or a dt.datetime object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datetime
|
Optional[datetime]
|
if None, make a Timestamp from the current time. if a dt.datetime, make a Timestamp from it. |
None
|
Returns:
| Type | Description |
|---|---|
Timestamp
|
protobuf Timestamp Message. |
Source code in hostess/station/proto_utils.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
proto_formatdict(proto)
return a (possibly nested) dict showing the legal fields of a protobuf message or message type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
proto
|
Union[Message, Descriptor]
|
protobuf Message or Descriptor whose format to describe |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Union[dict, str]]
|
dict whose keys are field names and whose values are protobuf data types or nested dicts (representing child Messages) of the same format. |
Source code in hostess/station/proto_utils.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | |
station.station
DelegateContext
module-attribute
code denoting the relationship between a Delegate's execution context and its supervising Station's interpreter process. "local" means that the Delegate is (or will be) running in separate threads of the same process; "subprocess" means a child process of the Station's interpreter process; "daemon" means a double-forked, fully-disowned and separate process.
Station
Bases: Node
central control node for hostess network. can receive Updates from and send Instructions to Delegates.
Source code in hostess/station/station.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 | |
running_delegates
property
get metadata dicts for all still-running Delegates.
unfinished_delegates
property
get metadata dicts for all still-running Delegates executing in local context (this Station's process).
__init__(host, port, name='station', n_threads=8, max_inbox_mb=250, logdir=Path(__file__).parent / '.nodelogs', _is_process_owner=False, **kwargs)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
hostname or address for Station. usually should be your external IP address for remote connections and 'localhost' for local use. |
required |
port
|
int
|
port this Station's TCP server will listen on. |
required |
name
|
str
|
name for Station. |
'station'
|
n_threads
|
int
|
how many threads should the Station use? |
8
|
max_inbox_mb
|
float
|
how large can the Station's inbox get, in MB, before it dumps older Messages? |
250
|
logdir
|
Path
|
where should the Station write logs? |
parent / '.nodelogs'
|
_is_process_owner
|
bool
|
if True, the Station will attempt to stop the Python interpreter when it shuts down. |
False
|
**kwargs
|
Union[bool, tuple[Union[type[Sensor], type[Actor]]], float, int]
|
additional kwargs for the Node constructor (see Node documentation for valid options). |
{}
|
Source code in hostess/station/station.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
_ackcheck(_conn, comm)
callback for interpreting comms and responding as appropriate.
should only be called inline of the ack() method of the Station's
server attribute (a talkie.TCPTalk object).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
_conn
|
socket
|
open |
required |
comm
|
dict
|
decoded hostess comm as produced by |
required |
Returns:
| Name | Type | Description |
|---|---|---|
response |
bytes
|
response to comm |
description |
str
|
loggable description of response type / status |
Source code in hostess/station/station.py
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 | |
_check_delegates()
Update time-based elements of metadata dicts for our Delegates.
Crucial step of Station's main loop. Should only be called by
Station._main_loop().
Source code in hostess/station/station.py
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 | |
_handle_incoming_message(update)
Top-level dispatcher function for handling Updates from Delegates. Route wilco, state, info, and report components of Update -- if any -- to the appropriate methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
update
|
Update
|
Update Message from Delegate. |
required |
Source code in hostess/station/station.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | |
_handle_info(message)
Handler for 'info' Updates. Unpack all the "notes" (serialized Python objects + metadata) bundled in an info Update and match each one against our Actors, executing each Actor that matches a note with that note.
If message is an exit report, also always log its info.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Update
|
Update Message from a Delegate. |
required |
Source code in hostess/station/station.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | |
_handle_report(update)
Handler for "completion" Updates received from Delegates. Perform action tracking and cleanup, and execute any appropriate follow-on actions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
update
|
Update
|
'completion' Update from Delegate. |
required |
Source code in hostess/station/station.py
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 | |
_handle_state(update)
update the info dict for one of our Delegates in response to state and id elements of an Update Message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
update
|
Update
|
Update Message from Delegate. |
required |
Source code in hostess/station/station.py
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 | |
_handle_wilco(update)
handle 'wilco' Update from a Delegate. Delegates send these on receipt of Instructions prior to actually performing them. Record time and whether or not the Delegate acknowledged that it understood and would follow the Instruction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
update
|
Update
|
'wilco' Update Message from Delegate. |
required |
Source code in hostess/station/station.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
_launch_delegate_in_subprocess(context, kwargs)
staticmethod
Launch a delegate in a child or daemonized process. Should only be
called by Station.launch_delegate().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
DelegateContext
|
how to launch the delegate. Should only be 'daemon' or 'subprocess'; if 'local', we should never have gotten here. |
required |
kwargs
|
dict[str, Any]
|
kwargs for launch, passed to |
required |
Source code in hostess/station/station.py
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 | |
_main_loop()
launch main loop for Station. This should only be called by
Station._start(), which should only be called by Station.start().
Source code in hostess/station/station.py
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 | |
_record_message(box, msg, pos)
helper function for Station._ackcheck(). write log entry for sent
Message and record it as sent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
box
|
Mailbox
|
outbox for Delegate we sent Message in msg to |
required |
msg
|
Msg
|
wrappper for Message we sent to delegate |
required |
pos
|
int
|
index of msg within box |
required |
Source code in hostess/station/station.py
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 | |
_select_outgoing_message(delegate)
Helper function for Station._ackcheck(). When we receive an Update
from one of our Delegates and we've got one or more Instructions
prepared for them, we reply with one. This function checks if we have
any Instructions for that Delegate, and, if so, picks which we should
send.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delegate
|
str
|
name of Delegate we're talking to. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Mailbox]
|
|
Optional[Instruction]
|
|
Optional[int]
|
|
Source code in hostess/station/station.py
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 | |
_set_logfile()
create standardized log file name.
Source code in hostess/station/station.py
93 94 95 96 97 98 | |
_shutdown(exception=None)
shut down the Station. This method should normally be called only by
Station.shutdown().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception
|
Optional[Exception]
|
unhandled Exception that caused shutdown, if any. |
None
|
Source code in hostess/station/station.py
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 | |
_situation_comm()
Construct a hostess comm describing this Station's overall situation.
The hostess situation app works by constructing human-readable
representations of these comms.
Source code in hostess/station/station.py
855 856 857 858 859 860 861 862 863 864 | |
_update_task_record(msg)
helper function for _ackcheck(). update task record associated with a 'do' Instruction so that we know that we sent it and when.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
Msg
|
wrapper for 'do' Instruction we just sent to a Delegate. |
required |
Source code in hostess/station/station.py
593 594 595 596 597 598 599 600 601 602 603 | |
get_delegate(name)
return delegate info structure for first Delegate named "name" (there should never be more than one unless someone has seriously messed with the Station).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
name of Delegate |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
info |
Source code in hostess/station/station.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 | |
launch_delegate(name, elements=(), host='localhost', update_interval=0.25, context='daemon', **kwargs)
launch a Delegate, by default daemonized. prepare a metadata dict for it, and prepare ourselves to receive Messages from it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
name to assign to Delegate. |
required |
elements
|
Sequence[tuple[str, str]]
|
sequence of (module_name, class_name) describing Actors and Sensors Delegate should construct and attach to itself at launch. |
()
|
host
|
str
|
hostname or ip on which Delegate should launch. remote launch is not yet implemented. |
'localhost'
|
update_interval
|
float
|
how frequently the Delegate should send unprompted 'heartbeat' Updates to this Station. |
0.25
|
context
|
DelegateContext
|
where to launch the Delegate in relation to this Station's interpreter process: "local" to run threaded in the same process; "subprocess" to run in a child process; "daemon" to run in a fully-detached process. |
'daemon'
|
kwargs
|
Union[int, float]
|
additional kwargs to pass to
|
{}
|
Returns:
| Type | Description |
|---|---|
Optional[Node]
|
None if |
Source code in hostess/station/station.py
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 | |
match_and_execute(obj, category)
Check to see if we have an Actor or Actors intended to handle obj
by calling their match() methods with obj. If any of them say they
can deal with obj, pass obj to their execute() methods.
In a typical Station application, obj will be something a Delegate
packed into a "completion" or "info" Update. Its type will be entirely
application-dependent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
object one of our Actors might be able to work with |
required |
category
|
str
|
what category of Actor might be able to work with |
required |
Source code in hostess/station/station.py
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 | |
queue_task(delegate, instruction)
queue an Instruction for a Delegate and set up tracking for its state. this method is intended for "do" Instructions that contain Actions, not Instructions we do not want to track in the same way (like config). The default InstructionFromInfo Actor uses this method to queue the Instructions it makes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delegate
|
str
|
name of Delegate for which to queue task |
required |
instruction
|
Instruction
|
Instruction Message |
required |
Source code in hostess/station/station.py
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 | |
relaunch_delegate(name)
Relaunch an existing Delegate with the same initialization settings, although not full runtime configuration. If it's still running, shut it down first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
name of Delegate to relaunch. |
required |
Source code in hostess/station/station.py
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 | |
save_port_to_shared_memory(address=None)
write this Station's port number to a shared memory address, allowing
other applications to query or monitor it. Specifically, calling this
function will allow the hostess situation app to automatically find
this Station.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
address
|
Optional[str]
|
shared memory address to write port to. Exactly what this means depends on the operating environment. In CPython on Linux, it denotes a filename in /dev/shm. if not specified, defaults to the name of this Station. |
None
|
Source code in hostess/station/station.py
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 | |
set_delegate_config(delegate, config)
Construct a 'configure' Instruction for a Delegate that instructs it to merge a config dict into its existing config dict; put that Instruction in the outbox for that Delegate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delegate
|
str
|
name of Delegate to configure |
required |
config
|
Mapping
|
configuration to add to the Delegate's config dict. |
required |
Source code in hostess/station/station.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
set_delegate_properties(delegate, **propvals)
Construct a 'configure' Instruction for a Delegate that instructs it to assign specific values to named properties of itself; put that Instruction in the outbox for that Delegate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delegate
|
str
|
name of delegate to configure. |
required |
propvals
|
Any
|
argument names correspond to property names of target Delegate; argument values will be serialized as PythonObject Messages and then bundled into ConfigParam Messages. |
{}
|
Source code in hostess/station/station.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
shutdown_delegate(delegate, how='stop')
make a shutdown Instruction and queue it in the outbox for the specified Delegate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delegate
|
str
|
name of Delegate we would like to shut down |
required |
how
|
Literal['stop', 'kill']
|
"stop" if we would like the Delegate to shut down gracefully; "kill" if we would like the Delegate to stop immediately no matter what. |
'stop'
|
Source code in hostess/station/station.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 | |
blank_delegateinfo()
utility function for Station. creates an empty Delegate metadata dict.
Returns: "blank" Delegate metadata dict suitable for use as an element of Station.delegates.
Source code in hostess/station/station.py
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 | |
get_port_from_shared_memory(memory_address='station')
fetch a named Station's port number from a shared memory address. Used
by the hostess situation app; can also be used by other 'plugins' or
for ad-hoc inspection of a Station.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
memory_address
|
str
|
shared memory address a Station's port number might be stored in. Exactly what this means depends on the environment. In CPython on Linux, it denotes a filename in /dev/shm. |
'station'
|
Returns:
| Type | Description |
|---|---|
int
|
port number of Station that saved its port number to |
Source code in hostess/station/station.py
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 | |
station.talkie
TCPTalk
lightweight multithreaded tcp server.
Source code in hostess/station/talkie.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | |
locked = property(_get_locked, _set_locked)
class-attribute
instance-attribute
is the server locked, preventing it from communicating with peers? note that TCPTalk never locks itself. Its optional lockout behavior is intended to be handled by some sort of lock object shared with a handler application, for cases in which something needs locks for synchronization.
__init__(host, port, n_threads=4, poll=0.01, decoder=read_comm, ackcheck=None, executor=None, lock=None, chunksize=16384, delay=0.01, timeout=10)
Note: TCPTalk immediately starts running when initialized.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
hostname for server's socket, either an ip address or a resolvable name like "localhost" |
required |
port
|
int
|
port number for server's socket |
required |
n_threads
|
int
|
number of i/o threads. server will always launch n_threads + 1 threads; the +1 is its selector thread. |
4
|
poll
|
float
|
poll/spool delay for threads |
0.01
|
decoder
|
Optional[Callable]
|
optional callable used to decode received messages |
read_comm
|
ackcheck
|
Optional[Callable]
|
callable for inserting message responses -- this can be used to attach a Station's responder rules to the server |
None
|
executor
|
Optional[ThreadPoolExecutor]
|
optional ThreadPoolExecutor, if the server should run in existing thread pool |
None
|
lock
|
Optional[Lock]
|
optional lock, if the tcp server should be subject to an external lockout |
None
|
chunksize
|
int
|
chunk size for reading responses from socket |
16384
|
delay
|
float
|
time to wait before checking socket again after failed read |
0.01
|
timeout
|
int
|
timeout on socket |
10
|
Source code in hostess/station/talkie.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
_accept(sock)
accept-connection callback for i/o threads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sock
|
socket
|
TCP socket we've received a connection request on. in normal operation, this will always be self.sock. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
stream |
None
|
always None. (present for signature compatibility) |
event |
str
|
"blocking" if accepting connection would block; "accept" on successful accept |
peername |
Optional[tuple[str, int]]
|
name of peer on successful accept (tuple of ip address, fileno). None if blocking (because peer name is not known). |
status |
str
|
"blocking on self" if blocking, "ok" on successful accept |
Source code in hostess/station/talkie.py
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 | |
_ack(data, peersock)
acknowledgement callback for read threads. calls self.ackcheck if we have one; if we don't, just sends an empty comm to the peer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
decoded object or raw bytes read from peersock. this is typically not passed directly but rather curried into a copy of _ack() constructed in _read(). |
required |
peersock
|
socket
|
open socket to peer. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
stream |
None
|
always None. for signature compatibility |
event |
str
|
"ack attempt" if attempt failed; for successful ack, if we have an ackcheck function, whatever status code it returned, or "sent_ack" if we don't have an ackcheck |
status |
str
|
empty string if we have no response; "ok" on successful ack; description of error on failed ack |
Source code in hostess/station/talkie.py
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 | |
_check_peerage(key)
check to see if another thread is already handling a peer. essentially a synchronization lock function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Union[SelectorKey, socket]
|
socket to peer, or selector key wrapping socket |
required |
Returns:
| Name | Type | Description |
|---|---|---|
peername |
Optional[tuple[str, int]]
|
tuple of (ip, fileno), or None if connection on socket is not yet accepted or socket is already closed |
peered |
bool
|
True if another thread is handling the peer, False if not (including if the socket is pending/unreadable) |
Source code in hostess/station/talkie.py
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 | |
_get_locked()
getter for self.locked
Source code in hostess/station/talkie.py
142 143 144 145 146 | |
_handle_callback(callback, peername, peersock)
inner callback-handler tree for i/o threads. should only ever be
called from an io thread loop (TCPTalk.launch_io()).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
Callable
|
one of self._read, self._ack, or self._accept. attached to peersock by self.sel, queued by a call to self.sel.register in an io or selector thread. |
required |
peername
|
Optional[str]
|
name of peer, if known (tuple of (ip, fileno)). |
required |
peersock
|
socket
|
open socket to peer |
required |
Returns:
| Name | Type | Description |
|---|---|---|
stream |
Any
|
decoded or raw bytes read from socket, if any |
event |
str
|
description of event, primarily for logging |
peername |
Optional[tuple[str, int]]
|
existing or newly-discovered peername (ip, fileno), or None if we still don't know it |
status |
str
|
code for event, primarily for control flow |
Source code in hostess/station/talkie.py
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 | |
_read(peersock)
read-from-socket callback for i/o threads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peersock
|
socket
|
open socket to peer |
required |
Returns:
| Name | Type | Description |
|---|---|---|
stream |
Any
|
output of self.decoder on successful read and decode; bytes read from peersock on successful read and failed decode; None on failed read |
event |
str
|
description of read/decode length or read/decode error |
status |
str
|
"ok" if everything went well, error code if not |
Source code in hostess/station/talkie.py
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 | |
_set_locked(_val)
intentionally nonfunctional setter for self.locked. Always raises AttributeError.
Source code in hostess/station/talkie.py
148 149 150 151 152 153 | |
_trydecode(stream)
inner stream-decode handler function for self.read().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
bytes
|
bytes received from peer. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
stream |
Any
|
output of self.decoder, if successful; undecoded stream if not. |
event |
str
|
"decoded {nbytes}" on successful decode; "read {nbytes}" on failed decode |
status |
str
|
"ok" if successful; description of decode error if not |
Source code in hostess/station/talkie.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
_tryread(peersock)
inner read-individual-chunk-from-socket handler for read
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peersock
|
socket
|
open socket to read chunk from |
required |
Returns:
| Name | Type | Description |
|---|---|---|
data |
Optional[bytes]
|
bytes read from peersock, if any |
status |
str
|
"streaming" if receive operation was successful; "unavailable" if peer is temporarily unavailable |
Raises:
| Type | Description |
|---|---|
OSError
|
for any OSError other than temporary unavailability |
Source code in hostess/station/talkie.py
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
kill(signal=0)
immediately shut down, closing the server's socket and attempting to terminate all its threads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
int
|
termination signal to send to threads. changing this number does nothing special by default and is intended for subclasses or application-specific purposes. |
0
|
Source code in hostess/station/talkie.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | |
launch_io(name)
launch a read thread in this server's executor. must be run in a thread or it will block and be useless.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
Union[str, int]
|
identifier for thread |
required |
Source code in hostess/station/talkie.py
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 | |
launch_selector()
launch the server's selector thread.
Source code in hostess/station/talkie.py
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
queued_descriptors()
Returns:
| Type | Description |
|---|---|
set[int]
|
set of all file descriptors for currently-queued sockets. Primarily for selector thread loop but can also be used diagnostically. |
Source code in hostess/station/talkie.py
209 210 211 212 213 214 215 216 | |
tend()
check on all threads we believe to be running. If any of them aren't, relaunch them. Never called automatically.
Returns:
| Type | Description |
|---|---|
Optional[list]
|
None, if server is still initializing. otherwise, list of Exceptions raised by crashed threads (empty if none crashed). |
Source code in hostess/station/talkie.py
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 | |
read_from_socket(headerread, sock, timeout)
one-shot read-all-data-from-socket function
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
headerread
|
Optional[Callable[[bytes], dict]]
|
optional function to read data header in order to determine total data size |
required |
sock
|
socket
|
open socket to peer |
required |
timeout
|
float
|
timeout duration |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
bytes received from peer |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
if any attempt to read a chunk of data takes more than timeout seconds |
Source code in hostess/station/talkie.py
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 | |
stsend(data, host, port, timeout=10, delay=0, chunksize=None)
wrapper for tcp_send() that autoencodes data as hostess comms. Used by
Delegates to send comms to their Station.
See tcp_send() for a full description of arguments and return values.
Source code in hostess/station/talkie.py
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 | |
tcp_send(data, host, port, timeout=10, delay=0, chunksize=None, headerread=None)
one-shot send-data-over-TCP-and-get-response utility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
data to send |
required |
host
|
str
|
hostname (usually ip address or 'localhost') of recipient |
required |
port
|
int
|
port number of recipient |
required |
timeout
|
float
|
how long to wait for successful connection / send (s) |
10
|
delay
|
float
|
delay between sends to socket (s) |
0
|
chunksize
|
Optional[float]
|
chunk size for sends; None means unchunked unless a nonzero
|
None
|
headerread
|
Optional[Callable[[bytes], dict]]
|
optional function to decode response header, specifically in order to determine intended length of response |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
response |
Union[str, bytes]
|
response, if successfully received (possibly an empty bytestring); "timeout" on timeout, "connection refused" on failed connection |
sockname |
Optional[int]
|
file descriptor for socket, if a connection was ever established; None if not |
Source code in hostess/station/talkie.py
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 | |
subutils
utilities for executing, managing, and watching subprocesses
Processlike = Union[Viewer, invoke.runners.Runner, invoke.runners.Result]
module-attribute
union of expected types for interfaces to processes.
CBuffer
wrapper class for a Dispatcher that includes the ability to yield pseudo-buffers that execute the Dispatcher on "write". streamlined alternative to objects like Invoke's Watchers.
Source code in hostess/subutils.py
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 | |
__init__(dispatcher=None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dispatcher
|
Optional[Dispatcher]
|
Dispatcher to associate with any buffers this object produces. the Dispatcher should have at least steps "out", "err", and "done". If not specified, defaults to a simple console handler. |
None
|
Source code in hostess/subutils.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | |
cacheoff()
Pause caching.
Source code in hostess/subutils.py
362 363 364 365 | |
cacheon()
Resume caching.
Source code in hostess/subutils.py
367 368 369 370 371 372 | |
execute(*args, stream, **kwargs)
execute a specified step or steps of the underlying Dispatcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
args to pass to dispatcher.execute() |
()
|
stream
|
Sequence[Union[str, int]]
|
names of steps to execute |
required |
**kwargs
|
Any
|
kwargs to pass to dispatcher.execute() |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
results of dispatcher.execute() |
Source code in hostess/subutils.py
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
make_buffer(step)
Create a buffer for a named step of self.dispatcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step
|
Union[str, int]
|
name of step. |
required |
Returns:
| Type | Description |
|---|---|
DispatchBuffer
|
DispatchBuffer for that step. |
Source code in hostess/subutils.py
374 375 376 377 378 379 380 381 382 383 384 | |
make_callback(signal_generator, step)
create a callback for a named step of self.dispatcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal_generator
|
Optional[Callable[[], Any]]
|
optional niladic function whose output will be used as a signal to the named step of dispatcher. otherwise the callback will execute that step with no arguments. |
required |
step
|
Union[str, int]
|
name of step to execute when callback fires. |
required |
Returns:
| Type | Description |
|---|---|
Callable
|
callback function that takes a waitable object as an optional argument and executes a step of dispatcher when it completes. |
Source code in hostess/subutils.py
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | |
DispatchBuffer
A buffer-like interface to a Dispatcher.
Source code in hostess/subutils.py
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 | |
__init__(dispatcher, step)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dispatcher
|
Dispatcher
|
Dispatcher to associate with this buffer |
required |
step
|
Union[int, str]
|
named step of dispatcher to associate with this buffer |
required |
Source code in hostess/subutils.py
60 61 62 63 64 65 66 67 | |
flush()
staticmethod
remain flushed
Source code in hostess/subutils.py
77 78 79 80 | |
read(_=None)
return the dispatcher's cache for the associated step
Source code in hostess/subutils.py
69 70 71 | |
seek(*args, **kwargs)
staticmethod
seek nowhere
Source code in hostess/subutils.py
82 83 84 85 | |
write(message)
execute the associated step of dispatcher with message
Source code in hostess/subutils.py
73 74 75 | |
Dispatcher
Bases: Composition
Composition capable of skipping steps. By default creates empty caches that can be used as targets for sends but do not autocapture like the superclass's add_captures() method. intended for applications like handling console streams.
Source code in hostess/subutils.py
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 | |
__init__(*args, cached=True, **kwargs)
See Composition's documentation for a full description of valid args and kwargs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
args to pass to the Composition constructor. |
()
|
cached
|
bool
|
if True, retain results of every step in self.caches. |
True
|
**kwargs
|
Any
|
kwargs to pass to the composition constructor. |
{}
|
Source code in hostess/subutils.py
174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
_bind_special_runtime_kwargs(kwargs)
Composition method modified to permit skipping.
Source code in hostess/subutils.py
189 190 191 192 193 194 195 196 197 | |
_do_step(step_name, state)
Composition method modified to permit skipping.
Source code in hostess/subutils.py
199 200 201 202 203 204 | |
reset_caches()
reset and initialize caches.
Source code in hostess/subutils.py
206 207 208 209 210 | |
yield_buffer(step)
construct a buffer whose read and write methods access and execute a cache/step of this object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step
|
Union[str, int]
|
name of step to associate with the DispatchBuffer. |
required |
Source code in hostess/subutils.py
219 220 221 222 223 224 225 226 227 | |
yield_callback(signaler, step)
construct a callback function that fires a step of this object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signaler
|
Optional[Callable[[], None]]
|
an optional niladic function whose output acts as a signal to the step when the callback fires. Otherwise, simply execute the step with no signal. |
required |
step
|
Union[str, int]
|
name of step to execute with this callback. |
required |
Returns:
| Type | Description |
|---|---|
Callable
|
a function that takes one or no arguments. If it is called with no argument, it immediately fires the callback. If it is called with an object with a .wait method, it first calls its .wait method. This function returns whatever executing the step returns. |
Source code in hostess/subutils.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | |
Nullify
A fake buffer.
Source code in hostess/subutils.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
flush()
staticmethod
remain flushed
Source code in hostess/subutils.py
44 45 46 47 | |
read(_size=None)
staticmethod
read nothing
Source code in hostess/subutils.py
34 35 36 37 | |
seek(_hence)
staticmethod
seek nowhere
Source code in hostess/subutils.py
49 50 51 52 | |
write(_obj)
staticmethod
write nothing
Source code in hostess/subutils.py
39 40 41 42 | |
RunCommand
Callable object for managed shell command execution.
Encapsulates an Invoke runner and adds additional syntax and monitoring. Often, but not always, best used as the substrate for a Viewer.
Source code in hostess/subutils.py
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 | |
__call__(*args, **kwargs)
Execute a shell command parsed from args and kwargs.
This method has two legal calling conventions along with a variety of keyword-argument meta-options that modify how it executes the shell command.
Calling conventions
These conventions are not mutually exclusive, although it is generally less confusing to pick one or the other.
1
Pass the shell command as a string. This can be simpler in many cases,
and is mandatory for programs with non-standard calling conventions,
like the ffmpeg command below.
Examples: >>> cmd = RunCommand() >>> cmd('ls') >>> cmd('cp -r /path/to/folder /path/to/other/folder') >>> cmd('ffmpeg -i first.mp4 -filter:v "crop=100:10:20:200" second.mp4')
2
Construct the shell command using multiple arguments to __call__.
This allows you to treat the shell command more like a Python
function, which can be simpler and less error-prone than dynamic
string formatting when you would like to pass variable parameters to a
command.
RunCommand uses the following rules to parse args and kwargs into shell command strings. They are compatible with most, although not all, shell programs:
- RunCommand treats the first positional argument like a shell command name. This means that passing a positional argument is mandatory if you did not bind a command to the RunCommand when creating it. The parsed command string always starts with this argument.
- Subsequent positional arguments are command parameters. By
default, the parser places them at the end of the command string,
after any command options. Pass
_args_at_end=Falseto place them before command options. - Keyword arguments are command options. The parser transforms
keyword argument names in order to make Python naming and calling
conventions compatible with shell conventions.
- It ignores
"_"characters at the start and end of names. This can be used to pass numeric options, like"_0=True", or options that share a name with a Python reserved keyword, like"dir_=/opt". - it treats single-character names (not counting prefixed or
suffixed
"_") as options preceded by a"-"and does not use an'='to separate them from their values.cmd("ls", I="a*")is equivalent to"ls -I a*". - it treats longer names as options preceded by
"--"and uses an'='to separate them from their values.cmd("ls", width=20)is equivalent to"ls --width=20". - It replaces
"_"characters within names with"-".cmd("ls", time_style="iso")is equivalent to"ls --time-style=iso". - if a keyword argument is True, RunCommand treats it as a
"switch".
cmd("ls", a=True)is equivalent to"ls -a". - if a keyword argument is False, RunCommand ignores it.
cmd("ls", a=False)is equivalent to"ls".
- It ignores
Tip
In addition to these conventions, bear in mind that if you
specified a command when you construct a RunCommand object, that
command will always be used as the first positional argument to
__call__(), and if you specified kwargs, they will be added to
any kwargs you pass or don't pass to __call__().
Returns:
Interface object for executed process. Of variable type: if
_viewer=True, a Viewer; if _viewer=False and _bg=True,
an Invoke Result; if _viewer=False and _bg=False, an
Invoke Runner; if _viewer=False and _disown=True,
None (_disown=True overrides the value of _bg.)
Source code in hostess/subutils.py
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 | |
__init__(command=None, ctx=None, runclass=None, chunksize=20000, **kwargs)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
Optional[str]
|
optional string form of a shell command to bind to this object. If you do not pass this, this object will be "generic", able to run any shell command. For instance, ls = RunCommand("ls") constructs a RunCommand just for ls. ls(a=True) will run "ls -a". |
None
|
ctx
|
Optional[Context]
|
optional Context object (just makes a new one if not given) |
None
|
runclass
|
Optional[type(Runner)]
|
optional Runner subclass (uses the default of ctx if not given; if both are None, uses invoke.runners.Local) |
None
|
chunksize
|
int
|
maximum number of bytes to read at once from a child process's stdout/stderr. higher values will generally increase performance but may have undesirable effects in some cases. |
20000
|
**kwargs
|
Any
|
optional keyword arguments to bind to this object; Will be added to any kwargs passed to calls to this object. See call for a complete description of behavior. |
{}
|
Source code in hostess/subutils.py
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 | |
cstring(*args, args_at_end=True, **kwargs)
Create a shell command string from args and *kwargs, including any
command and kwargs curried into this object. Used as part of the
__call__() workflow; can also be used to determine what shell
command this object would execute if you called it.
See __call__ for a complete description of arg and kwarg parsing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
Union[int, float, str]
|
args to parse into shell command |
()
|
args_at_end
|
bool
|
place args after the first at the end of the shell command? |
True
|
kwargs
|
Union[int, float, str]
|
kwargs to parse into shell command |
{}
|
Source code in hostess/subutils.py
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 | |
Viewer
encapsulates an instance of a RunCommand subclass or other process
abstraction. performs a variety of automated output handling, process
initialization, and metadata tracking operations, and also prevents the
abstraction from throwing errors or unexpectedly blocking in REPL
environments. Viewer.from_command() is the preferred constructor for
most purposes.
Viewer pretends to inherit most of the attributes of its encapsulated
process abstraction, so in addition to attributes explicitly defined on
Viewer, you can access attributes like .done and call methods like
.kill().
Source code in hostess/subutils.py
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 | |
from_command(command, *args, ctx=None, runclass=None, cbuffer=None, chunksize=20000, **kwargs)
classmethod
Construct a Viewer from a command. This is the most convenient
constructor for Viewer and should generally be preferred to
Viewer.__init__.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
Union[str, RunCommand]
|
Either a shell command as a string, or an existing
|
required |
args
|
Any
|
additional arguments for the executed shell command. See
|
()
|
ctx
|
Optional[Context]
|
optional Invoke |
None
|
runclass
|
Optional[Runner]
|
underlying Invoke |
None
|
cbuffer
|
Optional[CBuffer]
|
context buffer for |
None
|
chunksize
|
int
|
number of bytes to read at once from stdout/stderr. |
20000
|
kwargs
|
Any
|
additional keyword arguments for the executed shell
command. See |
{}
|
Returns:
| Type | Description |
|---|---|
Viewer
|
a |
Source code in hostess/subutils.py
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 | |
wait_for_output(stream='any', poll=0.05, timeout=10)
Block until the Viewer receives output on the specified stream(s) or its process exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
Literal['out', 'err', 'any']
|
"out" to wait for output on stdout, "err" to wait for output on stderr, "any" for either. |
'any'
|
poll
|
float
|
poll rate (seconds) |
0.05
|
timeout
|
float
|
how long to wait between successive outputs before raising a TimeoutError (seconds) |
10
|
Source code in hostess/subutils.py
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 | |
_submit_callback(callback, waitable)
syntactic sugar for running a function in a thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
Callable[[Any], Any]
|
function to run in the thread. must take at least one argument. |
required |
waitable
|
Any
|
object to call |
required |
Returns:
| Type | Description |
|---|---|
Future
|
A Future object for the threaded callback(waitable) call. |
Source code in hostess/subutils.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 | |
_wait_on(it)
Block until it completes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
it
|
Any
|
immediately call it.wait(). if it has no .wait(), do nothing. |
required |
Source code in hostess/subutils.py
88 89 90 91 92 93 94 95 96 97 98 | |
console_stream_handler(out=None, err=None, done=None, handle_out=None, handle_err=None, handle_done=None)
produce a Dispatcher suited for capturing stdout, stderr, and process completion, optionally with inline callbacks. Used by Viewer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out
|
Optional[MutableSequence]
|
optional existing list to use as cache for stdout; if none specified, creats a new list. |
None
|
err
|
Optional[MutableSequence]
|
same but for stderr. |
None
|
done
|
Optional[MutableSequence]
|
same but for results of done callback. |
None
|
handle_out
|
Optional[Callable[[str], Any]]
|
optional inline formatter/callback for stdout. by default just strips newlines. |
None
|
handle_err
|
Optional[Callable[[str], Any]]
|
same but for stderr. |
None
|
handle_done
|
Optional[Callable]
|
optional callback for process completion; defaults to simply returning the results of the Dispatcher's "done" step. |
None
|
Returns:
| Type | Description |
|---|---|
Dispatcher
|
a Dispatcher ready to handle console streams. |
Source code in hostess/subutils.py
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 | |
defer(func, *args, **kwargs)
Defer a function call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
function whose call to defer |
required |
args
|
Any
|
positional arguments to deferred call |
()
|
kwargs
|
Any
|
keyword arguments to deferred call |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[], Any]
|
A niladic function that, when called, executes |
Source code in hostess/subutils.py
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 | |
deferinto(func, *args, _target, **kwargs)
Defer a function call and redirect its result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
function whose call to defer |
required |
*args
|
Any
|
positional arguments for the deferred call |
()
|
_target
|
MutableSequence
|
object to append the call's return value to (must have an .append() method; a list is suitable) |
required |
**kwargs
|
Any
|
keyword arguments for the deferred call |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[], None]
|
A niladic function that, when called, executes func(args, *kwargs), but appends its return value to _target rather than returning it. |
Source code in hostess/subutils.py
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 | |
dispatch_callback(dispatch, callback=None, step=None, to_wait_on=None)
simple callback for a Dispatcher. See Dispatcher.yield_callback for full documentation.
Source code in hostess/subutils.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | |
done_callback(dispatch, runner)
simple Dispatcher callback for invoke.runner / result completion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dispatch
|
Dispatcher
|
Dispatcher to trigger with callback |
required |
runner
|
Union[Result, Runner]
|
Result or Runner object. fire callback with information about process result when it completes. |
required |
Returns:
| Type | Description |
|---|---|
Future
|
result of dispatcher "done" step executed with return value of locally-defined callback() function. |
Source code in hostess/subutils.py
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 | |
make_call_redirect(func, fork=False)
the middle sibling of the piped() / make_call_redirect() / watched_process() family.
Modify a function so that, when called, it runs in a subprocess, directing its output into a dict of pipes. Intended for longer-term, speculative, or callback-focused functions than piped(). The calling process is always responsible for polling the pipes; watched_process() provides a more automated alternative.
This mutates the return signature of the modified function so that it always returns None. It redirects its return value to the 'result' Pipe.
Note that this function cannot be used with the @ decorator syntax
because it returns a tuple.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
function to be modified. |
required |
fork
|
bool
|
if True, execute |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
redirected_func |
Callable
|
the modified function |
pipes |
dict[str, Pipe]
|
a dict of |
Source code in hostess/subutils.py
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 | |
make_piped_callback(func)
Turn a function into a callback. The decorated function sends its result to a Pipe rather than returning it, allowing its caller to receive output from it even if it is executed in a subprocess.
Note that this is not usable with the @ decorator syntax because it returns a tuple.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
function to turn into a callback. |
required |
Returns:
| Type | Description |
|---|---|
Pipe
|
|
Callable
|
|
Source code in hostess/subutils.py
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 | |
make_watch_caches()
construct an empty 'caches' structure for watched_process()
Returns:
| Type | Description |
|---|---|
dict[str, list]
|
dictionary of lists suitable for capturing output of a watched process |
Source code in hostess/subutils.py
1044 1045 1046 1047 1048 1049 1050 1051 | |
piped(func, block=True)
the youngest sibling of the piped() / make_call_redirect() / watched_process() family.
decorator that modifies a function so that, when called, it executes in a subprocess rather than the calling interpreter's process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
function to decorate |
required |
block
|
bool
|
if True, the decorated function blocks until completion when called (like a regular function). If False, calling the decorated function returns a Process object rather than its normal return value. In this case, the caller is responsible for polling the Process if it wishes to receive a return value from the function. |
True
|
Source code in hostess/subutils.py
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 | |
replace_aliases(mapping, aliasdict)
replace keys of a mapping with aliases. intended primarily as a helper for aliased kwargs. impure; mutates mapping if any keys match aliasdict.
Source code in hostess/subutils.py
419 420 421 422 423 424 425 426 427 428 429 430 | |
run(*args, **kwargs)
run a command not in a Viewer
Source code in hostess/subutils.py
1135 1136 1137 1138 1139 | |
runv(*args, **kwargs)
run a command in a Viewer
Source code in hostess/subutils.py
1130 1131 1132 | |
strip_newline(text)
just strip newlines. helper function for console streams.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
string to strip. |
required |
Returns:
| Type | Description |
|---|---|
str
|
text stripped of newlines. |
Source code in hostess/subutils.py
258 259 260 261 262 263 264 265 266 267 268 | |
trydelete(obj, target)
attempt to delete the key or item named "obj" from target. Do nothing if it doesn't exist.
Source code in hostess/subutils.py
408 409 410 411 412 413 414 415 416 | |
watched_process(func, *, caches, fork=False)
the eldest sibling of the piped() / make_call_redirect() / watched_process() family.
decorate a function so that calling it will execute it in a subprocess rather than the calling interpreter's process, redirecting its stdout, stderr, and any return value to 'caches'.
This mutates the decorated function's call and return signatures. It adds the kwargs _blocking (default True) and _poll (default 0.05), which set auto-join/poll and poll interval (s) respectively.
If _blocking is True, calling the decorated function blocks until the subprocess exits and returns a tuple whose first element is its normal return value and whose second argument is the caches dict. This should generally be used in a thread, unless you have some unusual reason to execute a subprocessed function serially.
If _blocking is False, the decorated function returns a tuple whose first value is a Process object and whose second value is a dict of pipes. Note that in this case, the calling process is responsible for polling the pipes if it wishes to receive output.
Note that caches is a mandatory argument with no default value. To use this function with the @ decorator syntax, do something like:
IMAGE_OUTPUT = make_watch_caches()
@watched_process(caches=IMAGE_OUTPUT)
def process_image( ...
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
function to run in subprocess |
required |
caches
|
MutableMapping[str, MutableSequence]
|
dict of lists for func's output. 'result' will contain any return value; 'out', its stdout; 'err', its stderr. make_watch_caches() constructs a suitable set of empty caches. |
required |
fork
|
bool
|
if True, double-fork the subprocess so it will not terminate if the calling process exits. |
False
|
Returns:
| Type | Description |
|---|---|
Callable
|
function with mutated signature that, when called, executes in a subprocess. |
Source code in hostess/subutils.py
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 | |
utilities
generic utility objects for hostess
HOSTESS_CONSOLE = rich.console.Console()
module-attribute
convenient shared rich console
Aliased
generic wrapper for aliasing a class method.
Examples:
If you'd like a library function to append to a list, but it's only
willing to write:
>>> import json
>>> my_list = []
>>> writeable_list = Aliased(my_list, ("write",), "append")
>>> json.dump([1, 2, 3], writeable_list)
>>> print(writeable_list)
Aliased: ('write',) -> append:
['[1', ', 2', ', 3', ']']
Source code in hostess/utilities.py
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 | |
configured(func, config)
decorator that permits dynamic partial evaluation of a function.
configured splats config into all calls to the decorated
function, so that its behavior can change along with changes to the
contents of config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
function to configure |
required |
config
|
Mapping[str, Any]
|
mapping to use as extra kwargs to func |
required |
Returns:
| Type | Description |
|---|---|
Callable
|
version of |
Source code in hostess/utilities.py
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | |
console_and_log(message, level='info', style=None)
print a message to console and log it with this module's default logger.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Any
|
object to print and log. must be compatible with both default logger and rich.console.Console.print. strings or numbers are recommended. |
required |
level
|
str
|
logging level as a string ("info", "warning", etc.) |
'info'
|
style
|
Optional[Union[str, Style]]
|
optional rich Style or string description of one, e.g. "red" |
None
|
Source code in hostess/utilities.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
curry(func, *args, **kwargs)
alias for cytoolz.curry with type hinting. this is a hack to improve PyCharm's static analysis.
Source code in hostess/utilities.py
256 257 258 259 260 261 262 263 | |
dcom(string, sep=';', bad=(',', '\n'))
simple string sanitization function. the default values assume that you want to jam the string into a CSV field. always assumes you don't care about distinguishing different forbidden characters from one another in the output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string
|
str
|
string to sanitize |
required |
sep
|
str
|
separator to replace 'bad' characters with |
';'
|
bad
|
Collection[str]
|
characters to replace with sep |
(',', '\n')
|
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in hostess/utilities.py
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
filestamp()
shorthand for standardized event stamp that is also a legal filename
Source code in hostess/utilities.py
42 43 44 | |
gb(b, round_to=2)
utility function to convert B to GB.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
b
|
float
|
how many bytes? |
required |
round_to
|
Optional[int]
|
if not None, round output to this many digits. |
2
|
Returns:
| Type | Description |
|---|---|
float
|
|
Source code in hostess/utilities.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
get_module(module_name)
dynamically import a module by name. check to see if it's already in sys.modules; if not, just try to import it; if that doesn't work, try to interpret module_name as a path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module_name
|
str
|
name of or path to a Python module. |
required |
Returns:
| Type | Description |
|---|---|
ModuleType
|
a module, hopefully. |
Source code in hostess/utilities.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | |
infer_stream_length(stream)
attempts to infer the size of a potential read from an object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
Union[BufferedReader, BinaryIO, Path, str, Response]
|
may be a buffered reader (like the result of calling open()), a buffer like io.BytesIO, or a Path |
required |
Returns:
| Type | Description |
|---|---|
Optional[int]
|
an estimate of its size based on best available method, or None if |
Optional[int]
|
impossible. |
Source code in hostess/utilities.py
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 | |
is_any(obj, coll)
like obj in coll, for use in cases when obj and coll do not, or
might not, support use of in.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
an object |
required |
coll
|
Iterable
|
a collection |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if |
Source code in hostess/utilities.py
466 467 468 469 470 471 472 473 474 475 476 477 478 | |
logstamp(extra=0)
shorthand for standardized text timestamp only (no hostname)
Source code in hostess/utilities.py
47 48 49 | |
mb(b, round_to=2)
utility function to convert B to MB.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
b
|
int
|
how many bytes? |
required |
round_to
|
Optional[int]
|
if not None, round output to this many digits. |
2
|
Returns:
| Type | Description |
|---|---|
float
|
|
Source code in hostess/utilities.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
notary(cache=None, be_loud=False, resolution=0)
create a function that records, timestamps, and optionally prints messages. if you pass eject=True to that function, it will return its note cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache
|
Optional[MutableMapping]
|
cache for notes (if None, creates a dict) |
None
|
be_loud
|
bool
|
if True, makes output function verbose by default. individual calls can override this setting. |
False
|
resolution
|
int
|
time resolution in significant digits after the second. collisions can occur if entries are sent faster than the time resolution. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
note |
Callable[[Any], Optional[MutableMapping]]
|
function for notetaking |
Source code in hostess/utilities.py
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 | |
record_and_yell(message, cache, loud=False, extra=0)
place message into a cache object with a timestamp; optionally print it
Source code in hostess/utilities.py
174 175 176 177 178 179 180 181 182 | |
signal_factory(threads)
creates a 'signaler' function that simply assigns values to a mapping bound in enclosing scope. this is primarily intended as a simple inter-thread communication utility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threads
|
MutableMapping[Hashable, Optional[int]]
|
mapping from thread names to None or ints. In normal usage, named threads will poll the key of this mapping corresponding to their name to check for received signals. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Hashable, Optional[int]], None]
|
a process that takes a thread name and an optional integer (default
0) and assigns that integer to the corresponding key of the
|
Source code in hostess/utilities.py
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 | |
stamp()
create standardized text event stamp
Source code in hostess/utilities.py
37 38 39 | |
timeout_factory(raise_timeout=True, timeout=5)
returns a tuple of functions. calling the first starts a wait timer if not started, and also returns current wait time. calling the second resets the wait timer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raise_timeout
|
bool
|
if True, raises TimeoutError if waiting > timeout. otherwise, this is basically just a stopwatch. |
True
|
timeout
|
float
|
timeout in seconds. Used only if raise_timeout is True. |
5
|
Source code in hostess/utilities.py
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 | |
unix2dt(epoch)
alias for dt.datetime.fromtimestamp().
Source code in hostess/utilities.py
250 251 252 | |
yprint(obj, indent=0, replace_null=True, maxlen=256)
lazy way to pretty-print many objects by using pyyaml's excellent YAML
formatter. Doesn't work well for everything.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
object to pretty-print |
required |
indent
|
int
|
indentation in spaces |
0
|
replace_null
|
bool
|
if True, replace the YAML value 'null' with 'None' |
True
|
maxlen
|
int
|
maximum length of output |
256
|
Returns:
| Type | Description |
|---|---|
str
|
mildly stylized YAML representation of |
Source code in hostess/utilities.py
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 | |