1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 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
|
#!/bin/sh
# BIG NOTE: Not bash, not any other predetermined shell implementation
#
# NOTE: This script is intentionally written with portable shell constructs
# with the aim and hope to work in different interpreters, so it is a
# bit dumber and less efficient than could be achieved with the more
# featured shells in the spectrum. Also, to minimize the in-memory and
# debug-console traffics, tests for (non-)emptiness of anticipated large
# strings are not done by `test -n/-z`, but by counting the size of the
# string (zero or not).
# NOTE ALSO: The configuration parser in this script is not meant to be a
# reference or 100% compliant with what the binary code uses; its aim
# is to just pick out some strings relevant for tracking config changes.
#
# Copyright (C) 2016-2020 Eaton
# Copyright (C) 2020-2025 Jim Klimov <jimklimov+nut@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#! \file nut-driver-enumerator.sh(.in)
# \author Jim Klimov <EvgenyKlimov@eaton.com>
# \brief Enumerate NUT devices for service-unit instance configuration
# \details This script allows to enumerate UPSes in order to produce the
# individual service unit instances for each defined configuration.
# It assumes the user has adequate permissions to inspect and create
# services (e.g. is a root or has proper RBAC profiles to do so).
# It helps service frameworks such as Linux systemd and Solaris SMF.
# When executed, this script looks for all configured ups.conf
# sections and registered service instances, and makes these two
# lists match up. It has also a mode to do this in a loop, to keep
# checking for differences and applying them, on systems where it's
# problematic to trigger it in response to FS event notifications.
# Returns exit codes:
# 0 Sections and services already match up
# 42 Sections and services differed, but now match up -
# now the caller should likely restart some services.
# Note that the drivers' service instances were started or
# stopped as required (by AUTO_START=yes) - but maybe the
# upsd or upsmon services should restart. If you pass envvar
# REPORT_RESTART_42=no then this codepath would return 0.
# In default mode, such non-null reconfiguration should cause
# the nut-driver-enumerator service to restart and this would
# propagate to other NUT services that depend on it.
# 13 Sections and services differed, and still do not match up
# 1 Bad inputs, e.g. unrecognized service management framework
# 2 Absent or unreadable ups.conf file
#
# NOTE: Currently found caveats that might be solved later but require
# considerable effort:
# * Solaris SMF constrains the syntax of valid strings for instance names
# (e.g. not starting with a digit, no period chars) which blocks creation
# of some UPS driver instances. This might be worked around by hashing
# the device name e.g. to base64 (and un-hashing instance name when calling
# upsdrvctl), but is not quite user-friendly. Also can store device name
# in a service attribute while mangling the instance name to a valid subset.
# Comparisons (if devices are already wrapped) becomes more complicated in
# the script in either case, as well as in the service startup method.
# ** The `+` `/` `=` characters from base64 are also invalid for SMF instance
# name, but the first two can be sed'ed to `-` `_` and back, for example.
# Some prefix word is also needed (avoid starting with a digit).
# The trailing padding `=` can be dropped, and added until we get a
# non-empty decode. Conversions can be done by
# `echo "$string" | openssl base64 -e|-d`
# * Dummy-UPS services that "proxy" another locally defined section are
# essentially a circular dependency for upsd. While the system might
# start-up lacking a driver, there should be some timer to re-enable
# failed not-disabled drivers (would be useful in any case though).
# Directory where NUT configs are located, e.g. /etc/nut or /etc/ups
# Set at package configuration, compiled into daemons and drivers
prefix="/usr/local/ups"
[ -n "${NUT_CONFPATH-}" ] || NUT_CONFPATH="${prefix}/etc"
# Technically this should be a distribution-dependent value configured
# during package build. But everyone has it the same from systemd defaults:
[ -n "${SYSTEMD_CONFPATH-}" ] || SYSTEMD_CONFPATH="/etc/systemd/system"
if [ -n "$ZSH_VERSION" ]; then
### Problem: loops like `for UPS in $UPSLIST` do not separate
### the UPSLIST into many tokens but use it as one string.
echo "FATAL: zsh is not supported in this script" >&2
exit 1
# setopt noglob
# setopt +F
# IFS="`printf ' \t\r\n'`" ; export IFS
fi
if set | grep -E '^(shell|version|t?csh)' | grep -E 't?csh' >/dev/null ; then
echo "FATAL: csh or tcsh is not supported in this script" >&2
exit 1
fi
# Third-party services to depend on (can be overridden by config file)
### Note that for systemd+udev integration, it may be better to set up
### triggers in udev, see e.g.
### http://stackoverflow.com/questions/18463755/linux-start-daemon-on-connected-usb-serial-dongle
### Also can tune whether a driver "Wants" another service (would consider
### ordering if that one is enabled, but live if it is disabled), or if it
### "Requires" that (would cause that to start).
DEPSVC_USB_SYSTEMD="systemd-udevd.service nut-udev-settle.service"
DEPREQ_USB_SYSTEMD="Wants"
# Serial drivers may rely on USB dongles or even custom-owned real ports:
DEPSVC_SERIAL_SYSTEMD="systemd-udevd.service nut-udev-settle.service"
DEPREQ_SERIAL_SYSTEMD="Wants"
DEPSVC_NET_FULL_SYSTEMD="network-online.target systemd-resolved.service ifplugd.service"
DEPREQ_NET_FULL_SYSTEMD="Wants"
DEPSVC_NET_LOCAL_SYSTEMD="network.target"
DEPREQ_NET_LOCAL_SYSTEMD="Wants"
SVCNAME_SYSTEMD="nut-driver"
# Some or all of these FMRIs may be related to dynamically changing hardware
# require_all) ;; # All cited services are running (online or degraded)
# require_any) ;; # At least one of the cited services is running
# optional_all) ;; # (All) cited services are running or would not run
# # without administrative action (disabled, maintenance,
# # not present, or are waiting for dependencies which do
# # not start without administrative action).
DEPSVC_USB_SMF="svc:/system/hotplug:default svc:/system/dbus:default svc:/system/hal:default svc:/milestone/devices:default"
DEPREQ_USB_SMF="optional_all"
# By default there are several physical network FMRIs shipped and at most
# only one is enabled on a particular system (e.g. :default or :nwam)
DEPSVC_NET_FULL_SMF="svc:/network/physical svc:/milestone/name-services"
DEPREQ_NET_FULL_SMF="optional_all"
DEPSVC_NET_LOCAL_SMF="svc:/network/loopback:default"
DEPREQ_NET_LOCAL_SMF="optional_all"
SVCNAME_SMF="svc:/system/power/nut-driver"
[ -z "${NUT_DRIVER_ENUMERATOR_CONF-}" ] && \
NUT_DRIVER_ENUMERATOR_CONF="${NUT_CONFPATH}/nut-driver-enumerator.conf"
[ -s "${NUT_DRIVER_ENUMERATOR_CONF}" ] && \
echo "Sourcing config file: ${NUT_DRIVER_ENUMERATOR_CONF}" && \
. "${NUT_DRIVER_ENUMERATOR_CONF}"
[ -z "${UPSCONF-}" ] && \
UPSCONF="${NUT_CONFPATH}/ups.conf"
# Start a freshly-registered unit?
[ -z "${AUTO_START-}" ] && AUTO_START=yes
# We avoid regex '\t' which gets misinterpreted by some tools
TABCHAR="`printf '\t'`" || TABCHAR=' '
if [ -z "${SERVICE_FRAMEWORK-}" ] ; then
[ -x /usr/sbin/svcadm ] && [ -x /usr/sbin/svccfg ] && [ -x /usr/bin/svcs ] && [ -x /usr/bin/svcprop ] && \
SERVICE_FRAMEWORK="smf"
[ -z "${SERVICE_FRAMEWORK-}" ] && \
[ -x /bin/systemctl ] && \
SERVICE_FRAMEWORK="systemd"
fi
# Optionally use Coreutils timeout to limit the
# (potentially hanging) calls to systemd tools...
# Should not hurt with SMF too, if it ever misbehaves.
if [ -z "${TIMEOUT_CMD+x}" ]; then
# Envvar not set at all (set but empty is okay, caller wants that then)
TIMEOUT_CMD=""
TIMEOUT_ARGS=""
if which timeout 2>/dev/null >/dev/null ; then
# Systemd default timeout for unit start/stop
TIMEOUT_CMD="timeout"
TIMEOUT_ARGS="90s"
fi
fi
# Should be populated by configure script during NUT build:
NUT_WEBSITE_BASE='https://www.networkupstools.org/historic/v2.8.3'
# Fallback, no trailing slash!
[ -n "${NUT_WEBSITE_BASE-}" ] || NUT_WEBSITE_BASE='https://www.networkupstools.org'
# Cache needed bits of ups.conf to speed up later parsing. Note that these
# data are needed for most operations, and populated by upslist_readFile()
UPSCONF_DATA=""
# Subset of normalized data above that only has sections, drivers and ports (SDP)
UPSCONF_DATA_SDP=""
# List of configured UPSes in the config-file
UPSLIST_FILE=""
# List of configured service instances for UPS drivers
UPSLIST_SVCS=""
# Framework-specific implementations are generally hooked here:
hook_registerInstance=""
hook_unregisterInstance=""
hook_refreshSupervizor=""
hook_listInstances=""
hook_listInstances_raw=""
hook_validInstanceName=""
hook_validFullUnitName=""
hook_validInstanceSuffixName=""
hook_getSavedDeviceName=""
hook_findSavedDeviceName=""
hook_setSavedDeviceName=""
hook_setDocLink=""
hook_getSavedMD5=""
hook_setSavedMD5=""
hook_restart_upsd=""
hook_restart_drv=""
case "${SERVICE_FRAMEWORK-}" in
smf)
hook_registerInstance="smf_registerInstance"
hook_unregisterInstance="smf_unregisterInstance"
hook_refreshSupervizor="smf_refreshSupervizor"
hook_listInstances="smf_listInstances"
hook_listInstances_raw="smf_listInstances_raw"
hook_validInstanceName="smf_validInstanceName"
hook_validFullUnitName="smf_validFullUnitName"
hook_validInstanceSuffixName="smf_validInstanceSuffixName"
hook_getSavedDeviceName="smf_getSavedDeviceName"
hook_findSavedDeviceName="smf_findSavedDeviceName"
hook_setSavedDeviceName="smf_setSavedDeviceName"
hook_setDocLink="smf_setDocLink"
hook_getSavedMD5="smf_getSavedMD5"
hook_setSavedMD5="smf_setSavedMD5"
hook_restart_upsd="smf_restart_upsd"
hook_restart_drv="smf_restart_drv"
;;
systemd)
hook_registerInstance="systemd_registerInstance"
hook_unregisterInstance="systemd_unregisterInstance"
hook_refreshSupervizor="systemd_refreshSupervizor"
hook_listInstances="systemd_listInstances"
hook_listInstances_raw="systemd_listInstances_raw"
hook_validInstanceName="systemd_validInstanceName"
hook_validFullUnitName="systemd_validFullUnitName"
hook_validInstanceSuffixName="systemd_validInstanceSuffixName"
hook_getSavedDeviceName="systemd_getSavedDeviceName"
hook_findSavedDeviceName="systemd_findSavedDeviceName"
hook_setSavedDeviceName="systemd_setSavedDeviceName"
hook_setDocLink="systemd_setDocLink"
hook_getSavedMD5="systemd_getSavedMD5"
hook_setSavedMD5="systemd_setSavedMD5"
hook_restart_upsd="systemd_restart_upsd"
hook_restart_drv="systemd_restart_drv"
;;
selftest)
hook_registerInstance="selftest_NOOP"
hook_unregisterInstance="selftest_NOOP"
hook_refreshSupervizor="selftest_NOOP"
hook_listInstances="selftest_NOOP"
hook_listInstances_raw="selftest_NOOP"
hook_validInstanceName="selftest_NOOP"
hook_validFullUnitName="selftest_NOOP"
hook_validInstanceSuffixName="selftest_NOOP"
hook_getSavedDeviceName="selftest_NOOP"
hook_findSavedDeviceName="selftest_NOOP"
hook_setSavedDeviceName="selftest_NOOP"
hook_setDocLink="selftest_NOOP"
hook_getSavedMD5="selftest_NOOP"
hook_setSavedMD5="selftest_NOOP"
hook_restart_upsd="selftest_NOOP"
hook_restart_drv="selftest_NOOP"
;;
"")
echo "Error detecting the service-management framework on this OS" >&2
exit 1
;;
*)
echo "Error: User provided an unknown service-management framework '$SERVICE_FRAMEWORK'" >&2
exit 1
;;
esac
selftest_NOOP() {
echo "NO-OP: Self-testing context does not do systems configuration" >&2
return 0
}
common_isFiled() {
[ "${#UPSLIST_FILE}" != 0 ] && \
for UPSF in $UPSLIST_FILE ; do
[ "$1" = "$UPSF" ] && return 0
[ "`$hook_validInstanceName "$UPSF"`" = "$1" ] && return 0
done
return 1
}
common_isRegistered() {
[ "${#UPSLIST_SVCS}" != 0 ] && \
for UPSS in $UPSLIST_SVCS ; do
[ "$1" = "$UPSS" ] && return 0
[ "`$hook_validInstanceName "$1"`" = "$UPSS" ] && return 0
done
return 1
}
upslist_equals() {
# Compare pre-sorted list of DEVICES ($1) and SVCINSTs ($2) including
# the possible mangling for service names. Return 0 if lists describe
# exactly same set of devices and their services.
# Note: This logic only checks the names, not the contents of device
# sections, so re-definitions of an existing device configuration
# would not trigger a service restart by itself. Such deeper check
# belongs in a different routine, see upssvcconf_checksum_unchanged().
# Trivial case 0: one string is empty, another is not
# Note: `echo '' | wc -l` == "1" not "0"!
[ "${#1}" != 0 -a "${#2}" = 0 ] && return 1
[ "${#1}" = 0 -a "${#2}" != 0 ] && return 1
# Trivial case 1: equal strings
[ "$1" = "$2" ] && return 0
# Trivial case 2: different amount of entries
[ "`echo "$1" | wc -l`" = "`echo "$2" | wc -l`" ] || return $?
_TMP_DEV_SVC=""
for _DEV in $1 ; do
DEVINST="`$hook_validInstanceName "${_DEV}"`"
for _SVC in $2 ; do
[ "${_DEV}" = "${_SVC}" ] \
|| [ "$DEVINST" = "${_SVC}" ] \
&& { [ "${#_TMP_DEV_SVC}" = 0 ] \
&& _TMP_DEV_SVC="${_DEV} = ${_SVC}" \
|| _TMP_DEV_SVC="${_TMP_DEV_SVC}
${_DEV} = ${_SVC}" ; }
done
done
# Input was not empty; did anything in output fit?
[ "${#_TMP_DEV_SVC}" = 0 ] && return 1
# Exit code : is the built mapping as long as the source list(s)?
[ "`echo "$1" | wc -l`" = "`echo "${_TMP_DEV_SVC}" | wc -l`" ]
}
upssvcconf_checksum_unchanged() {
# $1 = dev, $2 = svc
# compare checksums of the configuration section from the file and the
# stashed configuration in a service instance (if any).
# FIXME : optimize by caching, we likely have quite a few requests
[ "`upsconf_getSection_MD5 "$1"`" = "`$hook_getSavedMD5 "$2"`" ]
}
upslist_checksums_unchanged() {
# For each device and its corresponding unit, compare checksums of the
# configuration section from the file and the stashed configuration in
# a service instance. Prints a list of mismatching service names that
# should get reconfigured.
[ "${#1}" = 0 -o "${#2}" = 0 ] && return 1
_TMP_SVC=""
for _DEV in $1 ; do
DEVINST="`$hook_validInstanceName "${_DEV}"`"
for _SVC in $2 ; do
if [ "${_DEV}" = "${_SVC}" ] \
|| [ "$DEVINST" = "${_SVC}" ] \
; then
upssvcconf_checksum_unchanged "${_DEV}" "${_SVC}" || \
{ [ "${#_TMP_SVC}" = 0 ] \
&& _TMP_SVC="${_SVC}" \
|| _TMP_SVC="${_TMP_SVC}
${_SVC}" ; }
fi
done
done
[ "${#_TMP_SVC}" = 0 ] && return 0
echo "${_TMP_SVC}"
return 1
}
upslist_savednames_find_missing() {
# Verify that all existing service units have a saved DEVICE name
# Report those that do not have a value there (any value) so we can
# amend those quickly after an upgrade. Otherwise we trust these.
# Return codes:
# 0) Some services were defined and at least one had DEVICE values
# (those that did not are reported in stdout)
# 1) No services defined yet (empty stdout)
# 2) All service units do not have DEVICE values (all reported in stdout)
# Get full instance names from system and from props
SVCINSTS="`$hook_listInstances_raw`" && [ "${#SVCINSTS}" != 0 ] || return 1
# If no props were found, (over)write them all
SVCINST_PROPS="`$hook_findSavedDeviceName`" && [ "${#SVCINST_PROPS}" != 0 ] \
|| { echo $SVCINSTS ; return 2; }
# Find and report services which do *not* have saved device names in
# props (do not report those that have a non-trivial prop value):
# whether an empty value or completely absent from the list
for SVCINST in $SVCINSTS ; do
echo "$SVCINST_PROPS" | grep -E "^${SVCINST}${TABCHAR}"'$' >/dev/null && echo "$SVCINST"
echo "$SVCINST_PROPS" | grep -E "^${SVCINST}${TABCHAR}" >/dev/null || echo "$SVCINST"
done
return 0
}
upslist_savednames_find_mismatch() {
# NOTE: Not used currently (as of NUT v2.8.2)
# TODO: Make use of this to fsck the enumerator configs
# TODO: Complete checking MD5 normalized names if original not hit
# TODO: Report all unit names if none has the DEVICE values? (code 2)
#
# Verify that all existing service units have a saved DEVICE name
# and that such name does match the unit instance's name (original
# or MD5 normalized version). If something does not match, returns
# the unit name so it can be redefined by caller. This does not
# inspect whether such DEVICE is defined in NUT configuration.
# This situation might occur in some errors, but the likely case
# is updating from versions that did not track this info yet (but
# upslist_savednames_find_missing() should have handled those).
# Return codes:
# 0) Some services were defined and at least one had DEVICE values
# (those that did not are reported in stdout)
# 1) No services defined yet (empty stdout)
# 2) All service units do not have DEVICE values (empty stdout)
# Get full instance names from system and from props
SVCINSTS="`$hook_listInstances_raw`" && [ "${#SVCINSTS}" != 0 ] || return 1
SVCINST_PROPS="`$hook_findSavedDeviceName`" && [ "${#SVCINST_PROPS}" != 0 ] || return 2
# Find services whose props exist but services themselves do not
# (e.g. upgrading from some version with different naming patterns)
echo "$SVCINST_PROPS" | while read SVCINST_PROP DEVNAME_PROP ; do
echo "$SVCINSTS" | grep -E "^${SVCINST_PROP}"'$' >/dev/null || echo "$SVCINST_PROP"
done
# Find and report services which do *not* have saved device names in
# props (do not report those that have a non-trivial prop value):
# whether an empty value or completely absent from the list
for SVCINST in $SVCINSTS ; do
echo "$SVCINST_PROPS" | grep -E "^${SVCINST}${TABCHAR}"'$' >/dev/null && echo "$SVCINST"
echo "$SVCINST_PROPS" | grep -E "^${SVCINST}${TABCHAR}" >/dev/null || echo "$SVCINST"
done
return 0
}
upsconf_getSection_content() {
# "$1" = name of ups.conf section to display in whole, from whatever
# comes on stdin (file or a pre-made normalized variable)
# empty "$1" means the global config (before any sections)
#
# NOTE (TODO?): This routine finds the one NUT device section, prints it
# and returns when the section is over. It currently does not cover (in
# a way allowing to do it efficiently) selection of several sections,
# or storing each section content in some array or dynamic variables
# (as would be better fit for portable shells) to later address them
# quickly without re-parsing the file or big envvar many times.
#
CURR_SECTION=""
SECTION_CONTENT=""
RES=1
[ -n "$1" ] || RES=0
while read LINE ; do
case "$LINE" in
\["$1"\])
if [ "$RES" = 0 ]; then
# We have already displayed a section, here is a new one,
# and this routine only displays one (TODO: toggle?)
break
fi
SECTION_CONTENT="$LINE"
CURR_SECTION="$1"
RES=0
continue
;;
\[*\ *\]|\[*"$TABCHAR"*\])
# Note that section-name brackets should contain a single token
# Fall through to add the line to contents of existing section
;;
\[*\])
[ "$CURR_SECTION" = "$1" ] && break
# Use a value that can not be a section name here:
CURR_SECTION="[]"
continue
;;
"") continue ;;
*) ;; # Fall through to add the line to contents of existing section
esac
if [ "$CURR_SECTION" = "$1" ]; then
if [ "${#SECTION_CONTENT}" = 0 ]; then
SECTION_CONTENT="$LINE"
else
SECTION_CONTENT="$SECTION_CONTENT
$LINE"
fi
fi
done
if [ "${#SECTION_CONTENT}" != 0 ]; then
echo "$SECTION_CONTENT"
fi
[ "$RES" = 0 ] || echo "ERROR: Section [$1] was not found in the '$UPSCONF' file" >&2
return $RES
}
upsconf_getSection() {
# Use the whole output of normalization parser
if [ x"${AVOID_REPARSE}" != xyes ] ; then
upslist_normalizeFile_once || return # Propagate errors upwards
fi
upsconf_getSection_content "$@" << EOF
${UPSCONF_DATA}
EOF
}
upsconf_getSection_MD5() {
calc_md5 "`upsconf_getSection "$@"`"
}
upsconf_getSection_SDP() {
# Use the section-driver-port subset
if [ x"${AVOID_REPARSE}" != xyes ] ; then
upslist_normalizeFile_once || return # Propagate errors upwards
fi
upsconf_getSection_content "$@" << EOF
${UPSCONF_DATA_SDP}
EOF
}
upsconf_getValue() {
# "$1" = name of ups.conf section, may be empty for global config
# "$2..$N" = name of config key; we will echo its value
### [ -n "$1" ] || return $?
[ -n "$2" ] || return $?
[ -n "$GETSECTION" ] || GETSECTION="upsconf_getSection"
CURR_SECTION="" # Gets set by a GETSECTION implementation
RES=0
# Note: Primary aim of this egrep is to pick either assignments or flags
# As a by-product it can be used to test if a particular value is set ;)
SECTION_CONTENT="`$GETSECTION "$1"`" || return
shift
KEYS="$*"
while [ "$#" -gt 0 ] ; do
RES_L=0
VALUE=""
LINE="`echo "$SECTION_CONTENT" | grep -E '(^'"$1"'=|^'"$1"'$)'`" \
&& VALUE="$(echo "$LINE" | sed -e "s,^$1=,," -e 's,^\"\(.*\)\"$,\1,' -e "s,^'\(.*\)'\$,\1,")" \
|| RES_L=$?
[ "$RES_L" = 0 ] || { RES="$RES_L" ; echo "ERROR: Section [$CURR_SECTION] or key '$1' in it was not found in the '$UPSCONF' file" >&2 ; }
echo "$VALUE"
shift
done
[ "$RES" = 0 ] || echo "ERROR: Section [$CURR_SECTION] or key(s) '$KEYS' in it was not found in the '$UPSCONF' file" >&2
return $RES
}
upsconf_getDriver() {
# "$1" = name of ups.conf section; return (echo) the driver name used there
# In the context this function is used, UPSCONF exists and section is there
GETSECTION="upsconf_getSection_SDP" upsconf_getValue "$1" "driver"
return $?
}
upsconf_getPort() {
# "$1" = name of ups.conf section; return (echo) the "port" name used there
# In the context this function is used, UPSCONF exists and section is there
GETSECTION="upsconf_getSection_SDP" upsconf_getValue "$1" "port"
return $?
}
upsconf_getDriverMedia() {
# "$1" = name of ups.conf section; return (echo) name and type of driver as
# needed for dependency evaluation (what services we must depend on for this
# unit), newline-separated (drvname<EOL>type). Empty type for unclassified
# results, assuming no known special dependencies (note that depending on
# particular system's physics, both serial and network media may need USB).
CURR_DRV="`upsconf_getDriver "$1"`" || return $?
case "$CURR_DRV" in
*netxml*|*snmp*|*ipmi*|*powerman*|*-mib*|*avahi*)
printf '%s\n%s\n' "$CURR_DRV" "network" ; return ;;
*apcupsd-ups*)
# Relay from a nearby apcupsd network server into NUT ecosystem:
CURR_PORT="`upsconf_getPort "$1"`" || CURR_PORT=""
case "$CURR_PORT" in
*localhost*|*127.0.0.1*|*::1*)
printf '%s\n%s\n' "$CURR_DRV" "network-localhost" ; return ;;
*)
printf '%s\n%s\n' "$CURR_DRV" "network" ; return ;;
esac
;;
*apc_modbus*)
CURR_PORT="`upsconf_getPort "$1"`" || CURR_PORT=""
CURR_PORTTYPE="`upsconf_getValue "$1" 'porttype'`" || CURR_PORTTYPE=""
case "$CURR_PORTTYPE" in
*usb*)
printf '%s\n%s\n' "$CURR_DRV" "usb" ; return ;;
*serial*)
printf '%s\n%s\n' "$CURR_DRV" "serial" ; return ;;
*) # default depends on driver build (against libmodbus
# version with or without support for usb)
# TOTHINK: Check for presence of config values like
# vendorid (USB) or baud (Serial)? They are optional
# with reasonable defaults anyway...
case "$CURR_PORT" in
*auto*)
printf '%s\n%s\n' "$CURR_DRV" "usb" ; return ;;
/*)
printf '%s\n%s\n' "$CURR_DRV" "serial" ; return ;;
*localhost*|*127.0.0.1*|*::1*)
printf '%s\n%s\n' "$CURR_DRV" "network-localhost" ; return ;;
*)
printf '%s\n%s\n' "$CURR_DRV" "network" ; return ;;
esac
# returns are above, but just in case - have a fallback:
printf '%s\n%s\n' "$CURR_DRV" "" ; return ;;
esac
;;
*usb*)
printf '%s\n%s\n' "$CURR_DRV" "usb" ; return ;;
nutdrv_qx) # May be direct serial or USB
CURR_PORT="`upsconf_getPort "$1"`" || CURR_PORT=""
case "$CURR_PORT" in
auto|/dev/*usb*|/dev/*hid*)
printf '%s\n%s\n' "$CURR_DRV" "usb" ; return ;;
/dev/*)
# See drivers/nutdrv_qx.c :: upsdrv_initups() for a list
if [ -n "`upsconf_getValue "$1" 'subdriver' 'vendorid' 'productid' 'vendor' 'product' 'serial' 'bus' 'busport' 'langid_fix'`" ] \
; then
printf '%s\n%s\n' "$CURR_DRV" "usb" ; return
else
printf '%s\n%s\n' "$CURR_DRV" "serial" ; return
fi
;;
*)
printf '%s\n%s\n' "$CURR_DRV" "" ; return ;;
esac
;;
*dummy*|*clone*) # May be networked (proxy to remote NUT)
CURR_PORT="`upsconf_getPort "$1"`" || CURR_PORT=""
case "$CURR_PORT" in
*@localhost|*@|*@127.0.0.1|*@::1)
printf '%s\n%s\n' "$CURR_DRV" "network-localhost" ; return ;;
*@*)
printf '%s\n%s\n' "$CURR_DRV" "network" ; return ;;
*)
printf '%s\n%s\n' "$CURR_DRV" "" ; return ;;
esac
;;
# FIXME: other modbus? sysfs like INA219? GPIO? Other local devices?
*) printf '%s\n%s\n' "$CURR_DRV" "" ; return ;;
esac
}
upsconf_getMedia() {
_DRVMED="`upsconf_getDriverMedia "$1"`" || return
echo "${_DRVMED}" | tail -n +2
return 0
}
upsconf_debug() {
_DRV="`upsconf_getDriver "$1"`"
_PRT="`upsconf_getPort "$1"`"
_MED="`upsconf_getMedia "$1"`"
_MD5="`upsconf_getSection_MD5 "$1"`"
NAME_MD5="`calc_md5 "$1"`"
echo "INST: ${NAME_MD5}~[$1]: DRV='${_DRV}' PORT='${_PRT}' MEDIA='${_MED}' SECTIONMD5='${_MD5}'"
}
calc_md5() {
# Tries several ways to produce an MD5 of the "$1" argument
_MD5="`echo "$1" | md5sum 2>/dev/null | awk '{print $1}'`" && [ -n "${_MD5}" ] || \
{ _MD5="`echo "$1" | openssl dgst -md5 2>/dev/null | awk '{print $NF}'`" && [ -n "${_MD5}" ]; } || \
return 1
echo "${_MD5}"
}
calc_md5_file() {
# Tries several ways to produce an MD5 of the file named by "$1" argument
[ -s "$1" ] || return 2
_MD5="`md5sum 2>/dev/null < "$1" | awk '{print $1}'`" && [ -n "${_MD5}" ] || \
{ _MD5="`openssl dgst -md5 2>/dev/null < "$1" | awk '{print $NF}'`" && [ -n "${_MD5}" ]; } || \
return 1
echo "${_MD5}"
}
smf_validFullUnitName() {
case "$1" in
*:*) echo "$1" ;;
*) echo "$SVCNAME_SMF:$1" ;;
esac
}
smf_validInstanceName() {
echo "MD5_`calc_md5 "$1"`"
}
smf_validInstanceSuffixName() {
case "$1" in
*:*) echo "$1" | sed 's,^.*:\([^:]*\)$,\1,' ;;
*) echo "$1" ;;
esac
}
smf_registerInstance() {
DEVICE="$1"
SVCINST="$1"
if /usr/bin/svcs "nut-driver:$SVCINST" >/dev/null 2>&1 ; then
smf_unregisterInstance "$SVCINST"
fi
/usr/sbin/svccfg -s nut-driver add "$DEVICE" || \
{ SVCINST="`smf_validInstanceName "$1"`" || return
if /usr/bin/svcs "nut-driver:$SVCINST" >/dev/null 2>&1 ; then
smf_unregisterInstance "$SVCINST"
fi
/usr/sbin/svccfg -s nut-driver add "$SVCINST" || return ; }
echo "Added instance: 'nut-driver:$SVCINST' for NUT configuration section '$DEVICE'" >&2
DEPSVC=""
DEPREQ=""
_MED="`upsconf_getMedia "$DEVICE"`"
case "${_MED}" in
usb)
DEPSVC="$DEPSVC_USB_SMF"
DEPREQ="$DEPREQ_USB_SMF" ;;
network-localhost)
DEPSVC="$DEPSVC_NET_LOCAL_SMF"
DEPREQ="$DEPREQ_NET_LOCAL_SMF" ;;
network)
DEPSVC="$DEPSVC_NET_FULL_SMF"
DEPREQ="$DEPREQ_NET_FULL_SMF" ;;
serial) ;;
'') ;;
*) echo "WARNING: Unexpected NUT media type ignored: '${_MED}'" >&2 ;;
esac
TARGET_FMRI="nut-driver:$SVCINST"
if [ -n "$DEPSVC" ]; then
[ -n "$DEPREQ" ] || DEPREQ="optional_all"
echo "Adding '$DEPREQ' dependency for '$SVCINST' on '$DEPSVC'..."
DEPPG="nut-driver-enumerator-generated"
RESTARTON="refresh"
/usr/sbin/svccfg -s "$TARGET_FMRI" addpg "$DEPPG" dependency && \
/usr/sbin/svccfg -s "$TARGET_FMRI" setprop "$DEPPG"/grouping = astring: "$DEPREQ" && \
/usr/sbin/svccfg -s "$TARGET_FMRI" setprop "$DEPPG"/restart_on = astring: "$RESTARTON" && \
/usr/sbin/svccfg -s "$TARGET_FMRI" setprop "$DEPPG"/type = astring: service && \
/usr/sbin/svccfg -s "$TARGET_FMRI" setprop "$DEPPG"/entities = fmri: "($DEPSVC)" && \
echo "OK" || echo "FAILED to define the dependency" >&2
fi
smf_setSavedMD5 "$SVCINST" "`upsconf_getSection_MD5 "$DEVICE"`"
# Save original device (config section) name to speed up some searches
smf_setSavedDeviceName "$SVCINST" "$DEVICE"
smf_setDocLink "$SVCINST" "$DEVICE"
/usr/sbin/svcadm refresh "${TARGET_FMRI}" || return
if [ "$AUTO_START" = yes ] ; then
/usr/sbin/svcadm clear "${TARGET_FMRI}" 2>/dev/null || true
/usr/sbin/svcadm enable "${TARGET_FMRI}" || return
echo "Started instance: 'nut-driver:$SVCINST' for NUT configuration section '$DEVICE'" >&2
fi
}
smf_unregisterInstance() {
echo "Removing instance: 'nut-driver:$1' ..." >&2
/usr/sbin/svcadm disable -ts 'nut-driver:'"$1" || false
/usr/sbin/svccfg -s nut-driver delete "$1"
}
smf_refreshSupervizor() {
:
}
smf_listInstances_raw() {
# Newer versions have pattern matching; older SMF might not have this luxury
/usr/bin/svcs -a -H -o fmri | grep -E '/nut-driver:'
}
smf_listInstances() {
# Chop twice, in case there is a leading "svc:/...."
smf_listInstances_raw | sed -e 's/^.*://' -e 's/^.*://' | sort -k1n -k1
}
smf_getSavedMD5() {
# Query service instance $1
PG="nut-driver-enumerator-generated-checksum"
PROP="SECTION_CHECKSUM"
if [ -n "$1" ]; then
TARGET_FMRI="nut-driver:$1"
else
# Global section
TARGET_FMRI="nut-driver"
PROP="SECTION_CHECKSUM_GLOBAL"
fi
# Note: lookups for GLOBAL cause each service instance to show up
/usr/bin/svcprop -p "$PG/$PROP" "$TARGET_FMRI" 2>/dev/null | head -1 | awk '{print $NF}'
}
smf_findSavedDeviceName() {
# Returns long service FMRI which has DEVICE=="$1"
# For empty "$1" returns a list of all recorded "FMRI<TAB>DEVICE"
if [ -z "$1" ]; then
/usr/bin/svcprop -p "nut-driver-enumerator-generated-devicename/DEVICE" \
'svc:/system/power/nut-driver:*' 2>/dev/null \
| sed 's|^\(svc:/[^:]*:[^/:]*\)/:properties/nut-driver-enumerator-generated-devicename/DEVICE astring \(.*\)$|\1\t\2|'
else
/usr/bin/svcprop -p "nut-driver-enumerator-generated-devicename/DEVICE" \
"svc:/system/power/nut-driver:$1" 2>/dev/null \
| sed 's|^\(svc:/[^:]*:[^/:]*\)/:prop.*$|\1|'
fi
}
smf_getSavedDeviceName() {
# Query service instance $1
PG="nut-driver-enumerator-generated-devicename"
PROP="DEVICE"
if [ -n "$1" ]; then
TARGET_FMRI="nut-driver:$1"
else
# Global section
echo ""
return 0
fi
# Note: lookups for GLOBAL cause each service instance to show up
/usr/bin/svcprop -p "$PG/$PROP" "$TARGET_FMRI" 2>/dev/null | head -1 | awk '{print $NF}'
}
smf_setSavedUniq() {
# Save data value $5 of type $4 into service FMRI $1
# under (scrapped and) newly created property group $2
# and property name $3
__TARGET_FMRI="$1"
__PG="$2"
__PROP="$3"
__TYPE="$4"
case "${__TYPE}" in
*:) ;;
*) __TYPE="${__TYPE}:" ;;
esac
__VAL="$5"
/usr/sbin/svccfg -s "${__TARGET_FMRI}" delprop "${__PG}" 2>/dev/null || true
/usr/sbin/svccfg -s "${__TARGET_FMRI}" addpg "${__PG}" application && \
/usr/sbin/svccfg -s "${__TARGET_FMRI}" setprop "${__PG}/${__PROP}" = "${__TYPE}" "${__VAL}"
[ $? = 0 ] && echo "OK" || { echo "FAILED to stash the service property ${__PG}/${__PROP}">&2 ; return 1 ; }
case "${__TARGET_FMRI}" in
svc:/*:*) ;; # A service instance by full FMRI, refresh
svc:/*/nut-driver|nut-driver) return 0 ;; # A base non-instance service item for nut-driver (known multi-instance only)
svc:/*) ;; # A base non-instance service item (not nut-driver)
*:*) ;; # A service instance by short FMRI, refresh
*) ;; # A base non-instance service item (not nut-driver)
esac
/usr/sbin/svcadm refresh "${__TARGET_FMRI}" || return
}
smf_setSavedMD5() {
# Save checksum value $2 into service instance $1
_PG="nut-driver-enumerator-generated-checksum"
_PROP="SECTION_CHECKSUM"
if [ -n "$1" ]; then
_TARGET_FMRI="nut-driver:$1"
else
# Global section
_TARGET_FMRI="nut-driver"
_PROP="SECTION_CHECKSUM_GLOBAL"
fi
smf_setSavedUniq "${_TARGET_FMRI}" "${_PG}" "${_PROP}" astring "$2"
}
smf_setSavedDeviceName() {
[ -n "$1" ] || return # No-op for global section
smf_setSavedUniq "nut-driver:$1" "nut-driver-enumerator-generated-devicename" "DEVICE" astring "$2"
}
smf_setDocLink() {
# Save documentation links for driver of device (config section) named $2
# into service instance $1
[ -n "$1" ] || return # No-op for global section
__TARGET_FMRI="nut-driver:$1"
__DRV="`upsconf_getDriver "$2"`"
### Sample:
#tm_common_name template
#tm_common_name/C ustring "physical network interface autoconfiguration"
#tm_doc_Network_Auto-Magic_OpenSolaris_Project_Page template
#tm_doc_Network_Auto-Magic_OpenSolaris_Project_Page/name astring "Network Auto-Magic OpenSolaris Project Page"
#tm_doc_Network_Auto-Magic_OpenSolaris_Project_Page/uri astring http://hub.opensolaris.org/bin/view/Project+nwam/
#tm_man_nwamd8 template
#tm_man_nwamd8/manpath astring /usr/share/man
#tm_man_nwamd8/section astring 8
#tm_man_nwamd8/title astring nwamd
__PG="tm_doc_${__DRV}_Page"
/usr/sbin/svccfg -s "${__TARGET_FMRI}" delprop "${__PG}" 2>/dev/null || true
/usr/sbin/svccfg -s "${__TARGET_FMRI}" addpg "${__PG}" template && \
/usr/sbin/svccfg -s "${__TARGET_FMRI}" setprop "${__PG}/name" = "astring:" "\"${__DRV} online\"" && \
/usr/sbin/svccfg -s "${__TARGET_FMRI}" setprop "${__PG}/uri" = "astring:" "${NUT_WEBSITE_BASE}/docs/man/${__DRV}.html"
[ $? = 0 ] && echo "OK" || { echo "FAILED to stash the service property group '${__PG}' for online docs">&2 ; return 1 ; }
__PG="tm_man_${__DRV}8"
/usr/sbin/svccfg -s "${__TARGET_FMRI}" delprop "${__PG}" 2>/dev/null || true
/usr/sbin/svccfg -s "${__TARGET_FMRI}" addpg "${__PG}" template && \
/usr/sbin/svccfg -s "${__TARGET_FMRI}" setprop "${__PG}/manpath" = "astring:" "/usr/local/ups/share/man" && \
/usr/sbin/svccfg -s "${__TARGET_FMRI}" setprop "${__PG}/section" = "astring:" "8" && \
/usr/sbin/svccfg -s "${__TARGET_FMRI}" setprop "${__PG}/title" = "astring:" "${__DRV}"
[ $? = 0 ] && echo "OK" || { echo "FAILED to stash the service property group '${__PG}' for local docs">&2 ; return 1 ; }
unset __DRV __PG __TARGET_FMRI
[ $? = 0 ] && echo "OK" || { echo "FAILED to stash the device doc links">&2 ; return 1 ; }
}
smf_restart_upsd() {
echo "Reloading or restarting NUT data server to make sure it knows new configuration..."
/usr/sbin/svcadm enable "nut-server" 2>/dev/null
/usr/sbin/svcadm clear "nut-server" 2>/dev/null
/usr/sbin/svcadm refresh "nut-server" || \
/usr/sbin/svcadm restart "nut-server"
}
smf_restart_drv() {
echo "Reloading or restarting NUT driver instance '$1' to make sure it knows new configuration..."
/usr/sbin/svcadm enable "nut-driver:$1" 2>/dev/null
/usr/sbin/svcadm clear "nut-driver:$1" 2>/dev/null
/usr/sbin/svcadm refresh "nut-driver:$1" || \
/usr/sbin/svcadm restart "nut-driver:$1"
}
systemd_validFullUnitName() {
case "$1" in
*@*.*) echo "$1" ;;
*@*) echo "$1.service" ;;
*) echo "$SVCNAME_SYSTEMD@$1.service" ;;
esac
}
systemd_validInstanceName() {
echo "MD5_`calc_md5 "$1"`"
}
systemd_validInstanceSuffixName() {
echo "$1" | sed -e 's,^.*@,,' -e 's,\.service$,,'
}
systemd_registerInstance() {
# Instance is registered by device section name; ultimate name in systemd may differ
DEVICE="$1"
SVCINST="$1"
/bin/systemctl enable 'nut-driver@'"$DEVICE".service || \
{ SVCINST="`systemd_validInstanceName "$1"`" && \
/bin/systemctl enable 'nut-driver@'"$SVCINST".service || return ; }
echo "Enabled instance: 'nut-driver@$SVCINST' for NUT configuration section '$DEVICE'" >&2
DEPSVC=""
DEPREQ=""
_MED="`upsconf_getMedia "$DEVICE"`"
case "${_MED}" in
usb)
DEPSVC="$DEPSVC_USB_SYSTEMD"
DEPREQ="$DEPREQ_USB_SYSTEMD" ;;
network-localhost)
DEPSVC="$DEPSVC_NET_LOCAL_SYSTEMD"
DEPREQ="$DEPREQ_NET_LOCAL_SYSTEMD" ;;
network)
DEPSVC="$DEPSVC_NET_FULL_SYSTEMD"
DEPREQ="$DEPREQ_NET_FULL_SYSTEMD" ;;
serial)
DEPSVC="$DEPSVC_SERIAL_SYSTEMD"
DEPREQ="$DEPREQ_SERIAL_SYSTEMD" ;;
'') ;;
# FIXME: modbus? sysfs like INA219? GPIO? Other local devices?
*) echo "WARNING: Unexpected NUT media type ignored: '${_MED}'" >&2 ;;
esac
if [ -n "$DEPSVC" ]; then
[ -n "$DEPREQ" ] || DEPREQ="#Wants"
echo "Adding '$DEPREQ'+After dependency for '$SVCINST' on '$DEPSVC'..."
mkdir -p "${SYSTEMD_CONFPATH}/nut-driver@$SVCINST.service.d" && \
cat > "${SYSTEMD_CONFPATH}/nut-driver@$SVCINST.service.d/nut-driver-enumerator-generated.conf" <<EOF
# Customization generated `date -u` by nut-driver-enumerator for NUT device '$DEVICE'
# DO NOT EDIT: This file would be removed or overwritten by that service
[Unit]
Description=Network UPS Tools - device driver for NUT device '$DEVICE'
${DEPREQ}=${DEPSVC}
After=${DEPSVC}
EOF
[ $? = 0 ] && echo "OK" || echo "FAILED to define the dependency" >&2
fi
systemd_setSavedMD5 "$SVCINST" "`upsconf_getSection_MD5 "$DEVICE"`"
systemd_setSavedDeviceName "$SVCINST" "$DEVICE"
systemd_setDocLink "$SVCINST" "$DEVICE"
if [ "$AUTO_START" = yes ] ; then
systemd_refreshSupervizor || echo "WARNING: Somehow managed to fail systemd_refreshSupervizor()" >&2
$TIMEOUT_CMD $TIMEOUT_ARGS /bin/systemctl start --no-block 'nut-driver@'"$SVCINST".service || return
echo "Started instance: 'nut-driver@$SVCINST' for NUT configuration section '$DEVICE'" >&2
fi
}
systemd_unregisterInstance() {
echo "Removing instance: 'nut-driver@$1' ..." >&2
$TIMEOUT_CMD $TIMEOUT_ARGS /bin/systemctl stop 'nut-driver@'"$1".service || \
$TIMEOUT_CMD $TIMEOUT_ARGS /bin/systemctl stop 'nut-driver@'"$1".service || \
$TIMEOUT_CMD $TIMEOUT_ARGS /bin/systemctl stop 'nut-driver@'"$1".service || false
/bin/systemctl disable 'nut-driver@'"$1".service
rm -rf "${SYSTEMD_CONFPATH}/nut-driver@$1.service.d"
/bin/systemctl reset-failed 'nut-driver@'"$1".service
}
systemd_refreshSupervizor() {
/bin/systemctl daemon-reload
}
systemd_listInstances_raw() {
/bin/systemctl show 'nut-driver@*' -p Id | grep -E '=nut-driver' | sed 's,^Id=,,'
}
systemd_listInstances() {
systemd_listInstances_raw | sed -e 's/^.*@//' -e 's/\.service$//' | sort -k1n -k1
}
systemd_getSavedMD5() {
# Query service instance $1 or global section
PROP="SECTION_CHECKSUM"
[ -n "$1" ] || PROP="SECTION_CHECKSUM_GLOBAL"
PROPFILE="${SYSTEMD_CONFPATH}/nut-driver@$1.service.d/nut-driver-enumerator-generated-checksum.conf"
[ -s "${PROPFILE}" ] \
&& grep "Environment='$PROP=" "${PROPFILE}" | sed -e "s,^Environment='$PROP=,," -e "s,'\$,," \
|| { echo "Did not find '${PROPFILE}' with a $PROP" ; return 1; }
}
systemd_findSavedDeviceName() {
# Returns long service instance name which has DEVICE=="$1"
# For empty "$1" returns a list of all recorded "SVC<TAB>DEVICE"
if [ -z "$1" ]; then
grep -H "Environment='DEVICE=" \
"${SYSTEMD_CONFPATH}"/nut-driver@*.service.d/nut-driver-enumerator-generated-devicename.conf \
| sed 's|^'"${SYSTEMD_CONFPATH}"'/\(nut-driver@[^/]*\.service\)\.d/.*DEVICE='"[\"']*\([^\"']*\)[\"']*"'$|\1\t\2|'
else
grep -E -H "Environment='DEVICE=($1|\"$1\")'" \
"${SYSTEMD_CONFPATH}"/nut-driver@*.service.d/nut-driver-enumerator-generated-devicename.conf \
| sed 's|^'"${SYSTEMD_CONFPATH}"'/\(nut-driver@[^/]*\.service\)\.d/.*$|\1|'
fi
}
systemd_getSavedDeviceName() {
# Query service instance "$1" (quiet NO-OP if empty, for mis-use
# in global sections context) to get the unquoted saved DEVICE
# section name corresponding to this service instance
[ -n "$1" ] || { echo ""; return 0; }
PROP="DEVICE"
PROPFILE="${SYSTEMD_CONFPATH}/nut-driver@$1.service.d/nut-driver-enumerator-generated-devicename.conf"
[ -s "${PROPFILE}" ] \
&& grep "Environment='$PROP=" "${PROPFILE}" | sed -e "s,^Environment='$PROP=,," -e "s,'\$,," -e 's,^"\(.*\)"$,\1,' \
|| { echo "Did not find '${PROPFILE}' with a $PROP" ; return 1; }
}
systemd_setSavedDeviceName() {
# Save device (config section) name $2 into service instance $1
[ -n "$1" ] || return # No-op for global section
PROPFILE="${SYSTEMD_CONFPATH}/nut-driver@$1.service.d/nut-driver-enumerator-generated-devicename.conf"
mkdir -p "${SYSTEMD_CONFPATH}/nut-driver@$1.service.d" && \
cat > "${PROPFILE}" << EOF
[Service]
Environment='DEVICE="$2"'
EOF
[ $? = 0 ] && echo "OK" || { echo "FAILED to stash the device name">&2 ; return 1 ; }
}
systemd_setDocLink() {
# Save documentation links for driver of device (config section) named $2
# into service instance $1
[ -n "$1" ] || return # No-op for global section
PROPFILE="${SYSTEMD_CONFPATH}/nut-driver@$1.service.d/nut-driver-enumerator-generated-doclink.conf"
mkdir -p "${SYSTEMD_CONFPATH}/nut-driver@$1.service.d" && \
__DRV="`upsconf_getDriver "$2"`"
cat > "${PROPFILE}" << EOF
[Unit]
Documentation=man:${__DRV}(8)
Documentation=${NUT_WEBSITE_BASE}/docs/man/${__DRV}.html
EOF
unset __DRV
[ $? = 0 ] && echo "OK" || { echo "FAILED to stash the device name">&2 ; return 1 ; }
}
systemd_setSavedMD5() {
# Save checksum value $2 into service instance $1
PROP="SECTION_CHECKSUM"
[ -n "$1" ] || PROP="SECTION_CHECKSUM_GLOBAL"
PROPFILE="${SYSTEMD_CONFPATH}/nut-driver@$1.service.d/nut-driver-enumerator-generated-checksum.conf"
mkdir -p "${SYSTEMD_CONFPATH}/nut-driver@$1.service.d" && \
cat > "${PROPFILE}" << EOF
[Service]
Environment='$PROP=$2'
EOF
[ $? = 0 ] && echo "OK" || { echo "FAILED to stash the checksum">&2 ; return 1 ; }
}
systemd_restart_upsd() {
# Do not restart/reload if not already running
case "`/bin/systemctl is-active "nut-server"`" in
active|unknown) ;; # unknown meant "starting" in our testing...
failed) echo "Note: nut-server unit was 'failed' - not disabled by user, so (re)starting it (probably had no config initially)" >&2 ;;
*) return 0 ;;
esac
echo "Reloading or restarting NUT data server to make sure it knows new configuration..."
# Note: reload is a better way to go about this, so the
# data service is not interrupted by re-initialization
# of the daemon. But systemd/systemctl sometimes stalls...
$TIMEOUT_CMD $TIMEOUT_ARGS /bin/systemctl reload-or-restart "nut-server" || \
$TIMEOUT_CMD $TIMEOUT_ARGS /bin/systemctl restart "nut-server"
}
systemd_restart_drv() {
# Do not restart/reload if not already running
case "`/bin/systemctl is-active "nut-driver@$1"`" in
active|unknown) ;;
*) return 0 ;;
esac
echo "Reloading or restarting NUT driver instance '$1' to make sure it knows new configuration..."
# Full restart, e.g. in case we changed the user= in configs
# however let "reload" try, in case we changed something that
# can be updated "on the fly", like the "debug_min" setting.
$TIMEOUT_CMD $TIMEOUT_ARGS /bin/systemctl reload-or-restart "nut-driver@$1" || \
$TIMEOUT_CMD $TIMEOUT_ARGS /bin/systemctl restart "nut-driver@$1"
}
upslist_normalizeFile_filter() {
# See upslist_normalizeFile() detailed comments below; this routine
# is a pipe worker to prepare the text into a simpler expected form.
# Pick the lines which contain a bracket or assignment character,
# or a single token (certain keywords come as just NUT "flags"),
# trim leading and trailing whitespace, comment-only lines, and in
# assignment lines trim the spaces around equality character and
# quoting characters around assignment of values without whitespaces.
# Any whitespace characters around a section name (single token that
# starts the line and is enclosed in brackets) and a trailing comment
# are dropped. Note that brackets with spaces inside, and brackets
# that do not start the non-whitespace payload of the line, are not
# sections.
grep -E -v '(^$|^#)' | \
sed -e 's,^['"$TABCHAR"'\ ]*,,' \
-e 's,^\#.*$,,' \
-e 's,['"$TABCHAR"'\ ]*$,,' \
-e 's,^\([^=\ '"$TABCHAR"']*\)['"$TABCHAR"'\ ]*=['"$TABCHAR"'\ ]*,\1=,g' \
-e 's,=\"\([^\ '"$TABCHAR"']*\)\"$,=\1,' \
-e 's,^\(\[[^]'"$TABCHAR"'\ ]*\]\)['"$TABCHAR"'\ ]*\(#.*\)*$,\1,' \
| grep -E -v '^$' \
| grep -E '([\[\=]|^[^ '"$TABCHAR"']*$|^[^ '"$TABCHAR"']*[ '"$TABCHAR"']*#.*$)'
}
upslist_normalizeFile() {
# Read the ups.conf file and find all defined sections (names of
# configuration blocks for drivers that connect to a certain device
# using specified protocol and media); normalize section contents
# as detailed below, to simplify subsequent parsing and comparison.
# File contents
UPSCONF_DATA=""
UPSCONF_DATA_SDP=""
if [ -n "$UPSCONF" ] && [ -f "$UPSCONF" ] && [ -r "$UPSCONF" ]; then
[ ! -s "$UPSCONF" ] \
&& echo "WARNING: The '$UPSCONF' file exists but is empty" >&2 \
&& return 0
# Ok to continue - we may end up removing all instances
else
echo "FATAL: The '$UPSCONF' file does not exist or is not readable" >&2
return 2
fi
# Store a normalized version of NUT configuration file contents.
# Also use a SDP subset with just section, driver and port info
# for faster parsing when determining driver-required media etc.
UPSCONF_DATA="$(upslist_normalizeFile_filter < "$UPSCONF")" \
&& [ "${#UPSCONF_DATA}" != 0 ] \
&& UPSCONF_DATA_SDP="`grep -E '^(\[.*\]|driver=|port=)' << EOF
$UPSCONF_DATA
EOF`" \
|| { echo "Error reading the '$UPSCONF' file or it does not declare any device configurations: nothing left after normalization" >&2
UPSCONF_DATA=""
UPSCONF_DATA_SDP=""
}
}
upslist_normalizeFile_once() {
# Wrapper that ensures that the parsing is only done once
# (will re-parse if there were no devices listed on the
# first time, though)
[ "${#UPSCONF_DATA}" = 0 ] && [ "${#UPSCONF_DATA_SDP}" = 0 ] || return 0
upslist_normalizeFile
}
upslist_readFile() {
# Use the routine above (unconditionally) to get or update the
# listing of device sections known at this moment.
# List of devices from the config file
UPSLIST_FILE=""
if [ "$DO_NORMALIZE_ONCE" = yes ]; then
upslist_normalizeFile_once || return # Propagate errors upwards
else
upslist_normalizeFile || return # Propagate errors upwards
fi
if [ "${#UPSCONF_DATA}" != 0 ] ; then
# Note that section-name brackets should contain a single token
UPSLIST_FILE="$(echo "$UPSCONF_DATA_SDP" | grep -E '^\[[^'"$TABCHAR"'\ ]*\]$' | sed 's,^\[\(.*\)\]$,\1,' | sort -k1n -k1)" \
|| UPSLIST_FILE=""
if [ "${#UPSLIST_FILE}" = 0 ] ; then
echo "Error reading the '$UPSCONF' file or it does not declare any device configurations: no section declarations in parsed normalized contents" >&2
fi
fi
# Ok to continue with empty results - we may end up removing all instances
}
upslist_readFile_once() {
# Wrapper that ensures that the parsing is only done once
# (will re-parse if there were no devices listed on the
# first time, though)
[ "${#UPSLIST_FILE}" = 0 ] || return 0
DO_NORMALIZE_ONCE=yes upslist_readFile
}
upslist_readSvcs() {
UPSLIST_SVCS="`$hook_listInstances`" || UPSLIST_SVCS=""
if [ "${#UPSLIST_SVCS}" = 0 ] && [ "$1" != "-" ] ; then
EXPLAIN=""
[ -z "$1" ] || EXPLAIN=" - $1"
echo "Error reading the list of ${SERVICE_FRAMEWORK-} service instances for UPS drivers, or none are defined${EXPLAIN}" >&2
# Ok to continue - we may end up defining new instances
fi
}
upslist_debug() {
for UPSF in "" $UPSLIST_FILE ; do
upsconf_debug "$UPSF"
done
}
upslist_addSvcs() {
# Note: This routine registers service instances for device config sections
# that are not wrapped currently. Support for redefined previously existing
# sections - is attained by removing the old service instance elsewhere and
# recreating it here, since any data could change including the dependency
# list, etc.
for UPSF in $UPSLIST_FILE ; do
if ! common_isRegistered "$UPSF" ; then
echo "Adding new ${SERVICE_FRAMEWORK} service instance for power device [${UPSF}]..." >&2
$hook_registerInstance "$UPSF"
fi
done
}
upslist_delSvcs() {
for UPSS in $UPSLIST_SVCS ; do
if ! common_isFiled "$UPSS" ; then
echo "Dropping old ${SERVICE_FRAMEWORK} service instance for power device [${UPSS}] which is no longer in config file..." >&2
$hook_unregisterInstance "$UPSS"
fi
done
}
upslist_restartSvcs() {
for UPSS in $UPSLIST_SVCS ; do
if common_isFiled "$UPSS" ; then
$hook_restart_drv "$UPSS"
fi
done
}
# FIXME : process via kill -l?
# Different shells use a SIG prefix or not to signal names
# so standard numbers are in fact more portable :\
TERMINATION_SIGNALS="2 3 15"
RECONFIGURATION_SIGNALS="1"
TERMINATE_ASAP=false
trap_handle_interruption_exit() {
# Handle SIGINT, SIGQUIT, SIGTERM with a message
echo "`date -u` : Received an interruption signal, terminating the script now" >&2
exit 0
}
trap_handle_interruption() {
# Handle SIGINT, SIGQUIT, SIGTERM gracefully - tell the main
# iteration to complete and just then abort
echo "`date -u` : Received an interruption signal, will terminate the script after ending the main routine. Repeat the signal if urgent!" >&2
TERMINATE_ASAP=true
trap 'trap_handle_interruption_exit' $TERMINATION_SIGNALS
}
nut_driver_enumerator_main() {
################# MAIN PROGRAM by default
TERMINATE_ASAP=false
trap 'trap_handle_interruption' $TERMINATION_SIGNALS
# Note: do not use the read..._once() here, to ensure that the
# looped daemon sees the whole picture, which can be new every time
upslist_readFile || return $?
#upslist_debug
upslist_readSvcs "before manipulations"
# Test if global config has changed since last run
# Note that we have upslist_normalizeFile called from upslist_readFile
# just above, so even if it came empty (e.g. new NUT installation, no
# device sections yet) we do not want to spend time and log storage to
# parse again and complain again.
RESTART_ALL=no
AVOID_REPARSE=yes upssvcconf_checksum_unchanged "" || { echo "`date -u` : Detected changes in global section of '$UPSCONF', will restart all drivers"; RESTART_ALL=yes; }
# Quickly exit if there's nothing to do (both lists empty or equal); note
# the lists are pre-sorted. Otherwise a non-zero exit will be done below.
# Note: We implement testing in detail whether section definitions were
# changed since last run, as a first step before checking that name
# lists are still equivalent, because we need to always have the result
# of the "has it changed?" check as a hit-list of something to remove,
# while the check for no new device section definitions is just boolean.
# We can only exit quickly if both there are no changed sections and no
# new or removed sections since last run.
{ [ -z "$UPSLIST_FILE" -a -z "$UPSLIST_SVCS" ] || { \
NEW_CHECKSUM="`upslist_checksums_unchanged "$UPSLIST_FILE" "$UPSLIST_SVCS"`" \
&& [ "${#NEW_CHECKSUM}" = 0 ] \
&& upslist_equals "$UPSLIST_FILE" "$UPSLIST_SVCS" ; \
} ; } \
&& if [ -z "$DAEMON_SLEEP" -o "${VERBOSE_LOOP}" = yes ] ; then \
echo "`date -u` : OK: No changes to reconcile between ${SERVICE_FRAMEWORK} service instances and device configurations in '$UPSCONF'" ; \
fi \
&& [ "$RESTART_ALL" = no ] && return 0
# Check list of devices with new section contents (per checksum) as
# compared to older runs (stashed in service instance configurations).
if [ "${#NEW_CHECKSUM}" = 0 ]; then
if [ "${VERBOSE_LOOP}" = yes ] ; then
echo "`date -u` : No changes to reconcile between *contents* of ${SERVICE_FRAMEWORK} service instances and device configurations in '$UPSCONF', but the *list* of instances vs. devices seems to have changed"
fi
else
if [ "${VERBOSE_LOOP}" = yes ] ; then
echo "`date -u` : Got some changes to reconcile between ${SERVICE_FRAMEWORK} service instances and device configurations in '$UPSCONF', content checksums changed for: `echo ${NEW_CHECKSUM} | tr '\n' ' '`"
fi
for UPSS in $NEW_CHECKSUM ; do
# NOTE: Pedantically, UPSS is a service instance name,
# and may be the MD5-normalized version in certain cases.
# For some operations below we need the original ups.conf
# section name for the device - the CURR_DEV value.
CURR_DEV="`USE_SAVEDINST=true get_device_for_service "${UPSS}"`" && [ "${#CURR_DEV}" -gt 0 ] || CURR_DEV="${UPSS}"
CURR_DRV="`upsconf_getDriver "${CURR_DEV}"`" || CURR_DRV=""
DO_UNREGISTER=yes
if [ -n "$CURR_DRV" ] ; then
# If reload is handled and does not complain,
# we are OK to proceed without re-defining
# and restarting the driver service instance.
if [ "${VERBOSE_LOOP}" = yes ] ; then
echo "`date -u` : Reloading ${SERVICE_FRAMEWORK} service instance '${UPSS}' whose section '${CURR_DEV}' in config file has changed: calling driver program '${CURR_DRV}' for the low-level work..." >&2
fi
"/usr/local/ups/bin/$CURR_DRV" -a "${CURR_DEV}" -c reload-or-error >/dev/null 2>/dev/null \
|| { if [ "${VERBOSE_LOOP}" = yes ] ; then sleep 1; "/usr/local/ups/bin/$CURR_DRV" -a "${CURR_DEV}" -c reload-or-error >&2 ; fi; } \
&& DO_UNREGISTER=no
fi
if [ "$DO_UNREGISTER" = yes ] ; then
echo "Dropping old ${SERVICE_FRAMEWORK} service instance '${UPSS}' whose section '${CURR_DEV}' in config file has changed..." >&2
$hook_unregisterInstance "$UPSS"
# Re-registration to reconcile below should set the "saved" values
else
echo "Keeping ${SERVICE_FRAMEWORK} service instance '${UPSS}' whose section '${CURR_DEV}' in config file has changed: live reload sufficed. Saving updated info into service properties." >&2
$hook_setSavedMD5 "$UPSS" "`upsconf_getSection_MD5 "${CURR_DEV}"`"
# TOTHINK: This is already there, else we redefine units for bigger discrepancies?
# $hook_setSavedDeviceName "$UPSS" "${CURR_DEV}"
fi
done
upslist_readSvcs "after updating for new config section checksums"
fi
if [ "${#UPSLIST_SVCS}" != 0 ]; then
# Drop services that are not in config file (any more?)
upslist_delSvcs
if [ "$RESTART_ALL" = yes ] && [ "$AUTO_START" = yes ] ; then
# Here restart only existing services; new ones will (try to)
# start soon after creation and upsd is handled below
upslist_restartSvcs
fi
fi
if [ "$RESTART_ALL" = yes ] ; then
# Save new checksum of global config
$hook_setSavedMD5 "" "`upsconf_getSection_MD5 ""`"
fi
if [ "${#UPSLIST_FILE}" != 0 ]; then
# Add services for sections that are in config file but not yet wrapped
upslist_addSvcs
$hook_refreshSupervizor
upslist_readSvcs "after checking for new config sections to define service instances"
fi
upslist_readSvcs
if [ "${#UPSLIST_SVCS}" != 0 ] ; then
echo "=== The currently defined service instances are:"
echo "$UPSLIST_SVCS"
fi
if [ "${#UPSLIST_FILE}" != 0 ] ; then
echo "=== The currently defined configurations in '$UPSCONF' are:"
echo "$UPSLIST_FILE"
fi
# We had some changes to the config file; upsd must be made aware
if [ "$AUTO_START" = yes ] ; then
$hook_restart_upsd
fi
# Return 42 if there was a change applied succesfully
# (but e.g. some services should restart - upsd, maybe upsmon)
UPSLIST_EQ_RES=0
upslist_equals "$UPSLIST_FILE" "$UPSLIST_SVCS" || UPSLIST_EQ_RES=$?
# File processing and service startups take a while;
# make sure upsconf did not change while we worked...
# NOTE: Check this at the last moment to minimize
# the chance of still not noticing the change made
# at just the wrong moment.
UPSCONF_CHECKSUM_END="`calc_md5_file "$UPSCONF"`" || true
if [ "$UPSCONF_CHECKSUM_END" != "$UPSCONF_CHECKSUM_START" ] ; then
# NOTE: even if daemonized, the sleep between iterations
# can be configured into an uncomfortably long lag, so
# we should re-sync the system config in any case.
echo "`date -u` : '$UPSCONF' changed while $0 $* was processing its older contents; re-running the script to pick up the late-coming changes"
# Make sure the cycle does not repeat itself due to diffs
# from an ages-old state of the file from when we started.
UPSCONF_CHECKSUM_START="$UPSCONF_CHECKSUM_END"
( nut_driver_enumerator_main ) ; return $?
# The "main" routine at the end of recursions will
# do REPORT_RESTART_42 logic or the error exit-code
fi
if [ "$UPSLIST_EQ_RES" = 0 ] ; then
echo "`date -u` : OK: No more changes to reconcile between ${SERVICE_FRAMEWORK} service instances and device configurations in '$UPSCONF'"
[ "${REPORT_RESTART_42-}" = no ] && return 0 || return 42
fi
return 13
}
nut_driver_enumerator_full_reconfigure() {
# Similar to the main routine for reconciling data,
# but this one removes all service instances and
# defines current mappings from scratch after that
upslist_readFile_once || return $?
upslist_readSvcs "before manipulations"
if [ "${#UPSLIST_SVCS}" != 0 ]; then
for UPSS in $UPSLIST_SVCS ; do
echo "Dropping old ${SERVICE_FRAMEWORK} service instance for power device [${UPSS}] to reconfigure the service unit..." >&2
$hook_unregisterInstance "$UPSS"
done
upslist_readSvcs "after dropping"
fi
if [ "${#UPSLIST_FILE}" != 0 ]; then
upslist_addSvcs
upslist_readSvcs "after checking for new config sections to define service instances"
fi
# Save new checksum of global config
$hook_setSavedMD5 "" "`upsconf_getSection_MD5 ""`"
# Service units were manipulated, including saving of checksums;
# refresh the service management daemon if needed
$hook_refreshSupervizor
if [ "${#UPSLIST_SVCS}" != 0 ] ; then
echo "=== The currently defined service instances are:"
echo "$UPSLIST_SVCS"
fi
if [ "${#UPSLIST_FILE}" != 0 ] ; then
echo "=== The currently defined configurations in '$UPSCONF' are:"
echo "$UPSLIST_FILE"
fi
# We had some changes to the config file; upsd must be made aware
if [ "$AUTO_START" = yes ] ; then
$hook_restart_upsd
fi
# Return 42 if there was a change applied succesfully
# (but e.g. some services should restart - upsd, maybe upsmon)
UPSLIST_EQ_RES=0
upslist_equals "$UPSLIST_FILE" "$UPSLIST_SVCS" || UPSLIST_EQ_RES=$?
# File processing and service startups take a while;
# make sure upsconf did not change while we worked...
# NOTE: Check this at the last moment to minimize
# the chance of still not noticing the change made
# at just the wrong moment.
UPSCONF_CHECKSUM_END="`calc_md5_file "$UPSCONF"`" || true
if [ "$UPSCONF_CHECKSUM_END" != "$UPSCONF_CHECKSUM_START" ] ; then
echo "`date -u` : '$UPSCONF' changed while $0 $* was processing its older contents; re-running the script to pick up and reconcile the late-coming changes"
nut_driver_enumerator_main ; return $?
# The "main" routine will do REPORT_RESTART_42 logic too
fi
if [ "$UPSLIST_EQ_RES" = 0 ] ; then
echo "`date -u` : OK: No more changes to reconcile between ${SERVICE_FRAMEWORK} service instances and device configurations in '$UPSCONF'"
[ "${REPORT_RESTART_42-}" = no ] && return 0 || return 42
fi
return 13
}
list_services_for_devices() {
FINAL_RES=0
upslist_readFile_once && [ "${#UPSLIST_FILE}" != 0 ] \
|| { echo "No devices detected in '$UPSCONF'" >&2 ; return 1 ; }
upslist_readSvcs "by user request" && [ "${#UPSLIST_SVCS}" != 0 ] \
|| { echo "No service instances detected" >&2 ; return 1; }
UPSLIST_SVCS_RAW="`$hook_listInstances_raw`" && [ "${#UPSLIST_SVCS_RAW}" != 0 ] \
|| { echo "No service units detected" >&2 ; return 1; }
for DEV in $UPSLIST_FILE ; do
vINST="`$hook_validInstanceName "$DEV"`"
vUNITD="`$hook_validFullUnitName "$DEV"`"
vUNITI="`$hook_validFullUnitName "$vINST"`"
# First pass over simple verbatim names
for INST in $UPSLIST_SVCS ; do
if [ "$INST" = "$DEV" ] ; then
for UNIT in $UPSLIST_SVCS_RAW ; do
if [ "$UNIT" = "$vUNITD" ] ; then
printf '%s\t%s\n' "$UNIT" "$DEV"
continue 3
fi
done
fi
done
for INST in $UPSLIST_SVCS ; do
if [ "$INST" = "$vINST" ] ; then
for UNIT in $UPSLIST_SVCS_RAW ; do
if [ "$UNIT" = "$vUNITI" ] ; then
printf '%s\t%s\n' "$UNIT" "$DEV"
continue 3
fi
done
fi
done
echo "WARNING: no service instances detected that match device '$DEV'" >&2
FINAL_RES=1
done
return $FINAL_RES
}
SVCS_DEVS_LIST=""
list_services_for_devices_once() {
# On first call, caches the system reponse
# On next calls returns what it got earlier
# Does not return any text, just the exit code
# (0 = data avail, even if empty, in SVCS_DEVS_LIST)
[ "${#SVCS_DEVS_LIST}" != 0 ] && return
# Pre-cache config file data, if nobody read it yet,
# and keep in main script context for reuse (no subshell)
upslist_readFile_once && \
SVCS_DEVS_LIST="`list_services_for_devices "$@"`" || return $?
}
get_device_for_service() {
[ -z "$1" ] && echo "Service (instance) name argument required" >&2 && return 1
# Instance name can be a hash or "native" NUT section name
SVC="`$hook_validInstanceSuffixName "$1"`" && [ -n "$SVC" ] \
|| { echo "Error getting SVC name from the inputs" >&2 ; return 1; }
# Reading the config is too expensive to do for every
# driver management attempt when there are many devices
if [ "${USE_SAVEDINST-}" != false ]; then
# Try to use last-stashed values from service properties first
# (NOTE: saved value is assumed to be valid if present)
SAVEDINST="`$hook_getSavedDeviceName "$SVC"`" || SAVEDINST=""
[ "${#SAVEDINST}" = 0 ] || { echo "$SAVEDINST" ; return 0 ; }
fi
case "$SVC" in
MD5_*) ;; # fall through to the bulk of code
*) upslist_readFile_once || return $?
echo "$UPSLIST_FILE" | grep -E "^$SVC\$"
return $?
;;
esac
# Inspect SVC=MD5_* usecase
FINAL_RES=0
list_services_for_devices_once && [ "${#SVCS_DEVS_LIST}" != 0 ] || FINAL_RES=$?
if [ "$FINAL_RES" = 0 ]; then
echo "$SVCS_DEVS_LIST" | grep "$SVC" | ( \
while read _SVC _DEV ; do
_SVC="`$hook_validInstanceSuffixName "${_SVC}"`" || exit
[ "${_SVC}" = "${SVC}" ] && echo "${_DEV}" && exit 0
done ; exit 1 ) && return 0
fi
echo "No service instance '$1' was detected that matches a NUT device" >&2
return 1
}
get_service_for_device() {
DEV="$1"
[ -z "$DEV" ] && echo "Device name argument required" >&2 && return 1
# Cheap check in service instance metadata, if saved
# (NOTE: saved value is assumed to be valid if present)
if [ "${USE_SAVEDSVC-}" != false ]; then
SAVEDSVC="`$hook_findSavedDeviceName "$DEV"`" || SAVEDSVC=""
[ "${#SAVEDSVC}" = 0 ] || { echo "$SAVEDSVC" ; return 0 ; }
fi
# Trawl all the data we have...
# TODO: Reorder to avoid extra parsing if we have an early hit?
upslist_readSvcs "by user request" && [ "${#UPSLIST_SVCS}" != 0 ] \
|| { echo "No service instances detected" >&2 ; return 1; }
UPSLIST_SVCS_RAW="`$hook_listInstances_raw`" && [ "${#UPSLIST_SVCS_RAW}" != 0 ] \
|| { echo "No service units detected" >&2 ; return 1; }
vINST="`$hook_validInstanceName "$DEV"`"
vUNITD="`$hook_validFullUnitName "$DEV"`"
vUNITI="`$hook_validFullUnitName "$vINST"`"
# First pass over simple verbatim names
for INST in $UPSLIST_SVCS ; do
if [ "$INST" = "$DEV" ] ; then
for UNIT in $UPSLIST_SVCS_RAW ; do
if [ "$UNIT" = "$vUNITD" ] ; then
echo "$UNIT"
return 0
fi
done
fi
done
# Second pass over other options
for INST in $UPSLIST_SVCS ; do
if [ "$INST" = "$vINST" ] ; then
for UNIT in $UPSLIST_SVCS_RAW ; do
if [ "$UNIT" = "$vUNITI" ] ; then
echo "$UNIT"
return 0
fi
done
fi
done
echo "No service instances detected that match device '$DEV'" >&2
return 1
}
update_upslist_savednames_find_missing() {
# Runs once in production modes that inspect and reconcile
# configs, to handle upgraded NUT deployments
SVCINSTS_NO_DEVICE="`upslist_savednames_find_missing`" || \
case "$?" in
1) return 0 ;; # No services defined yet
2) ;; # All service units do not have DEVICE values
esac
# Something found... or not? Or all is populated?
[ "${#SVCINSTS_NO_DEVICE}" != 0 ] || return 0
# Make a list of what devices are known in config matched
# to service instances defined in the system, if any
# Note to not check the service instance properties which
# we are validating and currently to not quite trust.
USE_SAVEDINST=false list_services_for_devices_once \
&& [ "${#SVCS_DEVS_LIST}" != 0 ] || return 0
# Go over services with no device value saved into properties,
# and write the values learned from mapping above
_MISSING_RES=0
for SVCINST in $SVCINSTS_NO_DEVICE ; do
_DEV="`printf '%s\n' "$SVCS_DEVS_LIST" | awk '( \$1 == "'"${SVCINST}"'" ) {print \$NF}'`"
echo "Service instance '$SVCINST' did not have a device recorded into properties, setting to '${_DEV}'"
[ -n "${_DEV}" ] || { echo "The device name value for '$SVCINST' is empty, skipping" >&2 ; _MISSING_RES=1 ; continue ; }
$hook_setSavedDeviceName "`$hook_validInstanceSuffixName "$SVCINST"`" "${_DEV}" || _MISSING_RES=$?
done
return ${_MISSING_RES}
}
RECONFIGURE_ASAP=false
trap_handle_hup_main() {
echo "`date -u` : Received a HUP during processing, scheduling reconfiguration to repeat ASAP (after the current iteration is done)" >&2
# Note: in the worst case the reconfig would run twice;
# we do not update UPSCONF_CHECKSUM_START in this case
# to avoid corrupting decisions of the currently running
# processing.
RECONFIGURE_ASAP=true
}
trap_handle_hup_sleep() {
echo "`date -u` : Received a HUP in my sleep, reprocessing configs right now!" >&2
# Avoid re-parsing main twice, though don't recalculate
# checksums needlessly on every loop cycle, either...
UPSCONF_CHECKSUM_START="`calc_md5_file "$UPSCONF"`" || true
RECONFIGURE_ASAP=true
if [ -n "$1" ] ; then
# Kill the sleeper PID
kill "$1"
fi
}
daemonize() {
# Note: do not further sub-shell this routine, so systemd
# is not confused whom to signal.
echo "`date -u` : Daemonizing $0 with config re-evaluation frequency $DAEMON_SLEEP" >&2
# Support (SIG)HUP == signal code 1 to quickly reconfigure,
# e.g. to request it while the sleep is happening or while
# "main" is processing an earlier change of the file.
RECONFIGURE_ASAP=false
trap 'trap_handle_hup_main' $RECONFIGURATION_SIGNALS
update_upslist_savednames_find_missing
# Note: this loop would die on errors with config file or
# inability to ensure that it matches the list of services.
# If caller did not `export REPORT_RESTART_42=no` then the
# loop would exit with code 42, and probably trigger restart
# of the service which wraps this daemon do topple others that
# depend on it.
# Note: do not quickly skip the "main" based on full-file
# checksum refresh, to ensure that whatever is configured
# gets applied (e.g. if user disabled some services or they
# died, or some config was not applied due to coding error).
while nut_driver_enumerator_main ; do
trap 'trap_handle_interruption_exit' $TERMINATION_SIGNALS
if $TERMINATE_ASAP ; then
echo "`date -u` : Trapped a SIGTERM/SIGINT/SIGQUIT during last run of nut_driver_enumerator_main, terminating gracefully now" >&2
exit 0
fi
if $RECONFIGURE_ASAP ; then
echo "`date -u` : Trapped a SIGHUP during last run of nut_driver_enumerator_main, repeating reconfiguration quickly" >&2
else
sleep $DAEMON_SLEEP &
trap "trap_handle_hup_sleep $!" $RECONFIGURATION_SIGNALS
wait $!
fi
RECONFIGURE_ASAP=false
trap 'trap_handle_hup_main' $RECONFIGURATION_SIGNALS
done
exit $?
}
# Save the checksum of ups.conf as early as possible,
# to test in the end that it is still the same file.
UPSCONF_CHECKSUM_START="`calc_md5_file "$UPSCONF"`" || true
# By default, update wrapping of devices into services
if [ $# = 0 ]; then
update_upslist_savednames_find_missing
nut_driver_enumerator_main ; exit $?
fi
if [ $# = 1 ] ; then
[ -n "$DAEMON_SLEEP" ] || DAEMON_SLEEP=60
# Note: Not all shells have 'case ... ;&' support
case "$1" in
--daemon=*) DAEMON_SLEEP="`echo "$1" | sed 's,^--daemon=,,'`" ;;
--daemon-after=*) DAEMON_SLEEP="`echo "$1" | sed 's,^--daemon-after=,,'`" ;;
esac
case "$1" in
--daemon-after|--daemon-after=*)
REPORT_RESTART_42=no nut_driver_enumerator_main || exit $?
daemonize &
exit $?
;;
--daemon|--daemon=*)
daemonize &
exit $?
;;
esac
fi
unset DAEMON_SLEEP
usage() {
cat << EOF
$0 (no args)
Update wrapping of devices into services
$0 --daemon(=freq)
Update wrapping of devices into services in an infinite loop
Default freq is 60 sec
$0 --daemon-after(=freq)
Update wrapping of devices into services in an infinite loop;
first do one run of the loop though, then daemonize (this way
service unit is deemed started only when NUT config and driver
instances are in sync). Default freq is 60 sec.
$0 --reconfigure
Stop and un-register all service instances and recreate them
(e.g. if new dependency template was defined in a new
version of this script and/or NUT package)
$0 --get-service-framework
Print the detected service
management framework in this OS
$0 --list-devices
Print list of devices in NUT config
$0 --list-services
Print list of service instances which wrap registered
NUT devices (full name of service unit)
$0 --list-instances
Print list of service instances which wrap registered
NUT devices (just instance suffix)
$0 --get-service-for-device DEV
Print the full name of service unit which wraps a NUT
device named "DEV"
$0 --get-device-for-service SVC
Print the NUT device name for full or instance-suffix name of
a service unit which wraps it
$0 --list-services-for-devices
Print a TAB-separated list of service units and corresponding
NUT device names which each such unit wraps
$0 --show-configs|--show-all-configs
Show the complete normalized list of device configuration blocks
$0 --show-config DEV
$0 --show-device-config DEV
Show configuration block of the specified NUT device
$0 --show-device-config-value DEV KEY [KEY...]
Show single configuration key value of the specified NUT device
For flags, shows the flag name if present in the section
If several keys or flags are requested, their values are reported
one per line in the same order (including empty lines for missing
values); any missing value yields a non-zero exit code.
For more information please Read The Fine Manual ('man nut-driver-enumerator')
and/or see
${NUT_WEBSITE_BASE}/docs/man/nut-driver-enumerator.html
Also check documentation of ups.conf and upsdrvsvcctl
EOF
}
while [ $# -gt 0 ]; do
case "$1" in
--help|-h|-help) usage; exit 0 ;;
--get-service-framework) echo "${SERVICE_FRAMEWORK}" ; exit 0 ;;
--reconfigure)
nut_driver_enumerator_full_reconfigure "$@"
exit $?
;;
--list-devices)
upslist_readFile_once && \
if [ "${#UPSLIST_FILE}" != 0 ] ; then
echo "=== The currently defined configurations in '$UPSCONF' are:" >&2
echo "$UPSLIST_FILE"
exit 0
fi
echo "No devices detected in '$UPSCONF'" >&2
exit 1
;;
--list-services)
UPSLIST_SVCS_RAW="`$hook_listInstances_raw`" && \
if [ "${#UPSLIST_SVCS_RAW}" != 0 ] ; then
echo "=== The currently defined service units are:" >&2
echo "$UPSLIST_SVCS_RAW"
exit 0
fi
echo "No service units detected" >&2
exit 1
;;
--list-instances)
upslist_readSvcs "by user request" && \
if [ "${#UPSLIST_SVCS}" != 0 ] ; then
echo "=== The currently defined service instances are:" >&2
echo "$UPSLIST_SVCS"
exit 0
fi
echo "No service instances detected" >&2
exit 1
;;
--get-service-for-device)
shift
get_service_for_device "$@"
exit $?
;;
--get-device-for-service)
shift
get_device_for_service "$@"
exit $?
;;
--list-services-for-devices)
shift
list_services_for_devices "$@"
exit $?
;;
--show-configs|--show-device-configs|--show-all-configs|--show-all-device-configs)
RES=0
upslist_readFile_once || RES=$?
[ "$RES" != 0 ] && { echo "ERROR: upslist_readFile_once () failed with code $RES" >&2; exit $RES; }
[ "${#UPSLIST_FILE}" != 0 ] \
|| { echo "WARNING: No devices detected in '$UPSCONF'" >&2 ; RES=1 ; }
echo "$UPSCONF_DATA"
exit $RES
;;
--show-config|--show-device-config)
[ -z "$2" ] && echo "WARNING: Device name argument empty, will show global config" >&2
DEV="$2"
upsconf_getSection "$DEV"
exit $?
;;
--show-config-value|--show-device-config-value)
[ -z "$3" ] && echo "At least one configuration key name argument is required" >&2 && exit 1
[ -z "$2" ] && echo "WARNING: Device name argument empty, will show global config" >&2
DEV="$2"
shift 2
upsconf_getValue "$DEV" "$@"
exit $?
;;
upsconf_debug) # Not public, not in usage()
[ -z "$2" ] && echo "Device name argument required" >&2 && exit 1
upsconf_debug "$2"
exit $?
;;
upslist_debug) # Not public, not in usage()
upslist_readFile_once || exit
upslist_debug
exit $?
;;
upslist_savednames_find_missing) # Not public, not in usage()
upslist_savednames_find_missing
exit $?
;;
upslist_savednames_find_mismatch) # Not public, not in usage()
upslist_savednames_find_mismatch
exit $?
;;
update_upslist_savednames_find_missing) # Not public, not in usage()
update_upslist_savednames_find_missing
exit $?
;;
hook_findSavedDeviceName) shift ; $hook_findSavedDeviceName "$@" ; exit $? ;;
hook_getSavedDeviceName) shift ; $hook_getSavedDeviceName "$@" ; exit $? ;;
*) echo "Unrecognized argument: $1" >&2 ; exit 1 ;;
esac
shift
done
|