Compare commits

..

184 Commits

Author SHA1 Message Date
Aiden McClelland
d5f7e15dfb fix typo (#1702) 2022-07-26 17:32:37 -06:00
Aiden McClelland
7bf7b1e71e NO_KEY for CI images (#1700) 2022-07-26 17:32:28 -06:00
Matt Hill
7b17498722 set Matt as default assignee (#1697) 2022-07-26 15:12:31 -06:00
Aiden McClelland
3473633e43 sync blockdev after update (#1694) 2022-07-26 10:34:23 -06:00
Aiden McClelland
f455b8a007 ask for sudo password immediately during make (#1693) 2022-07-26 10:32:32 -06:00
Aiden McClelland
daabba12d3 honor shutdown from diagnostic ui (#1692) 2022-07-25 20:21:15 -06:00
Matt Hill
61864d082f messaging for restart, shutdown, rebuild (#1691)
* messaging for restart, shutdown, rebuild

* fix typo

* better messaging
2022-07-25 15:28:53 -06:00
Aiden McClelland
a7cd1e0ce6 sync data to fs before shutdown (#1690) 2022-07-25 15:23:40 -06:00
Matt Hill
0dd6d3a500 marketplace published at for service (#1689)
* at published timestamp to marketplace package show

* add todo
2022-07-25 12:47:50 -06:00
Aiden McClelland
bdb906bf26 add marketplace_url to backup metadata for service (#1688) 2022-07-25 12:43:40 -06:00
Aiden McClelland
61da050fe8 only validate mounts for inject if eos >=0.3.1.1 (#1686)
only validate mounts for inject if `>=0.3.1.1`
2022-07-25 12:20:24 -06:00
Matt Hill
83fe391796 replace bang with question mark in html (#1683) 2022-07-25 12:05:44 -06:00
Aiden McClelland
37657fa6ad issue notification when individual package restore fails (#1685) 2022-07-25 12:02:41 -06:00
Aiden McClelland
908a945b95 allow falsey rpc response (#1680)
* allow falsey rpc response

* better check for rpc error and remove extra function

Co-authored-by: Matt Hill <matthewonthemoon@gmail.com>
2022-07-25 10:16:04 -06:00
Aiden McClelland
36c720227f allow server.update to update to current version (#1679) 2022-07-22 14:10:09 -06:00
J M
c22c80d3b0 feat: atomic writing (#1673)
* feat: atomic writing

* Apply suggestions from code review

* clean up temp files on error

Co-authored-by: Aiden McClelland <me@drbonez.dev>
2022-07-22 14:08:49 -06:00
Aiden McClelland
15af827cbc add standby mode (#1671)
* add standby mode

* fix standby mode to go before drive mount
2022-07-22 13:13:49 -06:00
Matt Hill
4a54c7ca87 draft releases notes for 0311 (#1677) 2022-07-22 11:17:18 -06:00
Alex Inkin
7b8a0eadf3 chore: enable strict mode (#1569)
* chore: enable strict mode

* refactor: remove sync data access from PatchDbService

* launchable even when no LAN url

Co-authored-by: Matt Hill <matthewonthemoon@gmail.com>
2022-07-22 09:51:08 -06:00
Aiden McClelland
9a01a0df8e refactor build process (#1675)
* add nc-broadcast to view initialization.sh logs

* include stderr

* refactor build

* add frontend/config.json as frontend dependency

* fix nc-broadcast

* always run all workflows

* address dependabot alerts

* fix build caching

* remove registries.json

* more efficient build
2022-07-21 15:18:44 -06:00
Aiden McClelland
ea2d77f536 lower log level for docker deser fallback message (#1672) 2022-07-21 12:13:46 -06:00
Aiden McClelland
e29003539b trust local ca (#1670) 2022-07-21 12:11:47 -06:00
Lucy C
97bdb2dd64 run build checks only when relevant FE changes (#1664) 2022-07-20 20:22:26 -06:00
Aiden McClelland
40d446ba32 fix migration, add logging (#1674)
* fix migration, add logging

* change stack overflow to runtime error
2022-07-20 16:00:25 -06:00
J M
5fa743755d feat: Make the rename effect (#1669)
* feat: Make the rename effect

* chore: Change to dst and src

* chore: update the remove file to use dst src
2022-07-20 13:42:54 -06:00
J M
0f027fefb8 chore: Update to have the new version 0.3.1.1 (#1668) 2022-07-19 10:03:14 -06:00
Matt Hill
56acb3f281 Mask chars beyond 16 (#1666)
fixes #1662
2022-07-18 18:31:53 -06:00
Lucy C
5268185604 add readme to system-images folder (#1665) 2022-07-18 15:48:42 -06:00
J M
635c3627c9 feat: Variable args (#1667)
* feat: Variable args

* chore: Make the assert error message not wrong
2022-07-18 15:46:32 -06:00
Chris Guida
009f7ddf84 sdk: don't allow mounts in inject actions (#1653) 2022-07-18 12:26:00 -06:00
J M
4526618c32 fix: Resolve fighting with NM (#1660) 2022-07-18 09:44:33 -06:00
Matt Hill
6dfd46197d handle case where selected union enum is invalid after migration (#1658)
* handle case where selected union enum is invalid after migration

* revert necessary ternary and fix types

Co-authored-by: Lucy Cifferello <12953208+elvece@users.noreply.github.com>
2022-07-17 13:42:36 -06:00
Aiden McClelland
778471d3cc Update product.yaml (#1638) 2022-07-13 11:15:45 -06:00
Aiden McClelland
bbcf2990f6 fix build (#1639) 2022-07-13 11:14:50 -06:00
Aiden McClelland
ac30ab223b return correct error on failed os download (#1636) 2022-07-12 12:48:18 -06:00
J M
50e7b479b5 Fix/receipts health (#1616)
* release lock on update progress (#1614)

* chore: remove the receipt

* chore: Remove the receipt

Co-authored-by: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com>
2022-07-12 12:48:01 -06:00
Aiden McClelland
1367428499 update backend dependencies (#1637) 2022-07-12 12:18:12 -06:00
Mariusz Kogen
e5de91cbe5 🐋 docker stats fix (#1630)
* entry obsolete...

* 🐋 docker stats fix
2022-07-11 18:18:22 -06:00
J M
244260e34a chore: updating lock just from make clean; make (#1631) 2022-07-08 16:07:34 -06:00
Lucy C
575ed06225 fix display of comma between breakages (#1628) 2022-07-07 17:08:06 -06:00
Mariusz Kogen
b6fdc57888 Tor repository fix for arm64 (#1623)
When doing `sudo apt update` you get this:
`N: Skipping acquire of configured file 'main/binary-armhf/Packages' as repository 'https://deb.torproject.org/torproject.org bullseye InRelease' doesn't support architecture 'armhf'`
2022-07-07 15:34:54 -06:00
Aiden McClelland
758d7d89c2 keep status if package has no config (#1626) 2022-07-07 15:34:06 -06:00
Aiden McClelland
2db31b54e8 fix icons for sideloaded packages (#1624) 2022-07-07 15:33:53 -06:00
Thomas Moerkerken
99d16a37d5 Fix/adjust pipeline (#1619)
* use the correct frontend make target

* allow interactive tty if available

* fix syntax on pipeline trigger paths
2022-07-06 17:10:35 -06:00
Lucy C
449968bc4e Fix/misc UI (#1622)
* show available marketplace updates in menu

* complete feature

* delete unused class

* update tsmatches to remove console log

* fix merge conflict

* change config header font size

* fix new options emission for config elements

* delete unecessary import

* add custom modal for service marketplace conflict action

* cleanup

* remove unecessary imports

* pr cleanup of unused imports and classes

Co-authored-by: Matt Hill <matthewonthemoon@gmail.com>
2022-07-06 17:10:22 -06:00
Aiden McClelland
b0a55593c1 handle current-dependents properly during update (#1621) 2022-07-06 10:34:03 -06:00
Lucy C
17ef97c375 remove beta flag actions from UI config build (#1617)
* remove beta flag

Co-authored-by: Aiden McClelland <me@drbonez.dev>
2022-07-05 13:49:53 -06:00
Thomas Moerkerken
36e0ba0f06 Add basic GitHub workflows builds (#1578)
* add easy target for backend build

* add reusable backend build workflow

* add reusable frontend build workflow

* add full build workflow

* add some comments
2022-07-05 13:46:06 -06:00
gStart9
b365a60c00 Default to https:// urls for repositories, remove apt-transport-https (#1610)
As of apt 1.5 (released 2017), the package apt-transport-https is no longer required because https:// is supported out of the box.
Reference: https://packages.debian.org/bullseye/apt-transport-https "This is a dummy transitional package - https support has been moved into the apt package in 1.5. It can be safely removed."  Apt is currently at 2.2.4.

Use a sed one-liner to convert all repos in /etc/apt/sources.list and /etc/apt/sources.list.d/*.list that are http:// to https:// (https:// is available for all http:// URLs currently referenced in EmbassyOS).
2022-07-05 13:45:10 -06:00
Lucy C
88afb756f5 show available marketplace updates in menu (#1613)
* show service updates in menu
2022-07-05 13:02:32 -06:00
Aiden McClelland
e2d58c2959 release lock on update progress (#1614) 2022-07-05 12:01:54 -06:00
Lucy C
3cfc333512 fix conditional display state (#1612)
* fix conditional display state

* fix footer

* fix empty case

* remove select all from backup restore

* fix styling and add warning message to service restore

* update copy
2022-07-04 15:06:23 -06:00
J M
89da50dd37 fix: Closed file (#1608) 2022-07-04 14:17:43 -06:00
Matt Hill
9319314672 display bottom item in backup list and refactor for cleanliness (#1609)
* display bottom item in backup list and refactor for cleanliness

* fix spelling mistake

* display initial toggle to deselect all, as all are selected by default

* add select/deselect all to backup restore and handle backup case when no services intalled

Co-authored-by: Lucy Cifferello <12953208+elvece@users.noreply.github.com>
2022-07-04 14:16:18 -06:00
Lucy C
6d805ae941 Fix/UI misc (#1606)
* stop expansion when description icon clicked

* add test for ensuring string sanitization

* rename log out to terminate in sessions component and remove sanitization bypass as unneeded

* remove unecessary instances of safe string
2022-07-01 18:25:45 -06:00
J M
8ba932aa36 feat: fetch effect (#1605)
* feat: fetch effect

* fix: Make not available in sandbox

* chore: Update to use text(), and to use headers

* chore: use the postman echo for testing

* chore: add json

* chore: Testing the json

* chore: Make the json lazy
2022-07-01 17:05:01 -06:00
Aiden McClelland
b580f549a6 actually purge old current-dependents 2022-07-01 16:06:01 -06:00
Lucy C
cb9c01d94b strip html from colors from logs (#1604) 2022-07-01 15:41:09 -06:00
Aiden McClelland
f9b0f6ae35 don't crash service if io-format is set for main (#1599) 2022-07-01 09:29:11 -06:00
Lucy C
1b1ff05c81 fix html parsing in logs (#1598) 2022-06-30 16:41:55 -06:00
Matt Hill
7b465ce10b nest new entries and message updates better (#1595)
* nest new entries and message updates better

* pass has new upward

* fix bulb display to make everyone happy
2022-06-30 15:32:54 -06:00
J M
ee66395dfe chore: commit the snapshots (#1592) 2022-06-30 12:39:51 -06:00
J M
31af6eeb76 fix: Stop the buffer from dropped pre-maturly (#1591) 2022-06-30 12:14:57 -06:00
Lucy C
e9a2d81bbe add select/deselect all to backups and enum lists (#1590) 2022-06-30 12:02:16 -06:00
Aiden McClelland
7d7f03da4f filter package ids when backing up (#1589) 2022-06-30 11:23:01 -06:00
Lucy C
8966b62ec7 update patchdb for array patch fix (#1588) 2022-06-29 17:51:20 -06:00
Aiden McClelland
ec8d9b0da8 switch to utc 2022-06-29 15:43:01 -06:00
Matt Hill
38ba1251ef turn chevron red in config if error (#1586) 2022-06-29 14:55:39 -06:00
Matt Hill
005c46cb06 preload redacted and visibility hidden (#1584)
* preload redacted and visibility hidden

* remove comment

* update patchdb

Co-authored-by: Lucy Cifferello <12953208+elvece@users.noreply.github.com>
2022-06-29 09:13:52 -06:00
Aiden McClelland
4b0ff07d70 Bugfix/backup lock order (#1583)
* different fix

* Revert "fix backup lock ordering (#1582)"

This reverts commit f1e065a448.
2022-06-29 09:03:10 -06:00
Aiden McClelland
f1e065a448 fix backup lock ordering (#1582) 2022-06-28 15:10:26 -06:00
J M
c82c6eaf34 fix: Properties had a null description (#1581)
* fix: Properties had a null description

* Update frontend/projects/ui/src/app/util/properties.util.ts
2022-06-28 13:57:51 -06:00
Matt Hill
b8f3759739 update welcome notes for 031 (#1580) 2022-06-28 13:41:05 -06:00
kn0wmad
70aba1605c Feat/use modern tor (#1575)
* Add guardian project repo and install latest stable tor

* Apt appendage
2022-06-28 12:28:08 -06:00
Matt Hill
2c5aa84fe7 selective backups and better drive selection interface (#1576)
* selective backups and better drive selection interface

* fix disabled checkbox and backup drives menu styling

* feat: package-ids

* only show services that are backing up on backup page

* refactor for performace and cleanliness

Co-authored-by: Matt Hill <matthill@Matt-M1.start9.dev>
Co-authored-by: Lucy Cifferello <12953208+elvece@users.noreply.github.com>
Co-authored-by: J M <mogulslayer@gmail.com>
2022-06-28 12:14:26 -06:00
Aiden McClelland
753f395b8d add avahi conditional compilation flags to dns (#1579) 2022-06-28 10:42:54 -06:00
Lucy C
f22f11eb58 Fix/sideload icon type (#1577)
* add content type to icon dataURL

* better handling of blob reading; remove verifying loader and reorganize html

* clean up PR feedback and create validation fn instead of boolean

* grpup upload state into one type

* better organize validation

* add server id to eos check for updates req

* fix patchdb to latest

Co-authored-by: Matt Hill <matthewonthemoon@gmail.com>
2022-06-27 15:25:42 -06:00
Lucy C
123f71cb86 Fix/mask generic inputs (#1570)
* add masking to generic input component

* clear inputs after submission

* adjust convenience FE make steps

* cleaner masking

* remove mask pipe from module

* switch to redacted font
2022-06-27 13:51:35 -06:00
Aiden McClelland
22af45fb6e add dns server to embassy-os (#1572)
* add dns server to embassy-os

* fix initialization

* multiple ip addresses
2022-06-27 10:53:06 -06:00
Matt Hill
0849df524a fix connection failure display monitoring and other style changes (#1573)
* fix connection failure display monitoring and other style chnages

* display updates more clearly in marketplace

* remove scrolling from release notes and long description

* remove unnecessary bangs

Co-authored-by: Matt Hill <matthill@Matt-M1.local>
Co-authored-by: Matt Hill <matthill@Matt-M1.start9.dev>
2022-06-27 10:44:12 -06:00
Lucy C
31952afe1e adjust service marketplace button for installation source relevance (#1571)
* adjust service marketplace button for installation source relevance

* cleanup

* show marketplace name instead of url; cleanup from PR feedback

* fix spacing

* further cleanup
2022-06-27 10:09:27 -06:00
Matt Hill
83755e93dc kill all sessions and remove ripple effect (#1567)
* button to kill all sessions, session sorting, remove ripple effect from buttons

* pr cleanup

Co-authored-by: Matt Hill <matthill@Matt-M1.local>
Co-authored-by: Lucy Cifferello <12953208+elvece@users.noreply.github.com>
2022-06-23 16:59:13 -06:00
J M
0fbcc11f99 fix: Make it so we only need the password on the backup (#1566)
* fix: Make it so we only need the password on the backup

* chore: Remove the rewrite of password
2022-06-23 10:25:47 -06:00
Matt Hill
d431fac7de fix bugs with config and clean up dev options (#1558)
* fix bugs with config and clean up dev options

* dont down down arrow in logs prematurely

* change config error border to match error text red color

* change restart button color

* fix error when sideloading and update copy

* adds back in param cloning as this bug creeped up again

* make restarting text match button color

* fix version comparision for updates category

Co-authored-by: Matt Hill <matthill@Matt-M1.local>
Co-authored-by: Lucy Cifferello <12953208+elvece@users.noreply.github.com>
2022-06-22 18:26:10 -06:00
Alex Inkin
53ca9b0420 refactor(patch-db): use PatchDB class declaratively (#1562)
* refactor(patch-db): use PatchDB class declaratively

* chore: remove initial source before init

* chore: show spinner

* fix: show Connecting to Embassy spinner until first connection

* fix: switching marketplaces

* allow for subscription to end with take when installing a package

* update patchdb

Co-authored-by: Lucy Cifferello <12953208+elvece@users.noreply.github.com>
2022-06-22 16:09:14 -06:00
BitcoinMechanic
a8749f574a fixed sentence that didn't make sense (#1565) 2022-06-22 09:57:10 -07:00
J M
a9d839fd8f fix: Missing a feature flat cfg (#1563) 2022-06-21 10:34:03 -06:00
J M
477d37f87d feat: Make sdk (#1564) 2022-06-21 10:25:54 -06:00
Matt Hill
d2195411a6 Reset password through setup wizard (#1490)
* closes FE portion of  #1470

* remove accidental commit of local script

* add reset password option (#1560)

* fix error code for incorrect password and clarify codes with comments

Co-authored-by: Matt Hill <matthill@Matt-M1.local>
Co-authored-by: Lucy Cifferello <12953208+elvece@users.noreply.github.com>
Co-authored-by: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com>
2022-06-20 16:48:32 -06:00
J M
1f5e6dbff6 chore: Add tracing for debuging the js procedure slowness (#1552)
* chore: Add tracing for debuging the js procedure slowness

* chore: Make the display to reduce vertical clutter
2022-06-20 16:22:19 -06:00
Lucy C
09c0448186 update should send version not version spec (#1559) 2022-06-20 14:18:20 -06:00
Lucy C
b318bf64f4 fix backend builds for safe git config (#1549) 2022-06-19 14:25:39 -06:00
Lucy Cifferello
af1d2c1603 update welcome message 2022-06-19 13:46:09 -06:00
Lucy Cifferello
1c11d3d08f update patch db 2022-06-19 13:46:09 -06:00
Lucy C
a4a8f33df0 Feature/restart service (#1554)
* add restart button to service show page and restart rpc api

* Feature/restart rpc (#1555)

* add restart rpc and status

* wire up rpc

* add restarting bool

Co-authored-by: Aiden McClelland <me@drbonez.dev>

* check if service is restarting

* filter package when restarting to avoid glitch

Co-authored-by: Aiden McClelland <me@drbonez.dev>
2022-06-19 13:46:09 -06:00
Lucy Cifferello
889cf03c1c fix circular images in instructions markdown modal 2022-06-19 13:46:09 -06:00
Matt Hill
0ac5b34f2d Remove app wiz and dry calls (#1541)
* no more app wiz or dry calls

* change spinner type

* better display for update available

* reintroduce dep breakages for update/downgrade and style alerts everywhere

* only show install alert on first install

Co-authored-by: Matt Hill <matthill@Matt-M1.local>
Co-authored-by: Matt Hill <matthill@Matt-M1.start9.dev>
2022-06-19 13:46:09 -06:00
Lucy Cifferello
37304a9d92 chore: cleanup and small misc fixes
display success alert if on latest EOS after check for update

fix bug with loader dismiss after alert present

fix restart button on update complete alert and fix mocks to account for this state

fix make clean and adjust default registry names
2022-06-19 13:46:09 -06:00
Matt Hill
4ad9886517 refactor app wizards completely (#1537)
* refactor app wizards completely

* display new and new options in config

Co-authored-by: Matt Hill <matthill@Matt-M1.start9.dev>
2022-06-19 13:46:09 -06:00
Matt Hill
8e9d2b5314 chore: cleanup - show spinner on service list when transitioning
config add new list items to end and auto scroll

remove js engine artifacts

fix view button in notification toast
2022-06-19 13:46:09 -06:00
Lucy C
7916a2352f Feature/sideload (#1520)
* base styling and action placeholders for package sideload

* apparently didnt add new folder

* wip

* parse manifest and icon from s9pk to upload

* wip handle s9pk upload

* adjust types, finalize actions, cleanup

* clean up and fix data clearing and response

* include rest rpc in proxy conf sample

* address feedback to use shorthand falsy coercion

* update copy and invalid package file ux

* do not wait package upload, instead show install progress

* fix proxy for rest rpc

rename sideload package page titles
2022-06-19 13:46:09 -06:00
Matt Hill
2b92d0f119 Swtich certain inputs and displays to courier for readability (#1521)
swtich certain inputs and displays to courier for readability

Co-authored-by: Matt Hill <matthill@Matt-M1.local>
2022-06-19 13:46:09 -06:00
Matt Hill
961a9342fa display QR code for interfaces (#1507)
* display QR code for interfaces

* add play-outline to preloader

Co-authored-by: Matt Hill <matthill@Matt-M1.local>
2022-06-19 13:46:09 -06:00
Lucy C
3cde39c7ed Feature/copy logs (#1491)
* make text selectable on mobile

* make logs copyable and adjust copy format

* fix linting

* fix linting further

* linting

* add formatting to copied logs

* fix copy abstraction and add formatting for server log copy
2022-06-19 13:46:09 -06:00
Matt Hill
09922c8dfa Rework install progress types and pipes for clarity (#1513)
* rework install progress types and pipes for clarity

* rework marketplace show display

Co-authored-by: Matt Hill <matthill@Matt-M1.local>
2022-06-19 13:46:09 -06:00
waterplea
0390954a85 feat: enable strictNullChecks
feat: enable `noImplicitAny`

chore: remove sync data access

fix loading package data for affected dependencies

chore: properly get alt marketplace data

update patchdb client to allow for emit on undefined values
2022-06-19 13:46:09 -06:00
J M
948fb795f2 feat: uid/gid/mode added to metadata (#1551) 2022-06-17 12:16:04 -06:00
J M
452c8ea2d9 Feat/js metadata (#1548)
* feat: metadata effect

* feat: Metadata for effects

* chore: Add in the new types
2022-06-16 15:58:48 -06:00
Aiden McClelland
9c41090a7a add textarea to ValueSpecString (#1534) 2022-06-16 13:14:18 -06:00
Aiden McClelland
59eee33767 fix dependency/dependent id issue (#1546) 2022-06-16 13:14:05 -06:00
Aiden McClelland
cc5e60ed90 fix incorrect error message for deserialization in ValueSpecString (#1547) 2022-06-16 13:13:50 -06:00
J M
27bc493884 Feat: Make the js check for health (#1543)
* Feat: Make the js check for health

* chore: Add in the migration types

* feat: type up the migration
2022-06-16 11:58:55 -06:00
J M
75a2b2d2ab chore: Update the lite types to include the union and enum (#1542) 2022-06-15 19:31:47 -06:00
J M
0b7d8b4db0 fix: found a unsaturaded args fix 2022-06-15 14:40:42 -06:00
J M
d05cd7de0d chore: Update types to match embassyd (#1539)
* chore: Update types to match embassyd

* chore: Undo the optional
2022-06-15 14:39:20 -06:00
Aiden McClelland
b0068a333b disable unnecessary services 2022-06-14 12:43:27 -06:00
Aiden McClelland
d947c2db13 fixes #1169 (#1533)
* fixes #1169

* consolidate trim

Co-authored-by: J M <2364004+Blu-J@users.noreply.github.com>

Co-authored-by: J M <2364004+Blu-J@users.noreply.github.com>
2022-06-14 11:47:04 -06:00
Aiden McClelland
90e09c8c25 add "error_for_status" to static file downloads 2022-06-14 11:42:31 -06:00
J M
dbf59a7853 fix: restart/ uninstall sometimes didn't work (#1527)
* fix: restart/ uninstall sometimes didn't work

* Fix: Match the original lock types
2022-06-13 14:18:41 -06:00
Aiden McClelland
4d89e3beba fixes a bug where nginx will crash if eos goes into diagnostic mode a… (#1506)
fixes a bug where nginx will crash if eos goes into diagnostic mode after service init has completed
2022-06-13 12:43:12 -06:00
J M
5a88f41718 Feat/js known errors (#1514)
* feat: known errors for js

* chore: add expected exports

* Update js_scripts.rs

* chore: Use agreed upon shape

* chore: add updates to d.ts

* feat: error case

* chore: Add expectedExports as a NameSpace`

* chore: add more documentation to the types.d.ts
2022-06-10 13:04:52 -06:00
Aiden McClelland
435956a272 fix "missing proxy" error in embassy-cli (#1516)
* fix "missing proxy" error in embassy-cli

* fix: Add test and other fix for SetResult

Co-authored-by: J M <mogulslayer@gmail.com>
2022-06-10 12:58:58 -06:00
Aiden McClelland
7854885465 allow interactive TTY if available 2022-06-08 09:29:24 -06:00
Keagan McClelland
901ea6203e fixes serialization of regex pattern + description 2022-06-07 17:32:47 -06:00
J M
9217d00528 Fix/memory leak docker (#1505)
* fix: potential fix for the docker leaking the errors and such

* chore: Make sure that the buffer during reading the output will not exceed 10mb ish

* Chore: Add testing

* fix: Docker buffer reading to lines now works

* chore: fixing the broken responses
2022-06-07 12:58:12 -06:00
J M
f234f894af fix: potential fix for the docker leaking the errors and such (#1496)
* fix: potential fix for the docker leaking the errors and such

* chore: Make sure that the buffer during reading the output will not exceed 10mb ish

* Chore: Add testing
2022-06-07 11:11:43 -06:00
Aiden McClelland
4286edd78f allow embassy-cli not as root (#1501)
* allow embassy-cli not as root
* clean up merge
2022-06-07 11:11:01 -06:00
Keagan McClelland
334437f677 generate unique ca names based off of server id 2022-06-06 18:56:27 -06:00
Keagan McClelland
183c5cda14 refactors error handling for less redundancy 2022-06-06 18:43:32 -06:00
Keagan McClelland
45265453cb control experiment for correct configs 2022-06-06 18:43:32 -06:00
Keagan McClelland
80a06272cc fixes regex black hole 2022-06-06 18:23:28 -06:00
J M
473213d14b chore: fix the master (#1495)
* chore: fix the master

* chore: commit all the things swc
2022-06-06 15:02:44 -06:00
Matt Hill
d53e295569 UI cosmetic improvements (#1486)
* resize alerts and modals

* fix log color

* closes #1404

Co-authored-by: Matt Hill <matthill@Matt-M1.local>
2022-06-06 11:31:45 -06:00
Thomas Moerkerken
18e2c610bc add quotes to handles spaces in working dir 2022-06-06 10:10:51 -06:00
J M
e0c68c1911 Fix/patch db unwrap remove (#1481)
* fix: Change the git to always give a maybe, then create the error in the failure cases

* fix: No wifi last

* chore: Revert to older api

* fix: build for sdk

* fix: build for sdk

* chore: update patch db

* chore: use the master patch db
2022-06-06 09:52:19 -06:00
Mariusz Kogen
34729c4509 Enable Control Groups for Docker containers (#1468)
Enabling Control Groups give Docker containers the ability to track and expose missing memory metrics. Try `docker stats`
2022-06-06 08:32:33 -06:00
Matt Hill
ca778b327b Clean up config (#1484)
* better formatting for union list

* cleaner config

Co-authored-by: Matt Hill <matthill@Matt-M1.local>
2022-06-03 12:35:56 -06:00
Benjamin B
bde6169746 Update contribution and frontend readme (#1467)
* docs: small updates to contributing and frontend readme

* chore: change build:deps script to use npm ci
2022-06-03 12:26:45 -06:00
Lucy C
3dfbf2fffd UI version updates and welcome message for 0.3.1 (#1479) 2022-06-03 12:23:32 -06:00
Benjamin B
34068ef633 Link to tor address on LAN setup page (#1277) (#1466)
* style: format lan page component

* Link to tor address on LAN setup page (#1277)
2022-06-01 15:43:57 -06:00
Benjamin B
e11729013f Disable view in marketplace button when side-loaded (#1471)
Disble view in marketplace button when side-loaded
2022-06-01 15:20:45 -06:00
Thomas Moerkerken
cceef054ac remove interactive TTY requirement from cmds 2022-06-01 14:37:12 -06:00
J M
b8751e7add Chore/version 0 3 1 0 (#1475)
* feat: move over to workspaces

* chore: Move to libs

* chore:fix(build): Compat

* chore: fixing pr
2022-06-01 10:22:00 -06:00
Keagan McClelland
37344f99a7 cleanup after rebase 2022-05-27 13:20:33 -06:00
Keagan McClelland
61bcd8720d warn if script is present but manifest does not require one 2022-05-27 13:20:33 -06:00
Keagan McClelland
6801ff996e require script is present during pack step iff any pkg procs are type script 2022-05-27 13:20:33 -06:00
J M
c8fc9a98bf fix: Change the source + add input 2022-05-27 13:20:33 -06:00
J M
52de5426ad Feat: js action
wip: Getting async js

feat: Have execute get action config

feat: Read + Write

chore: Add typing for globals

chore: Change the default path, include error on missing function, and add json File Read Write

chore: Change the default path, include error on missing function, and add json File Read Write

wip: Fix the unit test

wip: Fix the unit test

feat: module loading
2022-05-27 13:20:33 -06:00
Benjamin B
e7d0a81bfe Fix links in CONTRIBUTING.md, update ToC 2022-05-27 11:45:57 -06:00
Alex Inkin
4f3223d3ad refactor: isolate network toast and login redirect to separate services (#1412)
* refactor: isolate network toast and login redirect to separate services

* chore: remove accidentally committed sketch of a service

* chore: tidying things up

* feat: add `GlobalModule` encapsulating all global subscription services

* remove angular build cache when building deps

* chore: fix more issues found while testing

* chore: fix issues reported by testing

* chore: fix template error

* chore: fix server-info

* chore: fix server-info

* fix: switch to Observable to fix race conditions

* fix embassy name display on load

* update patchdb

* clean up patch data watch

Co-authored-by: Lucy Cifferello <12953208+elvece@users.noreply.github.com>
2022-05-26 16:56:47 -06:00
J M
4829637b46 fix: Dependency vs dependents (#1462)
* fix: Dependency vs dependents

* chore: Remove the debugging
2022-05-26 15:39:46 -06:00
J M
7f2494a26b Fix/making js work (#1456)
* Feat: js action

wip: Getting async js

feat: Have execute get action config

feat: Read + Write

chore: Add typing for globals

chore: Change the default path, include error on missing function, and add json File Read Write

chore: Change the default path, include error on missing function, and add json File Read Write

wip: Fix the unit test

wip: Fix the unit test

feat: module loading

* fix: Change the source + add input

* fix: Change the source + add input

wip: Fix missing js files during running

fix: Change the source + add input

wip: Fix missing js files during running

* fix: other paths

* feat: Build the arm js snapshot

* fix: test with more

* chore: Make the is_subset a result
2022-05-25 12:19:40 -06:00
J M
f7b5fb55d7 Feat/js action (#1437)
* Feat: js action

wip: Getting async js

feat: Have execute get action config

feat: Read + Write

chore: Add typing for globals

chore: Change the default path, include error on missing function, and add json File Read Write

chore: Change the default path, include error on missing function, and add json File Read Write

wip: Fix the unit test

wip: Fix the unit test

feat: module loading

* fix: Change the source + add input

* fix: single thread runtime

* fix: Smaller fixes

* Apply suggestions from code review

Co-authored-by: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com>

* fix: pr

Co-authored-by: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com>
2022-05-19 18:02:50 -06:00
Lucy C
2b6e54da1e Proxy local frontend to remote backend (#1452)
* add server proxy configurations

* change address to host due to compliation warning

* adjust config sample to more accurately reflect production version
2022-05-19 15:58:32 -06:00
Jonathan Zernik
1023916390 Add nginx config for proxy redirect (#1421)
* Add nginx config for proxy redirect protocol prefix

* Update proxy_redirect config to use scheme variable

* Only include proxy redirect directive when ssl is true
2022-05-19 14:56:53 -06:00
Keagan McClelland
6a0e9d5c0a refactor packer to async 2022-05-19 11:08:22 -06:00
Aiden McClelland
7b4d657a2d actually address warning instead of muting it like a sociopath 2022-05-16 16:46:59 -06:00
Keagan McClelland
b7e86bf556 cleanse warnings 2022-05-16 16:46:59 -06:00
Aiden McClelland
fa777bbd63 fix remaining rename 2022-05-16 16:23:46 -06:00
Aiden McClelland
2e7b2c15bc rename ActionImplementation to PackageProcedure 2022-05-16 16:23:46 -06:00
Keagan McClelland
9bc0fc8f05 formatting 2022-05-16 16:11:45 -06:00
Keagan McClelland
b354d30fe9 Update backend/src/s9pk/header.rs
Co-authored-by: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com>
2022-05-16 16:11:45 -06:00
Keagan McClelland
a253e95b5a make scripts optional 2022-05-16 16:11:45 -06:00
Keagan McClelland
7e4c0d660a fix paths 2022-05-16 16:11:45 -06:00
Keagan McClelland
6a8bf2b074 s/open/create 2022-05-16 16:11:45 -06:00
Keagan McClelland
16729ebffc change script path 2022-05-16 16:11:45 -06:00
Keagan McClelland
f44d432b6a no tar for scripts 2022-05-16 16:11:45 -06:00
Keagan McClelland
93ee418f65 redundant imports 2022-05-16 16:11:45 -06:00
Keagan McClelland
cd6bda2113 optional script unpacking 2022-05-16 16:11:45 -06:00
Keagan McClelland
4a007cea78 cleanup assets and scripts on uninstall 2022-05-16 16:11:45 -06:00
Keagan McClelland
ab532b4432 fix script name 2022-05-16 16:11:45 -06:00
Keagan McClelland
ee98b91a29 remove scripts volume 2022-05-16 16:11:45 -06:00
Keagan McClelland
0294143b22 create script dirs on install 2022-05-16 16:11:45 -06:00
Keagan McClelland
2890798342 pack scripts into s9pk 2022-05-16 16:11:45 -06:00
Keagan McClelland
2d44852ec4 iterators can be played now 2022-05-16 11:24:14 -06:00
Keagan McClelland
b9de5755d1 fix error with circle of fifths type 2022-05-16 11:24:14 -06:00
Mariusz Kogen
84463673e2 ☯️ For the peace of mind ☯️ (#1444)
Simplifying and clarifying for first time builders
2022-05-16 11:09:11 -06:00
Dread
56efe9811d Update README.md to include yq (#1385)
Update README.md to include yq install instructions for Linux
2022-05-11 16:23:10 -06:00
Keagan McClelland
a6234e4507 adds product key to error message in setup flow when there is mismatch 2022-05-11 16:19:24 -06:00
Keagan McClelland
e41b2f6ca9 make nicer update sound 2022-05-11 16:15:56 -06:00
Lucy C
8cf000198f Fix/id params (#1414)
* watch config.json for changes when just building frontend

* fix version for data consistency

* clone param ids so not recursively stringified; add global type for stringified instances

* ensure only most recent data source grabbed to fix issue with service auto update on marketplace switch

* use take instead of shallow cloning data
2022-05-10 12:20:32 -06:00
J M
cc6cbbfb07 chore: Convert from ajv to ts-matches (#1415) 2022-05-10 11:00:56 -06:00
Mariusz Kogen
10d7a3d585 Switching SSH keys to start9 user (#1321)
* Update ssh.rs for start9 user

* .ssh directory for uid 1000 user

* Update init.rs for start9 user

* “His name is Robert Paulson”

* typo

* just cleaning up ...
2022-05-09 15:16:24 -06:00
J M
864555bcf0 Feat bulk locking (#1422)
* Feat: Multi-lock capabilities add to config

* wip: RPC.rs fixes, new combinatoric

* wip: changes

* chore: More things that are bulk

* fix: Saving

* chore: Remove a dyn object

* chore: Add tests + remove unused

* Fix/feat  bulk locking (#1427)

* fix: health check

* fix: start/stop service

* fix: install/uninstall services

* chore: Fix the notifications

* fix: Version

* fix: Version as serde

* chore: Update to latest patch db

* chore: Change the htLock to something that makes more sense

* chore: Fix the rest of the ht

* "chore: More ht_lock":
2022-05-09 14:53:39 -06:00
489 changed files with 24483 additions and 9637 deletions

View File

@@ -3,14 +3,14 @@ description: Create a report to help us improve EmbassyOS
title: '[bug]: ' title: '[bug]: '
labels: [Bug, Needs Triage] labels: [Bug, Needs Triage]
assignees: assignees:
- dr-bonez - MattDHill
body: body:
- type: checkboxes - type: checkboxes
attributes: attributes:
label: Prerequisites label: Prerequisites
description: Please confirm you have completed the following. description: Please confirm you have completed the following.
options: options:
- label: I have searched for [existing issues](https://github.com/start9labs/embassy-os/issues) that already report this problem, without success. - label: I have searched for [existing issues](https://github.com/start9labs/embassy-os/issues) that already report this problem.
required: true required: true
- type: input - type: input
attributes: attributes:

View File

@@ -3,14 +3,14 @@ description: Suggest an idea for EmbassyOS
title: '[feat]: ' title: '[feat]: '
labels: [Enhancement] labels: [Enhancement]
assignees: assignees:
- dr-bonez - MattDHill
body: body:
- type: checkboxes - type: checkboxes
attributes: attributes:
label: Prerequisites label: Prerequisites
description: Please confirm you have completed the following. description: Please confirm you have completed the following.
options: options:
- label: I have searched for [existing issues](https://github.com/start9labs/embassy-os/issues) that already suggest this feature, without success. - label: I have searched for [existing issues](https://github.com/start9labs/embassy-os/issues) that already suggest this feature.
required: true required: true
- type: textarea - type: textarea
attributes: attributes:

24
.github/workflows/README.md vendored Normal file
View File

@@ -0,0 +1,24 @@
# This folder contains GitHub Actions workflows for building the project
## backend-pr
Runs: when a pull request targets the master branch and changes the libs/ and/or backend/ folders
This workflow uses the actions docker/setup-qemu-action@v1 and docker/setup-buildx-action@v1 to prepare the environment for aarch64 cross complilation using docker buildx.
A matrix-strategy has been used for building the v8 snapshot instead of the makefile to allow parallel job execution.
## frontend-pr
Runs: when a pull request targets the master branch and changes the frontend/ folder
This workflow builds the frontends.
## product
Runs: when a change to the master branch is made
This workflow builds everything, re-using the backend-pr and frontend-pr workflows.
The download and extraction order of artifacts is relevant to `make`, as it checks the file timestamps to decide which targets need to be executed.
Result: eos.img
## a note on uploading artifacts
Artifacts are used to share data between jobs. File permissions are not maintained during artifact upload. Where file permissions are relevant, the workaround using tar has been used. See (here)[https://github.com/actions/upload-artifact#maintaining-file-permissions-and-case-sensitive-files].

98
.github/workflows/backend-pr.yaml vendored Normal file
View File

@@ -0,0 +1,98 @@
name: Backend PR
on:
workflow_call:
workflow_dispatch:
jobs:
libs:
name: Build libs
strategy:
matrix:
target: [amd64, arm64]
include:
- target: amd64
snapshot_command: ./build-v8-snapshot.sh
artifact_name: js_snapshot
artifact_path: libs/js_engine/src/artifacts/JS_SNAPSHOT.bin
- target: arm64
snapshot_command: ./build-arm-v8-snapshot.sh
artifact_name: arm_js_snapshot
artifact_path: libs/js_engine/src/artifacts/ARM_JS_SNAPSHOT.bin
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
libs/target/
key: ${{ runner.os }}-cargo-libs-${{ matrix.target }}-${{ hashFiles('libs/Cargo.lock') }}
- name: Build v8 snapshot
run: ${{ matrix.snapshot_command }}
working-directory: libs
- uses: actions/upload-artifact@v3
with:
name: ${{ matrix.artifact_name }}
path: ${{ matrix.artifact_path }}
backend:
name: Build backend
runs-on: ubuntu-latest
needs: libs
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- name: Download arm_js_snapshot artifact
uses: actions/download-artifact@v3
with:
name: arm_js_snapshot
path: libs/js_engine/src/artifacts/
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
backend/target/
key: ${{ runner.os }}-cargo-backend-${{ hashFiles('backend/Cargo.lock') }}
- name: Build backend
run: make backend
- name: 'Tar files to preserve file permissions'
run: tar -cvf backend.tar ENVIRONMENT.txt GIT_HASH.txt backend/target/aarch64-unknown-linux-gnu/release/embassy*
- uses: actions/upload-artifact@v3
with:
name: backend
path: backend.tar

41
.github/workflows/frontend-pr.yaml vendored Normal file
View File

@@ -0,0 +1,41 @@
name: Frontend PR
on:
workflow_call:
workflow_dispatch:
jobs:
frontend:
name: Build frontend
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- uses: actions/setup-node@v3
with:
node-version: 16
- name: Get npm cache directory
id: npm-cache-dir
run: |
echo "::set-output name=dir::$(npm config get cache)"
- uses: actions/cache@v3
id: npm-cache
with:
path: ${{ steps.npm-cache-dir.outputs.dir }}
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Build frontends
run: make frontends
- name: 'Tar files to preserve file permissions'
run: tar -cvf frontend.tar ENVIRONMENT.txt GIT_HASH.txt frontend/dist frontend/config.json
- uses: actions/upload-artifact@v3
with:
name: frontend
path: frontend.tar

155
.github/workflows/product.yaml vendored Normal file
View File

@@ -0,0 +1,155 @@
name: Build Pipeline
on:
workflow_dispatch:
push:
branches:
- master
- next
pull_request:
branches:
- master
- next
jobs:
compat:
name: Build compat.tar
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-compat-${{ hashFiles('**/system-images/compat/Cargo.lock') }}
- name: Build image
run: make system-images/compat/compat.tar
- uses: actions/upload-artifact@v3
with:
name: compat.tar
path: system-images/compat/compat.tar
utils:
name: Build utils.tar
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Build image
run: make system-images/utils/utils.tar
- uses: actions/upload-artifact@v3
with:
name: utils.tar
path: system-images/utils/utils.tar
backend:
uses: ./.github/workflows/backend-pr.yaml
frontend:
uses: ./.github/workflows/frontend-pr.yaml
image:
name: Build image
runs-on: ubuntu-latest
needs: [compat,utils,backend,frontend]
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- name: Download compat.tar artifact
uses: actions/download-artifact@v3
with:
name: compat.tar
path: system-images/compat
- name: Download utils.tar artifact
uses: actions/download-artifact@v3
with:
name: utils.tar
path: system-images/utils
- name: Download js_snapshot artifact
uses: actions/download-artifact@v3
with:
name: js_snapshot
path: libs/js_engine/src/artifacts/
- name: Download arm_js_snapshot artifact
uses: actions/download-artifact@v3
with:
name: arm_js_snapshot
path: libs/js_engine/src/artifacts/
- name: Download backend artifact
uses: actions/download-artifact@v3
with:
name: backend
- name: 'Extract backend'
run:
tar -mxvf backend.tar
- name: Download frontend artifact
uses: actions/download-artifact@v3
with:
name: frontend
- name: Skip frontend build
run: |
mkdir frontend/node_modules
mkdir frontend/dist
mkdir patch-db/client/node_modules
mkdir patch-db/client/dist
- name: 'Extract frontend'
run: |
tar -mxvf frontend.tar frontend/config.json
tar -mxvf frontend.tar frontend/dist
- name: Cache raspiOS
id: cache-raspios
uses: actions/cache@v3
with:
path: raspios.img
key: cache-raspios
- name: Build image
run: "make V=1 NO_KEY=1 eos.img --debug"
- name: Compress image
run: "gzip eos.img"
- uses: actions/upload-artifact@v3
with:
name: image
path: eos.img.gz

7
.gitignore vendored
View File

@@ -8,3 +8,10 @@
/product_key.txt /product_key.txt
/*_product_key.txt /*_product_key.txt
.vscode/settings.json .vscode/settings.json
deploy_web.sh
deploy_web.sh
secrets.db
.vscode/
/cargo-deps/**/*
ENVIRONMENT.txt
GIT_HASH.txt

3
.gitmodules vendored
View File

@@ -1,6 +1,3 @@
[submodule "rpc-toolkit"]
path = rpc-toolkit
url = https://github.com/Start9Labs/rpc-toolkit.git
[submodule "patch-db"] [submodule "patch-db"]
path = patch-db path = patch-db
url = https://github.com/Start9Labs/patch-db.git url = https://github.com/Start9Labs/patch-db.git

View File

@@ -19,6 +19,7 @@ All types of contributions are encouraged and valued. See the [Table of Contents
- [I Want To Contribute](#i-want-to-contribute) - [I Want To Contribute](#i-want-to-contribute)
- [Reporting Bugs](#reporting-bugs) - [Reporting Bugs](#reporting-bugs)
- [Suggesting Enhancements](#suggesting-enhancements) - [Suggesting Enhancements](#suggesting-enhancements)
- [Project Structure](#project-structure)
- [Your First Code Contribution](#your-first-code-contribution) - [Your First Code Contribution](#your-first-code-contribution)
- [Setting Up Your Development Environment](#setting-up-your-development-environment) - [Setting Up Your Development Environment](#setting-up-your-development-environment)
- [Building The Image](#building-the-image) - [Building The Image](#building-the-image)
@@ -134,22 +135,24 @@ Enhancement suggestions are tracked as [GitHub issues](https://github.com/Start9
<!-- You might want to create an issue template for enhancement suggestions that can be used as a guide and that defines the structure of the information to be included. If you do so, reference it here in the description. --> <!-- You might want to create an issue template for enhancement suggestions that can be used as a guide and that defines the structure of the information to be included. If you do so, reference it here in the description. -->
### Project Structure ### Project Structure
EmbassyOS is composed of the following components. Please visit the README for each component to understand the dependency requirements and installation instructions. EmbassyOS is composed of the following components. Please visit the README for each component to understand the dependency requirements and installation instructions.
- [`ui`](ui/README.md) (Typescript Ionic Angular) is the code that is deployed to the browser to provide the user interface for EmbassyOS. - [`ui`](frontend/README.md) (Typescript Ionic Angular) is the code that is deployed to the browser to provide the user interface for EmbassyOS.
- [`backend`] (backend/README.md) (Rust) is a command line utility, daemon, and software development kit that sets up and manages services and their environments, provides the interface for the ui, manages system state, and provides utilities for packaging services for EmbassyOS. - [`backend`](backend/README.md) (Rust) is a command line utility, daemon, and software development kit that sets up and manages services and their environments, provides the interface for the ui, manages system state, and provides utilities for packaging services for EmbassyOS.
- `patch-db` - A diff based data store that is used to synchronize data between the front and backend. - `patch-db` - A diff based data store that is used to synchronize data between the front and backend.
- Notably, `patch-db` has a [client](patch-db/client/README.md) with its own dependency and installation requirements. - Notably, `patch-db` has a [client](https://github.com/Start9Labs/patch-db/tree/master/client) with its own dependency and installation requirements.
- `rpc-toolkit` - A library for generating an rpc server with cli bindings from Rust functions. - `rpc-toolkit` - A library for generating an rpc server with cli bindings from Rust functions.
- `system-images` - (Docker, Rust) A suite of utility Docker images that are preloaded with EmbassyOS to assist with functions relating to services (eg. configuration, backups, health checks). - `system-images` - (Docker, Rust) A suite of utility Docker images that are preloaded with EmbassyOS to assist with functions relating to services (eg. configuration, backups, health checks).
- [`setup-wizard`] (ui/README.md)- Code for the user interface that is displayed during the setup and recovery process for EmbassyOS. - [`setup-wizard`](frontend/README.md)- Code for the user interface that is displayed during the setup and recovery process for EmbassyOS.
- [`diagnostic-ui`] (diagnostic-ui/README.md) - Code for the user interface that is displayed when something has gone wrong with starting up EmbassyOS, which provides helpful debugging tools. - [`diagnostic-ui`](frontend/README.md) - Code for the user interface that is displayed when something has gone wrong with starting up EmbassyOS, which provides helpful debugging tools.
### Your First Code Contribution ### Your First Code Contribution
#### Setting up your development environment #### Setting Up Your Development Environment
First, clone the EmbassyOS repository and from the project root, pull in the submodules for dependent libraries. First, clone the EmbassyOS repository and from the project root, pull in the submodules for dependent libraries.
``` ```sh
git clone https://github.com/Start9Labs/embassy-os.git git clone https://github.com/Start9Labs/embassy-os.git
git submodule update --init --recursive git submodule update --init --recursive
``` ```
@@ -188,7 +191,7 @@ The body of a pull request should contain sufficient description of what the cha
You should include references to any relevant [issues](https://github.com/Start9Labs/embassy-os/issues). You should include references to any relevant [issues](https://github.com/Start9Labs/embassy-os/issues).
### Rebasing Changes ### Rebasing Changes
When a pull request conflicts with the target branch, you may be asked to rebase it on top of the current target branch. The git rebase command will take care of rebuilding your commits on top of the new base. When a pull request conflicts with the target branch, you may be asked to rebase it on top of the current target branch. The `git rebase` command will take care of rebuilding your commits on top of the new base.
This project aims to have a clean git history, where code changes are only made in non-merge commits. This simplifies auditability because merge commits can be assumed to not contain arbitrary code changes. This project aims to have a clean git history, where code changes are only made in non-merge commits. This simplifies auditability because merge commits can be assumed to not contain arbitrary code changes.

View File

@@ -1,13 +1,17 @@
ENVIRONMENT_FILE := $(shell ./check-environment.sh)
GIT_HASH_FILE := $(shell ./check-git-hash.sh)
EMBASSY_BINS := backend/target/aarch64-unknown-linux-gnu/release/embassyd backend/target/aarch64-unknown-linux-gnu/release/embassy-init backend/target/aarch64-unknown-linux-gnu/release/embassy-cli backend/target/aarch64-unknown-linux-gnu/release/embassy-sdk EMBASSY_BINS := backend/target/aarch64-unknown-linux-gnu/release/embassyd backend/target/aarch64-unknown-linux-gnu/release/embassy-init backend/target/aarch64-unknown-linux-gnu/release/embassy-cli backend/target/aarch64-unknown-linux-gnu/release/embassy-sdk
EMBASSY_UIS := frontend/dist/ui frontend/dist/setup-wizard frontend/dist/diagnostic-ui EMBASSY_UIS := frontend/dist/ui frontend/dist/setup-wizard frontend/dist/diagnostic-ui
EMBASSY_SRC := raspios.img product_key.txt $(EMBASSY_BINS) backend/embassyd.service backend/embassy-init.service $(EMBASSY_UIS) $(shell find build) EMBASSY_SRC := raspios.img product_key.txt $(EMBASSY_BINS) backend/embassyd.service backend/embassy-init.service $(EMBASSY_UIS) $(shell find build)
COMPAT_SRC := $(shell find system-images/compat/src) COMPAT_SRC := $(shell find system-images/compat/src)
UTILS_SRC := $(shell find system-images/utils/Dockerfile) UTILS_SRC := $(shell find system-images/utils/Dockerfile)
BACKEND_SRC := $(shell find backend/src) $(shell find patch-db/*/src) $(shell find rpc-toolkit/*/src) backend/Cargo.toml backend/Cargo.lock BACKEND_SRC := $(shell find backend/src) $(shell find patch-db/*/src) backend/Cargo.toml backend/Cargo.lock
FRONTEND_SRC := $(shell find frontend/projects) $(shell find frontend/assets) FRONTEND_SHARED_SRC := $(shell find frontend/projects/shared) $(shell find frontend/assets) $(shell ls -p frontend/ | grep -v / | sed 's/^/frontend\//g') frontend/node_modules frontend/config.json patch-db/client/dist
PATCH_DB_CLIENT_SRC = $(shell find patch-db/client -not -path patch-db/client/dist) FRONTEND_UI_SRC := $(shell find frontend/projects/ui)
GIT_REFS := $(shell find .git/refs/heads) FRONTEND_SETUP_WIZARD_SRC := $(shell find frontend/projects/setup-wizard)
TMP_FILE := $(shell mktemp) FRONTEND_DIAGNOSTIC_UI_SRC := $(shell find frontend/projects/diagnostic-ui)
PATCH_DB_CLIENT_SRC := $(shell find patch-db/client -not -path patch-db/client/dist)
$(shell sudo true)
.DELETE_ON_ERROR: .DELETE_ON_ERROR:
@@ -27,8 +31,12 @@ clean:
rm -rf frontend/dist rm -rf frontend/dist
rm -rf patch-db/client/node_modules rm -rf patch-db/client/node_modules
rm -rf patch-db/client/dist rm -rf patch-db/client/dist
sudo rm -rf cargo-deps
eos.img: $(EMBASSY_SRC) system-images/compat/compat.tar system-images/utils/utils.tar sdk:
cd backend/ && ./install-sdk.sh
eos.img: $(EMBASSY_SRC) system-images/compat/compat.tar system-images/utils/utils.tar cargo-deps/aarch64-unknown-linux-gnu/release/nc-broadcast $(ENVIRONMENT_FILE) $(GIT_HASH_FILE)
! test -f eos.img || rm eos.img ! test -f eos.img || rm eos.img
if [ "$(NO_KEY)" = "1" ]; then NO_KEY=1 ./build/make-image.sh; else ./build/make-image.sh; fi if [ "$(NO_KEY)" = "1" ]; then NO_KEY=1 ./build/make-image.sh; else ./build/make-image.sh; fi
@@ -50,25 +58,46 @@ product_key.txt:
if [ "$(KEY)" != "" ]; then $(shell which echo) -n "$(KEY)" > product_key.txt; fi if [ "$(KEY)" != "" ]; then $(shell which echo) -n "$(KEY)" > product_key.txt; fi
echo >> product_key.txt echo >> product_key.txt
$(EMBASSY_BINS): $(BACKEND_SRC) snapshots: libs/snapshot-creator/Cargo.toml
cd libs/ && ./build-v8-snapshot.sh
cd libs/ && ./build-arm-v8-snapshot.sh
$(EMBASSY_BINS): $(BACKEND_SRC) $(ENVIRONMENT_FILE) $(GIT_HASH_FILE)
cd backend && ./build-prod.sh cd backend && ./build-prod.sh
touch $(EMBASSY_BINS)
frontend/node_modules: frontend/package.json frontend/node_modules: frontend/package.json
npm --prefix frontend ci npm --prefix frontend ci
$(EMBASSY_UIS): $(FRONTEND_SRC) frontend/node_modules patch-db/client patch-db/client/dist frontend/config.json frontend/dist/ui: $(FRONTEND_UI_SRC) $(FRONTEND_SHARED_SRC) $(ENVIRONMENT_FILE)
npm --prefix frontend run build:all npm --prefix frontend run build:ui
frontend/config.json: .git/HEAD $(GIT_REFS) frontend/dist/setup-wizard: $(FRONTEND_SETUP_WIZARD_SRC) $(FRONTEND_SHARED_SRC) $(ENVIRONMENT_FILE)
npm --prefix frontend run build:setup-wizard
frontend/dist/diagnostic-ui: $(FRONTEND_DIAGNOSTIC_UI_SRC) $(FRONTEND_SHARED_SRC) $(ENVIRONMENT_FILE)
npm --prefix frontend run build:diagnostic-ui
frontend/config.json: $(GIT_HASH_FILE) frontend/config-sample.json
jq '.useMocks = false' frontend/config-sample.json > frontend/config.json jq '.useMocks = false' frontend/config-sample.json > frontend/config.json
npm --prefix frontend run-script build-config npm --prefix frontend run-script build-config
patch-db/client/node_modules: patch-db/client/package.json patch-db/client/node_modules: patch-db/client/package.json
npm --prefix patch-db/client install npm --prefix patch-db/client ci
patch-db/client/dist: $(PATCH_DB_CLIENT_SRC) patch-db/client/node_modules patch-db/client/dist: $(PATCH_DB_CLIENT_SRC) patch-db/client/node_modules
! test -d patch-db/client/dist || rm -rf patch-db/client/dist ! test -d patch-db/client/dist || rm -rf patch-db/client/dist
rm -rf frontend/.angular/cache
npm --prefix patch-db/client run build npm --prefix patch-db/client run build
# this is a convenience step to build all frontends - it is not referenced elsewhere in this file # this is a convenience step to build all frontends - it is not referenced elsewhere in this file
frontend: frontend/node_modules $(EMBASSY_UIS) frontends: $(EMBASSY_UIS)
# this is a convenience step to build the UI
ui: frontend/dist/ui
# this is a convenience step to build the backend
backend: $(EMBASSY_BINS)
cargo-deps/aarch64-unknown-linux-gnu/release/nc-broadcast:
./build-cargo-dep.sh nc-broadcast

2479
backend/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -14,7 +14,7 @@ keywords = [
name = "embassy-os" name = "embassy-os"
readme = "README.md" readme = "README.md"
repository = "https://github.com/Start9Labs/embassy-os" repository = "https://github.com/Start9Labs/embassy-os"
version = "0.3.0-rev.3" version = "0.3.1-rev.1"
[lib] [lib]
name = "embassy" name = "embassy"
@@ -38,102 +38,109 @@ path = "src/bin/embassy-cli.rs"
[features] [features]
avahi = ["avahi-sys"] avahi = ["avahi-sys"]
beta = [] default = ["avahi", "sound", "metal", "js_engine"]
default = ["avahi", "sound", "metal"] dev = []
metal = [] metal = []
sound = [] sound = []
unstable = ["patch-db/unstable"] unstable = ["patch-db/unstable"]
[dependencies] [dependencies]
aes = { version = "0.7.5", features = ["ctr"] } aes = { version = "0.7.5", features = ["ctr"] }
async-trait = "0.1.51" async-stream = "0.3.3"
async-trait = "0.1.56"
avahi-sys = { git = "https://github.com/Start9Labs/avahi-sys", version = "0.10.0", branch = "feature/dynamic-linking", features = [ avahi-sys = { git = "https://github.com/Start9Labs/avahi-sys", version = "0.10.0", branch = "feature/dynamic-linking", features = [
"dynamic", "dynamic",
], optional = true } ], optional = true }
base32 = "0.4.0" base32 = "0.4.0"
base64 = "0.13.0" base64 = "0.13.0"
base64ct = "1.5.1"
basic-cookies = "0.1.4" basic-cookies = "0.1.4"
bollard = "0.11.0" bollard = "0.13.0"
chrono = { version = "0.4.19", features = ["serde"] } chrono = { version = "0.4.19", features = ["serde"] }
clap = "2.33" clap = "3.2.8"
color-eyre = "0.5" color-eyre = "0.6.1"
cookie_store = "0.15.0" cookie_store = "0.16.1"
digest = "0.9.0" current_platform = "0.2.0"
digest = "0.10.3"
digest-old = { package = "digest", version = "0.9.0" }
divrem = "1.0.0" divrem = "1.0.0"
ed25519 = { version = "1.5.2", features = ["pkcs8", "pem", "alloc"] }
ed25519-dalek = { version = "1.0.1", features = ["serde"] } ed25519-dalek = { version = "1.0.1", features = ["serde"] }
emver = { version = "0.1.6", features = ["serde"] } emver = { version = "0.1.6", features = ["serde"] }
fd-lock-rs = "0.1.3" fd-lock-rs = "0.1.4"
futures = "0.3.17" futures = "0.3.21"
git-version = "0.3.5" git-version = "0.3.5"
helpers = { path = "../libs/helpers" }
hex = "0.4.3" hex = "0.4.3"
hmac = "0.11.0" hmac = "0.12.1"
http = "0.2.5" http = "0.2.8"
hyper = "0.14.13" hyper = "0.14.20"
hyper-ws-listener = { git = "https://github.com/Start9Labs/hyper-ws-listener.git", branch = "main" } hyper-ws-listener = "0.2.0"
imbl = "1.0.1" imbl = "2.0.0"
indexmap = { version = "1.7.0", features = ["serde"] } indexmap = { version = "1.9.1", features = ["serde"] }
isocountry = "0.3.2" isocountry = "0.3.2"
itertools = "0.10.1" itertools = "0.10.3"
js_engine = { path = '../libs/js_engine', optional = true }
jsonpath_lib = "0.3.0" jsonpath_lib = "0.3.0"
lazy_static = "1.4" lazy_static = "1.4.0"
libc = "0.2.103" libc = "0.2.126"
log = "0.4.14" log = "0.4.17"
nix = "0.23.0" models = { version = "*", path = "../libs/models" }
nom = "7.0.0" nix = "0.24.1"
nom = "7.1.1"
num = "0.4.0" num = "0.4.0"
num_enum = "0.5.4" num_enum = "0.5.7"
openssh-keys = "0.5.0" openssh-keys = "0.5.0"
openssl = { version = "0.10.36", features = ["vendored"] } openssl = { version = "0.10.41", features = ["vendored"] }
patch-db = { version = "*", path = "../patch-db/patch-db", features = [ patch-db = { version = "*", path = "../patch-db/patch-db", features = [
"trace", "trace",
] } ] }
pbkdf2 = "0.9.0" pbkdf2 = "0.11.0"
pin-project = "1.0.8" pin-project = "1.0.11"
platforms = "1.1.0" pkcs8 = { version = "0.9.0", features = ["std"] }
prettytable-rs = "0.8.0" prettytable-rs = "0.8.0"
proptest = "1.0.0" proptest = "1.0.0"
proptest-derive = "0.3.0" proptest-derive = "0.3.0"
rand = "0.7.3" rand = { version = "0.8.5", features = ["std"] }
regex = "1.5.4" rand-old = { package = "rand", version = "0.7.3" }
reqwest = { version = "0.11.4", features = ["stream", "json", "socks"] } regex = "1.6.0"
reqwest_cookie_store = "0.2.0" reqwest = { version = "0.11.11", features = ["stream", "json", "socks"] }
rpassword = "5.0.1" reqwest_cookie_store = "0.3.0"
rpc-toolkit = { version = "*", path = "../rpc-toolkit/rpc-toolkit" } rpassword = "6.0.1"
rust-argon2 = "0.8.3" rpc-toolkit = "0.2.0"
rust-argon2 = "1.0.0"
scopeguard = "1.1" # because avahi-sys fucks your shit up scopeguard = "1.1" # because avahi-sys fucks your shit up
serde = { version = "1.0.130", features = ["derive", "rc"] } serde = { version = "1.0.139", features = ["derive", "rc"] }
serde_cbor = { package = "ciborium", version = "0.2.0" } serde_cbor = { package = "ciborium", version = "0.2.0" }
serde_json = "1.0.68" serde_json = "1.0.82"
serde_toml = { package = "toml", version = "0.5.8" } serde_toml = { package = "toml", version = "0.5.9" }
serde_yaml = "0.8.21" serde_with = { version = "1.14.0", features = ["macros", "json"] }
sha2 = "0.9.8" serde_yaml = "0.8.25"
simple-logging = "2.0" sha2 = "0.10.2"
sqlx = { version = "0.5.11", features = [ sha2-old = { package = "sha2", version = "0.9.9" }
simple-logging = "2.0.2"
sqlx = { version = "0.6.0", features = [
"chrono", "chrono",
"offline", "offline",
"runtime-tokio-rustls", "runtime-tokio-rustls",
"sqlite", "sqlite",
] } ] }
stderrlog = "0.5.1" stderrlog = "0.5.3"
tar = "0.4.37" tar = "0.4.38"
thiserror = "1.0.29" thiserror = "1.0.31"
tokio = { version = "1.15.0", features = ["full"] } tokio = { version = "1.19.2", features = ["full"] }
tokio-compat-02 = "0.2.0" tokio-stream = { version = "0.1.9", features = ["io-util", "sync"] }
tokio-stream = { version = "0.1.7", features = ["io-util", "sync"] }
tokio-tar = { git = "https://github.com/dr-bonez/tokio-tar.git" } tokio-tar = { git = "https://github.com/dr-bonez/tokio-tar.git" }
tokio-tungstenite = "0.14.0" tokio-tungstenite = "0.17.1"
tokio-util = { version = "0.6.8", features = ["io"] } tokio-util = { version = "0.7.3", features = ["io"] }
torut = "0.2.0" torut = "0.2.1"
tracing = "0.1" tracing = "0.1.35"
tracing-error = "0.1" tracing-error = "0.2.0"
tracing-futures = "0.2" tracing-futures = "0.2.5"
tracing-subscriber = "0.2" tracing-subscriber = { version = "0.3.14", features = ["env-filter"] }
typed-builder = "0.9.1" trust-dns-server = "0.21.2"
typed-builder = "0.10.0"
url = { version = "2.2.2", features = ["serde"] } url = { version = "2.2.2", features = ["serde"] }
[dependencies.serde_with]
features = ["macros", "json"]
version = "1.10.0"
[profile.dev.package.backtrace] [profile.dev.package.backtrace]
opt-level = 3 opt-level = 3

View File

@@ -8,9 +8,17 @@ if [ "$0" != "./build-dev.sh" ]; then
exit 1 exit 1
fi fi
alias 'rust-arm64-builder'='docker run --rm -it -v "$HOME/.cargo/registry":/root/.cargo/registry -v "$(pwd)":/home/rust/src start9/rust-arm-cross:aarch64' USE_TTY=
if tty -s; then
USE_TTY="-it"
fi
alias 'rust-arm64-builder'='docker run $USE_TTY --rm -v "$HOME/.cargo/registry":/root/.cargo/registry -v "$(pwd)":/home/rust/src start9/rust-arm-cross:aarch64'
cd .. cd ..
rust-arm64-builder sh -c "(cd backend && cargo build)" rust-arm64-builder sh -c "(cd backend && cargo build)"
cd backend cd backend
sudo chown -R $USER target
sudo chown -R $USER ~/.cargo
#rust-arm64-builder aarch64-linux-gnu-strip target/aarch64-unknown-linux-gnu/release/embassyd #rust-arm64-builder aarch64-linux-gnu-strip target/aarch64-unknown-linux-gnu/release/embassyd

View File

@@ -8,8 +8,16 @@ if [ "$0" != "./build-portable-dev.sh" ]; then
exit 1 exit 1
fi fi
alias 'rust-musl-builder'='docker run --rm -it -v "$HOME"/.cargo/registry:/root/.cargo/registry -v "$(pwd)":/home/rust/src start9/rust-musl-cross:x86_64-musl' USE_TTY=
if tty -s; then
USE_TTY="-it"
fi
alias 'rust-musl-builder'='docker run $USE_TTY --rm -v "$HOME"/.cargo/registry:/root/.cargo/registry -v "$(pwd)":/home/rust/src start9/rust-musl-cross:x86_64-musl'
cd .. cd ..
rust-musl-builder sh -c "(cd backend && cargo +beta build --target=x86_64-unknown-linux-musl --no-default-features)" rust-musl-builder sh -c "(cd backend && cargo +beta build --target=x86_64-unknown-linux-musl --no-default-features)"
cd backend cd backend
sudo chown -R $USER target
sudo chown -R $USER ~/.cargo

View File

@@ -8,8 +8,16 @@ if [ "$0" != "./build-portable.sh" ]; then
exit 1 exit 1
fi fi
alias 'rust-musl-builder'='docker run --rm -it -v "$HOME"/.cargo/registry:/root/.cargo/registry -v "$(pwd)":/home/rust/src start9/rust-musl-cross:x86_64-musl' USE_TTY=
if tty -s; then
USE_TTY="-it"
fi
alias 'rust-musl-builder'='docker run $USE_TTY --rm -v "$HOME"/.cargo/registry:/root/.cargo/registry -v "$(pwd)":/home/rust/src start9/rust-musl-cross:x86_64-musl'
cd .. cd ..
rust-musl-builder sh -c "(cd backend && cargo +beta build --release --target=x86_64-unknown-linux-musl --no-default-features)" rust-musl-builder sh -c "(cd backend && cargo +beta build --release --target=x86_64-unknown-linux-musl --no-default-features)"
cd backend cd backend
sudo chown -R $USER target
sudo chown -R $USER ~/.cargo

View File

@@ -8,21 +8,30 @@ if [ "$0" != "./build-prod.sh" ]; then
exit 1 exit 1
fi fi
alias 'rust-arm64-builder'='docker run --rm -it -v "$HOME/.cargo/registry":/root/.cargo/registry -v "$(pwd)":/home/rust/src start9/rust-arm-cross:aarch64' USE_TTY=
if tty -s; then
USE_TTY="-it"
fi
alias 'rust-arm64-builder'='docker run $USE_TTY --rm -v "$HOME/.cargo/registry":/root/.cargo/registry -v "$(pwd)":/home/rust/src -P start9/rust-arm-cross:aarch64'
cd .. cd ..
FLAGS=""
if [[ "$ENVIRONMENT" =~ (^|-)unstable($|-) ]]; then if [[ "$ENVIRONMENT" =~ (^|-)unstable($|-) ]]; then
if [[ "$ENVIRONMENT" =~ (^|-)beta($|-) ]]; then FLAGS="unstable,$FLAGS"
rust-arm64-builder sh -c "(cd backend && cargo build --release --features beta,unstable)" fi
else if [[ "$ENVIRONMENT" =~ (^|-)dev($|-) ]]; then
rust-arm64-builder sh -c "(cd backend && cargo build --release --features unstable)" FLAGS="dev,$FLAGS"
fi fi
if [[ "$FLAGS" = "" ]]; then
rust-arm64-builder sh -c "(git config --global --add safe.directory '*'; cd backend && cargo build --release)"
else else
if [[ "$ENVIRONMENT" =~ (^|-)beta($|-) ]]; then echo "FLAGS=$FLAGS"
rust-arm64-builder sh -c "(cd backend && cargo build --release --features beta)" rust-arm64-builder sh -c "(git config --global --add safe.directory '*'; cd backend && cargo build --release --features $FLAGS)"
else
rust-arm64-builder sh -c "(cd backend && cargo build --release)"
fi
fi fi
cd backend cd backend
sudo chown -R $USER target
sudo chown -R $USER ~/.cargo
#rust-arm64-builder aarch64-linux-gnu-strip target/aarch64-unknown-linux-gnu/release/embassyd #rust-arm64-builder aarch64-linux-gnu-strip target/aarch64-unknown-linux-gnu/release/embassyd

View File

@@ -1,12 +0,0 @@
#!/bin/bash
# Enter the backend directory, copy over the built EmbassyOS binaries and systemd services, edit the nginx config, then create the .ssh directory
cp target/aarch64-unknown-linux-gnu/release/embassy-init /mnt/usr/local/bin
cp target/aarch64-unknown-linux-gnu/release/embassyd /mnt/usr/local/bin
cp target/aarch64-unknown-linux-gnu/release/embassy-cli /mnt/usr/local/bin
cp *.service /mnt/etc/systemd/system/
echo "application/wasm wasm;" | sudo tee -a "/mnt/etc/nginx/mime.types"
mkdir -p /mnt/root/.ssh

View File

@@ -6,9 +6,11 @@ Wants=avahi-daemon.service nginx.service tor.service
[Service] [Service]
Type=oneshot Type=oneshot
Environment=RUST_LOG=embassy_init=debug,embassy=debug Environment=RUST_LOG=embassy_init=debug,embassy=debug,js_engine=debug
ExecStart=/usr/local/bin/embassy-init ExecStart=/usr/local/bin/embassy-init
RemainAfterExit=true RemainAfterExit=true
StandardOutput=file:/var/log/embassy-init.out.log
StandardError=file:/var/log/embassy-init.error.log
[Install] [Install]
WantedBy=embassyd.service WantedBy=embassyd.service

View File

@@ -5,7 +5,7 @@ Requires=embassy-init.service
[Service] [Service]
Type=simple Type=simple
Environment=RUST_LOG=embassyd=debug,embassy=debug Environment=RUST_LOG=embassyd=debug,embassy=debug,js_engine=debug
ExecStart=/usr/local/bin/embassyd ExecStart=/usr/local/bin/embassyd
Restart=always Restart=always
RestartSec=3 RestartSec=3

View File

@@ -8,4 +8,4 @@ if [ "$0" != "./install-sdk.sh" ]; then
exit 1 exit 1
fi fi
cargo install --bin=embassy-sdk --path=. --no-default-features cargo install --bin=embassy-sdk --bin=embassy-cli --path=. --no-default-features --features=js_engine

View File

@@ -1,47 +1,46 @@
{ {
"db": "SQLite", "db": "SQLite",
"10350f5a16f1b2a6ce91672ae5dc6acc46691bd8f901861545ec83c326a8ccef": { "10350f5a16f1b2a6ce91672ae5dc6acc46691bd8f901861545ec83c326a8ccef": {
"query": "INSERT INTO ssh_keys (fingerprint, openssh_pubkey, created_at) VALUES (?, ?, ?)",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 3 "Right": 3
}, }
"nullable": [] },
} "query": "INSERT INTO ssh_keys (fingerprint, openssh_pubkey, created_at) VALUES (?, ?, ?)"
}, },
"118d59de5cf930d5a3b5667b2220e9a3d593bd84276beb2b76c93b2694b0fd72": { "118d59de5cf930d5a3b5667b2220e9a3d593bd84276beb2b76c93b2694b0fd72": {
"query": "INSERT INTO session (id, user_agent, metadata) VALUES (?, ?, ?)",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 3 "Right": 3
}, }
"nullable": [] },
} "query": "INSERT INTO session (id, user_agent, metadata) VALUES (?, ?, ?)"
}, },
"165daa7d6a60cb42122373b2c5ac7d39399bcc99992f0002ee7bfef50a8daceb": { "165daa7d6a60cb42122373b2c5ac7d39399bcc99992f0002ee7bfef50a8daceb": {
"query": "DELETE FROM certificates WHERE id = 0 OR id = 1;",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 0 "Right": 0
}, }
"nullable": [] },
} "query": "DELETE FROM certificates WHERE id = 0 OR id = 1;"
}, },
"177c4b9cc7901a3b906e5969b86b1c11e6acbfb8e86e98f197d7333030b17964": { "177c4b9cc7901a3b906e5969b86b1c11e6acbfb8e86e98f197d7333030b17964": {
"query": "DELETE FROM notifications WHERE id = ?",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 1 "Right": 1
}, }
"nullable": [] },
} "query": "DELETE FROM notifications WHERE id = ?"
}, },
"1b2242afa55e730b37b00929b656d80940b457ec86c234ddd0de917bd8872611": { "1b2242afa55e730b37b00929b656d80940b457ec86c234ddd0de917bd8872611": {
"query": "INSERT INTO cifs_shares (hostname, path, username, password) VALUES (?, ?, ?, ?) RETURNING id AS \"id: u32\"",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -50,36 +49,36 @@
"type_info": "Int64" "type_info": "Int64"
} }
], ],
"parameters": {
"Right": 4
},
"nullable": [ "nullable": [
false false
] ],
} "parameters": {
"Right": 4
}
},
"query": "INSERT INTO cifs_shares (hostname, path, username, password) VALUES (?, ?, ?, ?) RETURNING id AS \"id: u32\""
}, },
"1eee1fdc793919c391008854407143d7a11b4668486c11a760b49af49992f9f8": { "1eee1fdc793919c391008854407143d7a11b4668486c11a760b49af49992f9f8": {
"query": "REPLACE INTO tor (package, interface, key) VALUES (?, 'main', ?)",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 2 "Right": 2
}, }
"nullable": [] },
} "query": "REPLACE INTO tor (package, interface, key) VALUES (?, 'main', ?)"
}, },
"2932aa02735b6422fca4ba889abfb3de8598178d4690076dc278898753d9df62": { "2932aa02735b6422fca4ba889abfb3de8598178d4690076dc278898753d9df62": {
"query": "UPDATE session SET logged_out = CURRENT_TIMESTAMP WHERE id = ?",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 1 "Right": 1
}, }
"nullable": [] },
} "query": "UPDATE session SET logged_out = CURRENT_TIMESTAMP WHERE id = ?"
}, },
"3502e58f2ab48fb4566d21c920c096f81acfa3ff0d02f970626a4dcd67bac71d": { "3502e58f2ab48fb4566d21c920c096f81acfa3ff0d02f970626a4dcd67bac71d": {
"query": "SELECT tor_key FROM account",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -88,16 +87,16 @@
"type_info": "Blob" "type_info": "Blob"
} }
], ],
"parameters": {
"Right": 0
},
"nullable": [ "nullable": [
false false
] ],
} "parameters": {
"Right": 0
}
},
"query": "SELECT tor_key FROM account"
}, },
"3e57a0e52b69f33e9411c13b03a5d82c5856d63f0375eb4c23b255a09c54f8b1": { "3e57a0e52b69f33e9411c13b03a5d82c5856d63f0375eb4c23b255a09c54f8b1": {
"query": "SELECT key FROM tor WHERE package = ? AND interface = ?",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -106,16 +105,16 @@
"type_info": "Blob" "type_info": "Blob"
} }
], ],
"parameters": {
"Right": 2
},
"nullable": [ "nullable": [
false false
] ],
} "parameters": {
"Right": 2
}
},
"query": "SELECT key FROM tor WHERE package = ? AND interface = ?"
}, },
"4691e3a2ce80b59009ac17124f54f925f61dc5ea371903e62cdffa5d7b67ca96": { "4691e3a2ce80b59009ac17124f54f925f61dc5ea371903e62cdffa5d7b67ca96": {
"query": "SELECT * FROM session WHERE logged_out IS NULL OR logged_out > CURRENT_TIMESTAMP",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -149,9 +148,6 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 0
},
"nullable": [ "nullable": [
false, false,
false, false,
@@ -159,51 +155,54 @@
false, false,
true, true,
false false
] ],
} "parameters": {
"Right": 0
}
},
"query": "SELECT * FROM session WHERE logged_out IS NULL OR logged_out > CURRENT_TIMESTAMP"
}, },
"530192a2a530ee6b92e5b98e1eb1bf6d1426c7b0cb2578593a367cb0bf2c3ca8": { "530192a2a530ee6b92e5b98e1eb1bf6d1426c7b0cb2578593a367cb0bf2c3ca8": {
"query": "UPDATE certificates SET priv_key_pem = ?, certificate_pem = ?, updated_at = datetime('now') WHERE lookup_string = ?",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 3 "Right": 3
}, }
"nullable": [] },
} "query": "UPDATE certificates SET priv_key_pem = ?, certificate_pem = ?, updated_at = datetime('now') WHERE lookup_string = ?"
}, },
"56b986f2a2b7091d9c3acdd78f75d9842242de1f4da8f3672f2793d9fb256928": { "56b986f2a2b7091d9c3acdd78f75d9842242de1f4da8f3672f2793d9fb256928": {
"query": "DELETE FROM tor WHERE package = ?",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 1 "Right": 1
}, }
"nullable": [] },
} "query": "DELETE FROM tor WHERE package = ?"
}, },
"5b114c450073f77f466c980a2541293f30087b57301c379630326e5e5c2fb792": { "5b114c450073f77f466c980a2541293f30087b57301c379630326e5e5c2fb792": {
"query": "REPLACE INTO tor (package, interface, key) VALUES (?, ?, ?)",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 3 "Right": 3
}, }
"nullable": [] },
} "query": "REPLACE INTO tor (package, interface, key) VALUES (?, ?, ?)"
}, },
"5c47da44b9c84468e95a13fc47301989900f130b3b5899d1ee6664df3ed812ac": { "5c47da44b9c84468e95a13fc47301989900f130b3b5899d1ee6664df3ed812ac": {
"query": "INSERT INTO certificates (id, priv_key_pem, certificate_pem, lookup_string, created_at, updated_at) VALUES (0, ?, ?, NULL, datetime('now'), datetime('now'))",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 2 "Right": 2
}, }
"nullable": [] },
} "query": "INSERT INTO certificates (id, priv_key_pem, certificate_pem, lookup_string, created_at, updated_at) VALUES (0, ?, ?, NULL, datetime('now'), datetime('now'))"
}, },
"629be61c3c341c131ddbbff0293a83dbc6afd07cae69d246987f62cf0cc35c2a": { "629be61c3c341c131ddbbff0293a83dbc6afd07cae69d246987f62cf0cc35c2a": {
"query": "SELECT password FROM account",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -212,36 +211,36 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 0
},
"nullable": [ "nullable": [
false false
] ],
} "parameters": {
"Right": 0
}
},
"query": "SELECT password FROM account"
}, },
"63785dc5f193ea31e6f641a910c75857ccd288a3f6e9c4f704331531e4f0689f": { "63785dc5f193ea31e6f641a910c75857ccd288a3f6e9c4f704331531e4f0689f": {
"query": "UPDATE session SET last_active = CURRENT_TIMESTAMP WHERE id = ? AND logged_out IS NULL OR logged_out > CURRENT_TIMESTAMP",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 1 "Right": 1
}, }
"nullable": [] },
} "query": "UPDATE session SET last_active = CURRENT_TIMESTAMP WHERE id = ? AND logged_out IS NULL OR logged_out > CURRENT_TIMESTAMP"
}, },
"6440354d73a67c041ea29508b43b5f309d45837a44f1a562051ad540d894c7d6": { "6440354d73a67c041ea29508b43b5f309d45837a44f1a562051ad540d894c7d6": {
"query": "DELETE FROM ssh_keys WHERE fingerprint = ?",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 1 "Right": 1
}, }
"nullable": [] },
} "query": "DELETE FROM ssh_keys WHERE fingerprint = ?"
}, },
"65e6c3fbb138da5cf385af096fdd3c062b6e826e12a8a4b23e16fcc773004c29": { "65e6c3fbb138da5cf385af096fdd3c062b6e826e12a8a4b23e16fcc773004c29": {
"query": "SELECT id, package_id, created_at, code, level, title, message, data FROM notifications WHERE id < ? ORDER BY id DESC LIMIT ?",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -285,9 +284,6 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 2
},
"nullable": [ "nullable": [
false, false,
true, true,
@@ -297,11 +293,14 @@
false, false,
false, false,
true true
] ],
} "parameters": {
"Right": 2
}
},
"query": "SELECT id, package_id, created_at, code, level, title, message, data FROM notifications WHERE id < ? ORDER BY id DESC LIMIT ?"
}, },
"668f39c868f90cdbcc635858bac9e55ed73192ed2aec5c52dcfba9800a7a4a41": { "668f39c868f90cdbcc635858bac9e55ed73192ed2aec5c52dcfba9800a7a4a41": {
"query": "SELECT id AS \"id: u32\", hostname, path, username, password FROM cifs_shares",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -330,30 +329,30 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 0
},
"nullable": [ "nullable": [
false, false,
false, false,
false, false,
false, false,
true true
] ],
} "parameters": {
"Right": 0
}
},
"query": "SELECT id AS \"id: u32\", hostname, path, username, password FROM cifs_shares"
}, },
"6b9abc9e079cff975f8a7f07ff70548c7877ecae3be0d0f2d3f439a6713326c0": { "6b9abc9e079cff975f8a7f07ff70548c7877ecae3be0d0f2d3f439a6713326c0": {
"query": "DELETE FROM notifications WHERE id < ?",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 1 "Right": 1
}, }
"nullable": [] },
} "query": "DELETE FROM notifications WHERE id < ?"
}, },
"6c96d76bffcc5f03290d8d8544a58521345ed2a843a509b17bbcd6257bb81821": { "6c96d76bffcc5f03290d8d8544a58521345ed2a843a509b17bbcd6257bb81821": {
"query": "SELECT priv_key_pem, certificate_pem FROM certificates WHERE id = 1;",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -367,27 +366,37 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 0
},
"nullable": [ "nullable": [
false, false,
false false
] ],
} "parameters": {
"Right": 0
}
},
"query": "SELECT priv_key_pem, certificate_pem FROM certificates WHERE id = 1;"
}, },
"7d548d2472fa3707bd17364b4800e229b9c2b1c0a22e245bf4e635b9b16b8c24": { "7d548d2472fa3707bd17364b4800e229b9c2b1c0a22e245bf4e635b9b16b8c24": {
"query": "INSERT INTO certificates (priv_key_pem, certificate_pem, lookup_string, created_at, updated_at) VALUES (?, ?, ?, datetime('now'), datetime('now'))",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 3 "Right": 3
}, }
"nullable": [] },
} "query": "INSERT INTO certificates (priv_key_pem, certificate_pem, lookup_string, created_at, updated_at) VALUES (?, ?, ?, datetime('now'), datetime('now'))"
},
"82a8fa7eae8a73b5345015c72af024b4f21489b1d9b42235398d7eb8977fb132": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Right": 1
}
},
"query": "UPDATE account SET password = ?"
}, },
"8595651866e7db772260bd79e19d55b7271fd795b82a99821c935a9237c1aa16": { "8595651866e7db772260bd79e19d55b7271fd795b82a99821c935a9237c1aa16": {
"query": "SELECT interface, key FROM tor WHERE package = ?",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -401,17 +410,17 @@
"type_info": "Blob" "type_info": "Blob"
} }
], ],
"parameters": {
"Right": 1
},
"nullable": [ "nullable": [
false, false,
false false
] ],
} "parameters": {
"Right": 1
}
},
"query": "SELECT interface, key FROM tor WHERE package = ?"
}, },
"9496e17a73672ac3675e02efa7c4bf8bd479b866c0d31fa1e3a85ef159310a57": { "9496e17a73672ac3675e02efa7c4bf8bd479b866c0d31fa1e3a85ef159310a57": {
"query": "SELECT priv_key_pem, certificate_pem FROM certificates WHERE lookup_string = ?",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -425,47 +434,47 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 1
},
"nullable": [ "nullable": [
false, false,
false false
] ],
} "parameters": {
"Right": 1
}
},
"query": "SELECT priv_key_pem, certificate_pem FROM certificates WHERE lookup_string = ?"
}, },
"9fcedab1ba34daa2c6ae97c5953c09821b35b55be75b0c66045ab31a2cf4553e": { "9fcedab1ba34daa2c6ae97c5953c09821b35b55be75b0c66045ab31a2cf4553e": {
"query": "REPLACE INTO account (id, password, tor_key) VALUES (?, ?, ?)",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 3 "Right": 3
}, }
"nullable": [] },
} "query": "REPLACE INTO account (id, password, tor_key) VALUES (?, ?, ?)"
}, },
"a1cbaac36d8e14c8c3e7276237c4824bff18861f91b0b08aa5791704c492acb7": { "a1cbaac36d8e14c8c3e7276237c4824bff18861f91b0b08aa5791704c492acb7": {
"query": "INSERT INTO certificates (id, priv_key_pem, certificate_pem, lookup_string, created_at, updated_at) VALUES (1, ?, ?, NULL, datetime('now'), datetime('now'))",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 2 "Right": 2
}, }
"nullable": [] },
} "query": "INSERT INTO certificates (id, priv_key_pem, certificate_pem, lookup_string, created_at, updated_at) VALUES (1, ?, ?, NULL, datetime('now'), datetime('now'))"
}, },
"a4e7162322b28508310b9de7ebc891e619b881ff6d3ea09eba13da39626ab12f": { "a4e7162322b28508310b9de7ebc891e619b881ff6d3ea09eba13da39626ab12f": {
"query": "UPDATE cifs_shares SET hostname = ?, path = ?, username = ?, password = ? WHERE id = ?",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 5 "Right": 5
}, }
"nullable": [] },
} "query": "UPDATE cifs_shares SET hostname = ?, path = ?, username = ?, password = ? WHERE id = ?"
}, },
"a6b0c8909a3a5d6d9156aebfb359424e6b5a1d1402e028219e21726f1ebd282e": { "a6b0c8909a3a5d6d9156aebfb359424e6b5a1d1402e028219e21726f1ebd282e": {
"query": "SELECT fingerprint, openssh_pubkey, created_at FROM ssh_keys",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -484,18 +493,18 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 0
},
"nullable": [ "nullable": [
false, false,
false, false,
false false
] ],
} "parameters": {
"Right": 0
}
},
"query": "SELECT fingerprint, openssh_pubkey, created_at FROM ssh_keys"
}, },
"abfdeea8cd10343b85f647d7abc5dc3bd0b5891101b143485938192ee3b8c907": { "abfdeea8cd10343b85f647d7abc5dc3bd0b5891101b143485938192ee3b8c907": {
"query": "SELECT id, package_id, created_at, code, level, title, message, data FROM notifications ORDER BY id DESC LIMIT ?",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -539,9 +548,6 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 1
},
"nullable": [ "nullable": [
false, false,
true, true,
@@ -551,21 +557,24 @@
false, false,
false, false,
true true
] ],
} "parameters": {
"Right": 1
}
},
"query": "SELECT id, package_id, created_at, code, level, title, message, data FROM notifications ORDER BY id DESC LIMIT ?"
}, },
"b376d9e77e0861a9af2d1081ca48d14e83abc5a1546213d15bb570972c403beb": { "b376d9e77e0861a9af2d1081ca48d14e83abc5a1546213d15bb570972c403beb": {
"query": "-- Add migration script here\nCREATE TABLE IF NOT EXISTS tor\n(\n package TEXT NOT NULL,\n interface TEXT NOT NULL,\n key BLOB NOT NULL CHECK (length(key) = 64),\n PRIMARY KEY (package, interface)\n);\nCREATE TABLE IF NOT EXISTS session\n(\n id TEXT NOT NULL PRIMARY KEY,\n logged_in TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n logged_out TIMESTAMP,\n last_active TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n user_agent TEXT,\n metadata TEXT NOT NULL DEFAULT 'null'\n);\nCREATE TABLE IF NOT EXISTS account\n(\n id INTEGER PRIMARY KEY CHECK (id = 0),\n password TEXT NOT NULL,\n tor_key BLOB NOT NULL CHECK (length(tor_key) = 64)\n);\nCREATE TABLE IF NOT EXISTS ssh_keys\n(\n fingerprint TEXT NOT NULL,\n openssh_pubkey TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (fingerprint)\n);\nCREATE TABLE IF NOT EXISTS certificates\n(\n id INTEGER PRIMARY KEY, -- Root = 0, Int = 1, Other = 2..\n priv_key_pem TEXT NOT NULL,\n certificate_pem TEXT NOT NULL,\n lookup_string TEXT UNIQUE,\n created_at TEXT,\n updated_at TEXT\n);\nCREATE TABLE IF NOT EXISTS notifications\n(\n id INTEGER PRIMARY KEY,\n package_id TEXT,\n created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n code INTEGER NOT NULL,\n level TEXT NOT NULL,\n title TEXT NOT NULL,\n message TEXT NOT NULL,\n data TEXT\n);\nCREATE TABLE IF NOT EXISTS cifs_shares\n(\n id INTEGER PRIMARY KEY,\n hostname TEXT NOT NULL,\n path TEXT NOT NULL,\n username TEXT NOT NULL,\n password TEXT\n);",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 0 "Right": 0
}, }
"nullable": [] },
} "query": "-- Add migration script here\nCREATE TABLE IF NOT EXISTS tor\n(\n package TEXT NOT NULL,\n interface TEXT NOT NULL,\n key BLOB NOT NULL CHECK (length(key) = 64),\n PRIMARY KEY (package, interface)\n);\nCREATE TABLE IF NOT EXISTS session\n(\n id TEXT NOT NULL PRIMARY KEY,\n logged_in TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n logged_out TIMESTAMP,\n last_active TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n user_agent TEXT,\n metadata TEXT NOT NULL DEFAULT 'null'\n);\nCREATE TABLE IF NOT EXISTS account\n(\n id INTEGER PRIMARY KEY CHECK (id = 0),\n password TEXT NOT NULL,\n tor_key BLOB NOT NULL CHECK (length(tor_key) = 64)\n);\nCREATE TABLE IF NOT EXISTS ssh_keys\n(\n fingerprint TEXT NOT NULL,\n openssh_pubkey TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (fingerprint)\n);\nCREATE TABLE IF NOT EXISTS certificates\n(\n id INTEGER PRIMARY KEY, -- Root = 0, Int = 1, Other = 2..\n priv_key_pem TEXT NOT NULL,\n certificate_pem TEXT NOT NULL,\n lookup_string TEXT UNIQUE,\n created_at TEXT,\n updated_at TEXT\n);\nCREATE TABLE IF NOT EXISTS notifications\n(\n id INTEGER PRIMARY KEY,\n package_id TEXT,\n created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n code INTEGER NOT NULL,\n level TEXT NOT NULL,\n title TEXT NOT NULL,\n message TEXT NOT NULL,\n data TEXT\n);\nCREATE TABLE IF NOT EXISTS cifs_shares\n(\n id INTEGER PRIMARY KEY,\n hostname TEXT NOT NULL,\n path TEXT NOT NULL,\n username TEXT NOT NULL,\n password TEXT\n);"
}, },
"cc33fe2958fe7caeac6999a217f918a68b45ad596664170b4d07671c6ea49566": { "cc33fe2958fe7caeac6999a217f918a68b45ad596664170b4d07671c6ea49566": {
"query": "SELECT hostname, path, username, password FROM cifs_shares WHERE id = ?",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -589,19 +598,19 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 1
},
"nullable": [ "nullable": [
false, false,
false, false,
false, false,
true true
] ],
} "parameters": {
"Right": 1
}
},
"query": "SELECT hostname, path, username, password FROM cifs_shares WHERE id = ?"
}, },
"d5117054072476377f3c4f040ea429d4c9b2cf534e76f35c80a2bf60e8599cca": { "d5117054072476377f3c4f040ea429d4c9b2cf534e76f35c80a2bf60e8599cca": {
"query": "SELECT openssh_pubkey FROM ssh_keys",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -610,36 +619,36 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 0
},
"nullable": [ "nullable": [
false false
] ],
} "parameters": {
"Right": 0
}
},
"query": "SELECT openssh_pubkey FROM ssh_keys"
}, },
"d54bd5b53f8c760e1f8cde604aa8b1bdc66e4e025a636bc44ffbcd788b5168fd": { "d54bd5b53f8c760e1f8cde604aa8b1bdc66e4e025a636bc44ffbcd788b5168fd": {
"query": "INSERT INTO notifications (package_id, code, level, title, message, data) VALUES (?, ?, ?, ?, ?, ?)",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 6 "Right": 6
}, }
"nullable": [] },
} "query": "INSERT INTO notifications (package_id, code, level, title, message, data) VALUES (?, ?, ?, ?, ?, ?)"
}, },
"d79d608ceb862c15b741a6040044c6dd54a837a3a0c5594d15a6041c7bc68ea8": { "d79d608ceb862c15b741a6040044c6dd54a837a3a0c5594d15a6041c7bc68ea8": {
"query": "INSERT OR IGNORE INTO tor (package, interface, key) VALUES (?, ?, ?)",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 3 "Right": 3
}, }
"nullable": [] },
} "query": "INSERT OR IGNORE INTO tor (package, interface, key) VALUES (?, ?, ?)"
}, },
"de2a5e90798d606047ab8180c044baac05469c0cdf151316bd58ee8c7196fdef": { "de2a5e90798d606047ab8180c044baac05469c0cdf151316bd58ee8c7196fdef": {
"query": "SELECT * FROM ssh_keys WHERE fingerprint = ?",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -658,18 +667,18 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 1
},
"nullable": [ "nullable": [
false, false,
false, false,
false false
] ],
} "parameters": {
"Right": 1
}
},
"query": "SELECT * FROM ssh_keys WHERE fingerprint = ?"
}, },
"ed848affa5bf92997cd441e3a50b3616b6724df3884bd9d199b3225e0bea8a54": { "ed848affa5bf92997cd441e3a50b3616b6724df3884bd9d199b3225e0bea8a54": {
"query": "SELECT priv_key_pem, certificate_pem FROM certificates WHERE id = 0;",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@@ -683,23 +692,24 @@
"type_info": "Text" "type_info": "Text"
} }
], ],
"parameters": {
"Right": 0
},
"nullable": [ "nullable": [
false, false,
false false
] ],
} "parameters": {
"Right": 0
}
},
"query": "SELECT priv_key_pem, certificate_pem FROM certificates WHERE id = 0;"
}, },
"f63c8c5a8754b34a49ef5d67802fa2b72aa409bbec92ecc6901492092974b71a": { "f63c8c5a8754b34a49ef5d67802fa2b72aa409bbec92ecc6901492092974b71a": {
"query": "DELETE FROM cifs_shares WHERE id = ?",
"describe": { "describe": {
"columns": [], "columns": [],
"nullable": [],
"parameters": { "parameters": {
"Right": 1 "Right": 1
}, }
"nullable": [] },
} "query": "DELETE FROM cifs_shares WHERE id = ?"
} }
} }

View File

@@ -1,76 +1,23 @@
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;
use clap::ArgMatches; use clap::ArgMatches;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use indexmap::IndexSet; use indexmap::IndexSet;
use patch_db::HasModel;
use rpc_toolkit::command; use rpc_toolkit::command;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::instrument; use tracing::instrument;
use self::docker::DockerAction;
use crate::config::{Config, ConfigSpec}; use crate::config::{Config, ConfigSpec};
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::id::{Id, ImageId, InvalidId}; use crate::id::ImageId;
use crate::procedure::{PackageProcedure, ProcedureName};
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::util::serde::{display_serializable, parse_stdin_deserializable, IoFormat}; use crate::util::serde::{display_serializable, parse_stdin_deserializable, IoFormat};
use crate::util::Version; use crate::util::Version;
use crate::volume::Volumes; use crate::volume::Volumes;
use crate::{Error, ResultExt}; use crate::{Error, ResultExt};
pub mod docker; pub use models::ActionId;
// TODO: create RPC endpoint that looks up the appropriate action and calls `execute`
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct ActionId<S: AsRef<str> = String>(Id<S>);
impl FromStr for ActionId {
type Err = InvalidId;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(ActionId(Id::try_from(s.to_owned())?))
}
}
impl From<ActionId> for String {
fn from(value: ActionId) -> Self {
value.0.into()
}
}
impl<S: AsRef<str>> AsRef<ActionId<S>> for ActionId<S> {
fn as_ref(&self) -> &ActionId<S> {
self
}
}
impl<S: AsRef<str>> std::fmt::Display for ActionId<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", &self.0)
}
}
impl<S: AsRef<str>> AsRef<str> for ActionId<S> {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl<S: AsRef<str>> AsRef<Path> for ActionId<S> {
fn as_ref(&self) -> &Path {
self.0.as_ref().as_ref()
}
}
impl<'de, S> Deserialize<'de> for ActionId<S>
where
S: AsRef<str>,
Id<S>: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
Ok(ActionId(Deserialize::deserialize(deserializer)?))
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)] #[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Actions(pub BTreeMap<ActionId, Action>); pub struct Actions(pub BTreeMap<ActionId, Action>);
@@ -103,16 +50,21 @@ pub struct Action {
pub description: String, pub description: String,
#[serde(default)] #[serde(default)]
pub warning: Option<String>, pub warning: Option<String>,
pub implementation: ActionImplementation, pub implementation: PackageProcedure,
pub allowed_statuses: IndexSet<DockerStatus>, pub allowed_statuses: IndexSet<DockerStatus>,
#[serde(default)] #[serde(default)]
pub input_spec: ConfigSpec, pub input_spec: ConfigSpec,
} }
impl Action { impl Action {
#[instrument] #[instrument]
pub fn validate(&self, volumes: &Volumes, image_ids: &BTreeSet<ImageId>) -> Result<(), Error> { pub fn validate(
&self,
eos_version: &Version,
volumes: &Volumes,
image_ids: &BTreeSet<ImageId>,
) -> Result<(), Error> {
self.implementation self.implementation
.validate(volumes, image_ids, true) .validate(eos_version, volumes, image_ids, true)
.with_ctx(|_| { .with_ctx(|_| {
( (
crate::ErrorKind::ValidateS9pk, crate::ErrorKind::ValidateS9pk,
@@ -141,7 +93,7 @@ impl Action {
ctx, ctx,
pkg_id, pkg_id,
pkg_version, pkg_version,
Some(&format!("{}Action", action_id)), ProcedureName::Action(action_id.clone()),
volumes, volumes,
input, input,
true, true,
@@ -152,77 +104,7 @@ impl Action {
} }
} }
#[derive(Clone, Debug, Deserialize, Serialize, HasModel)] fn display_action_result(action_result: ActionResult, matches: &ArgMatches) {
#[serde(rename_all = "kebab-case")]
#[serde(tag = "type")]
pub enum ActionImplementation {
Docker(DockerAction),
}
impl ActionImplementation {
#[instrument]
pub fn validate(
&self,
volumes: &Volumes,
image_ids: &BTreeSet<ImageId>,
expected_io: bool,
) -> Result<(), color_eyre::eyre::Report> {
match self {
ActionImplementation::Docker(action) => {
action.validate(volumes, image_ids, expected_io)
}
}
}
#[instrument(skip(ctx, input))]
pub async fn execute<I: Serialize, O: for<'de> Deserialize<'de>>(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
name: Option<&str>,
volumes: &Volumes,
input: Option<I>,
allow_inject: bool,
timeout: Option<Duration>,
) -> Result<Result<O, (i32, String)>, Error> {
match self {
ActionImplementation::Docker(action) => {
action
.execute(
ctx,
pkg_id,
pkg_version,
name,
volumes,
input,
allow_inject,
timeout,
)
.await
}
}
}
#[instrument(skip(ctx, input))]
pub async fn sandboxed<I: Serialize, O: for<'de> Deserialize<'de>>(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
volumes: &Volumes,
input: Option<I>,
timeout: Option<Duration>,
) -> Result<Result<O, (i32, String)>, Error> {
match self {
ActionImplementation::Docker(action) => {
action
.sandboxed(ctx, pkg_id, pkg_version, volumes, input, timeout)
.await
}
}
}
}
fn display_action_result(action_result: ActionResult, matches: &ArgMatches<'_>) {
if matches.is_present("format") { if matches.is_present("format") {
return display_serializable(action_result, matches); return display_serializable(action_result, matches);
} }
@@ -278,13 +160,3 @@ pub async fn action(
)) ))
} }
} }
pub struct NoOutput;
impl<'de> Deserialize<'de> for NoOutput {
fn deserialize<D>(_: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(NoOutput)
}
}

View File

@@ -1,354 +0,0 @@
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::{OsStr, OsString};
use std::net::Ipv4Addr;
use std::path::PathBuf;
use std::time::Duration;
use bollard::container::RemoveContainerOptions;
use futures::future::Either as EitherFuture;
use nix::sys::signal;
use nix::unistd::Pid;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::instrument;
use crate::context::RpcContext;
use crate::id::{Id, ImageId};
use crate::s9pk::manifest::{PackageId, SYSTEM_PACKAGE_ID};
use crate::util::serde::{Duration as SerdeDuration, IoFormat};
use crate::util::Version;
use crate::volume::{VolumeId, Volumes};
use crate::{Error, ResultExt, HOST_IP};
pub const NET_TLD: &str = "embassy";
lazy_static::lazy_static! {
pub static ref SYSTEM_IMAGES: BTreeSet<ImageId> = {
let mut set = BTreeSet::new();
set.insert("compat".parse().unwrap());
set.insert("utils".parse().unwrap());
set
};
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct DockerAction {
pub image: ImageId,
#[serde(default)]
pub system: bool,
pub entrypoint: String,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub mounts: BTreeMap<VolumeId, PathBuf>,
#[serde(default)]
pub io_format: Option<IoFormat>,
#[serde(default)]
pub inject: bool,
#[serde(default)]
pub shm_size_mb: Option<usize>, // TODO: use postfix sizing? like 1k vs 1m vs 1g
#[serde(default)]
pub sigterm_timeout: Option<SerdeDuration>,
}
impl DockerAction {
pub fn validate(
&self,
volumes: &Volumes,
image_ids: &BTreeSet<ImageId>,
expected_io: bool,
) -> Result<(), color_eyre::eyre::Report> {
for (volume, _) in &self.mounts {
if !volumes.contains_key(volume) && !matches!(&volume, &VolumeId::Backup) {
color_eyre::eyre::bail!("unknown volume: {}", volume);
}
}
if self.system {
if !SYSTEM_IMAGES.contains(&self.image) {
color_eyre::eyre::bail!("unknown system image: {}", self.image);
}
} else {
if !image_ids.contains(&self.image) {
color_eyre::eyre::bail!("image for {} not contained in package", self.image);
}
}
if expected_io && self.io_format.is_none() {
color_eyre::eyre::bail!("expected io-format");
}
Ok(())
}
#[instrument(skip(ctx, input))]
pub async fn execute<I: Serialize, O: for<'de> Deserialize<'de>>(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
name: Option<&str>,
volumes: &Volumes,
input: Option<I>,
allow_inject: bool,
timeout: Option<Duration>,
) -> Result<Result<O, (i32, String)>, Error> {
let mut cmd = tokio::process::Command::new("docker");
if self.inject && allow_inject {
cmd.arg("exec");
} else {
let container_name = Self::container_name(pkg_id, name);
cmd.arg("run")
.arg("--rm")
.arg("--network=start9")
.arg(format!("--add-host=embassy:{}", Ipv4Addr::from(HOST_IP)))
.arg("--name")
.arg(&container_name)
.arg(format!("--hostname={}", &container_name))
.arg("--no-healthcheck");
match ctx
.docker
.remove_container(
&container_name,
Some(RemoveContainerOptions {
v: false,
force: true,
link: false,
}),
)
.await
{
Ok(()) | Err(bollard::errors::Error::DockerResponseNotFoundError { .. }) => Ok(()),
Err(e) => Err(e),
}?;
}
cmd.args(
self.docker_args(ctx, pkg_id, pkg_version, volumes, allow_inject)
.await,
);
let input_buf = if let (Some(input), Some(format)) = (&input, &self.io_format) {
cmd.stdin(std::process::Stdio::piped());
Some(format.to_vec(input)?)
} else {
None
};
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
tracing::trace!(
"{}",
format!("{:?}", cmd)
.split(r#"" ""#)
.collect::<Vec<&str>>()
.join(" ")
);
let mut handle = cmd.spawn().with_kind(crate::ErrorKind::Docker)?;
let id = handle.id();
let timeout_fut = if let Some(timeout) = timeout {
EitherFuture::Right(async move {
tokio::time::sleep(timeout).await;
Ok(())
})
} else {
EitherFuture::Left(futures::future::pending::<Result<_, Error>>())
};
if let (Some(input), Some(mut stdin)) = (&input_buf, handle.stdin.take()) {
use tokio::io::AsyncWriteExt;
stdin
.write_all(input)
.await
.with_kind(crate::ErrorKind::Docker)?;
stdin.flush().await?;
stdin.shutdown().await?;
drop(stdin);
}
enum Race<T> {
Done(T),
TimedOut,
}
let res = tokio::select! {
res = handle.wait_with_output() => Race::Done(res.with_kind(crate::ErrorKind::Docker)?),
res = timeout_fut => {
res?;
Race::TimedOut
},
};
let res = match res {
Race::Done(x) => x,
Race::TimedOut => {
if let Some(id) = id {
signal::kill(Pid::from_raw(id as i32), signal::SIGKILL)
.with_kind(crate::ErrorKind::Docker)?;
}
return Ok(Err((143, "Timed out. Retrying soon...".to_owned())));
}
};
Ok(if res.status.success() || res.status.code() == Some(143) {
Ok(if let Some(format) = self.io_format {
match format.from_slice(&res.stdout) {
Ok(a) => a,
Err(e) => {
tracing::warn!(
"Failed to deserialize stdout from {}: {}, falling back to UTF-8 string.",
format,
e
);
serde_json::from_value(String::from_utf8(res.stdout)?.into())
.with_kind(crate::ErrorKind::Deserialization)?
}
}
} else if res.stdout.is_empty() {
serde_json::from_value(Value::Null).with_kind(crate::ErrorKind::Deserialization)?
} else {
serde_json::from_value(String::from_utf8(res.stdout)?.into())
.with_kind(crate::ErrorKind::Deserialization)?
})
} else {
Err((
res.status.code().unwrap_or_default(),
String::from_utf8(res.stderr)?,
))
})
}
#[instrument(skip(ctx, input))]
pub async fn sandboxed<I: Serialize, O: for<'de> Deserialize<'de>>(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
volumes: &Volumes,
input: Option<I>,
timeout: Option<Duration>,
) -> Result<Result<O, (i32, String)>, Error> {
let mut cmd = tokio::process::Command::new("docker");
cmd.arg("run").arg("--rm").arg("--network=none");
cmd.args(
self.docker_args(ctx, pkg_id, pkg_version, &volumes.to_readonly(), false)
.await,
);
let input_buf = if let (Some(input), Some(format)) = (&input, &self.io_format) {
cmd.stdin(std::process::Stdio::piped());
Some(format.to_vec(input)?)
} else {
None
};
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
let mut handle = cmd.spawn().with_kind(crate::ErrorKind::Docker)?;
if let (Some(input), Some(stdin)) = (&input_buf, &mut handle.stdin) {
use tokio::io::AsyncWriteExt;
stdin
.write_all(input)
.await
.with_kind(crate::ErrorKind::Docker)?;
}
let res = handle
.wait_with_output()
.await
.with_kind(crate::ErrorKind::Docker)?;
Ok(if res.status.success() || res.status.code() == Some(143) {
Ok(if let Some(format) = &self.io_format {
match format.from_slice(&res.stdout) {
Ok(a) => a,
Err(e) => {
tracing::warn!(
"Failed to deserialize stdout from {}: {}, falling back to UTF-8 string.",
format,
e
);
serde_json::from_value(String::from_utf8(res.stdout)?.into())
.with_kind(crate::ErrorKind::Deserialization)?
}
}
} else if res.stdout.is_empty() {
serde_json::from_value(Value::Null).with_kind(crate::ErrorKind::Deserialization)?
} else {
serde_json::from_value(String::from_utf8(res.stdout)?.into())
.with_kind(crate::ErrorKind::Deserialization)?
})
} else {
Err((
res.status.code().unwrap_or_default(),
String::from_utf8(res.stderr)?,
))
})
}
pub fn container_name(pkg_id: &PackageId, name: Option<&str>) -> String {
if let Some(name) = name {
format!("{}_{}.{}", pkg_id, name, NET_TLD)
} else {
format!("{}.{}", pkg_id, NET_TLD)
}
}
pub fn uncontainer_name(name: &str) -> Option<(PackageId<&str>, Option<&str>)> {
let (pre_tld, _) = name.split_once(".")?;
if pre_tld.contains('_') {
let (pkg, name) = name.split_once("_")?;
Some((Id::try_from(pkg).ok()?.into(), Some(name)))
} else {
Some((Id::try_from(pre_tld).ok()?.into(), None))
}
}
async fn docker_args(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
volumes: &Volumes,
allow_inject: bool,
) -> Vec<Cow<'_, OsStr>> {
let mut res = Vec::with_capacity(
(2 * self.mounts.len()) // --mount <MOUNT_ARG>
+ (2 * self.shm_size_mb.is_some() as usize) // --shm-size <SHM_SIZE>
+ 5 // --interactive --log-driver=journald --entrypoint <ENTRYPOINT> <IMAGE>
+ self.args.len(), // [ARG...]
);
for (volume_id, dst) in &self.mounts {
let volume = if let Some(v) = volumes.get(volume_id) {
v
} else {
continue;
};
let src = volume.path_for(ctx, pkg_id, pkg_version, volume_id);
if let Err(e) = tokio::fs::metadata(&src).await {
tracing::warn!("{} not mounted to container: {}", src.display(), e);
continue;
}
res.push(OsStr::new("--mount").into());
res.push(
OsString::from(format!(
"type=bind,src={},dst={}{}",
src.display(),
dst.display(),
if volume.readonly() { ",readonly" } else { "" }
))
.into(),
);
}
if let Some(shm_size_mb) = self.shm_size_mb {
res.push(OsStr::new("--shm-size").into());
res.push(OsString::from(format!("{}m", shm_size_mb)).into());
}
res.push(OsStr::new("--interactive").into());
if self.inject && allow_inject {
res.push(OsString::from(Self::container_name(pkg_id, None)).into());
res.push(OsStr::new(&self.entrypoint).into());
} else {
res.push(OsStr::new("--log-driver=journald").into());
res.push(OsStr::new("--entrypoint").into());
res.push(OsStr::new(&self.entrypoint).into());
if self.system {
res.push(OsString::from(self.image.for_package(SYSTEM_PACKAGE_ID, None)).into());
} else {
res.push(OsString::from(self.image.for_package(pkg_id, Some(pkg_version))).into());
}
}
res.extend(self.args.iter().map(|s| OsStr::new(s).into()));
res
}
}

View File

@@ -4,6 +4,7 @@ use std::marker::PhantomData;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use clap::ArgMatches; use clap::ArgMatches;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use patch_db::{DbHandle, LockReceipt};
use rpc_toolkit::command; use rpc_toolkit::command;
use rpc_toolkit::command_helpers::prelude::{RequestParts, ResponseParts}; use rpc_toolkit::command_helpers::prelude::{RequestParts, ResponseParts};
use rpc_toolkit::yajrc::RpcError; use rpc_toolkit::yajrc::RpcError;
@@ -18,12 +19,12 @@ use crate::util::display_none;
use crate::util::serde::{display_serializable, IoFormat}; use crate::util::serde::{display_serializable, IoFormat};
use crate::{ensure_code, Error, ResultExt}; use crate::{ensure_code, Error, ResultExt};
#[command(subcommands(login, logout, session))] #[command(subcommands(login, logout, session, reset_password))]
pub fn auth() -> Result<(), Error> { pub fn auth() -> Result<(), Error> {
Ok(()) Ok(())
} }
pub fn parse_metadata(_: &str, _: &ArgMatches<'_>) -> Result<Value, Error> { pub fn parse_metadata(_: &str, _: &ArgMatches) -> Result<Value, Error> {
Ok(serde_json::json!({ Ok(serde_json::json!({
"platforms": ["cli"], "platforms": ["cli"],
})) }))
@@ -51,7 +52,7 @@ async fn cli_login(
let password = if let Some(password) = password { let password = if let Some(password) = password {
password password
} else { } else {
rpassword::prompt_password_stdout("Password: ")? rpassword::prompt_password("Password: ")?
}; };
rpc_toolkit::command_helpers::call_remote( rpc_toolkit::command_helpers::call_remote(
@@ -168,7 +169,7 @@ pub async fn session() -> Result<(), Error> {
Ok(()) Ok(())
} }
fn display_sessions(arg: SessionList, matches: &ArgMatches<'_>) { fn display_sessions(arg: SessionList, matches: &ArgMatches) {
use prettytable::*; use prettytable::*;
if matches.is_present("format") { if matches.is_present("format") {
@@ -234,7 +235,7 @@ pub async fn list(
}) })
} }
fn parse_comma_separated(arg: &str, _: &ArgMatches<'_>) -> Result<Vec<String>, RpcError> { fn parse_comma_separated(arg: &str, _: &ArgMatches) -> Result<Vec<String>, RpcError> {
Ok(arg.split(",").map(|s| s.trim().to_owned()).collect()) Ok(arg.split(",").map(|s| s.trim().to_owned()).collect())
} }
@@ -256,3 +257,113 @@ pub async fn kill(
HasLoggedOutSessions::new(ids.into_iter().map(KillSessionId), &ctx).await?; HasLoggedOutSessions::new(ids.into_iter().map(KillSessionId), &ctx).await?;
Ok(()) Ok(())
} }
#[instrument(skip(ctx, old_password, new_password))]
async fn cli_reset_password(
ctx: CliContext,
old_password: Option<String>,
new_password: Option<String>,
) -> Result<(), RpcError> {
let old_password = if let Some(old_password) = old_password {
old_password
} else {
rpassword::prompt_password("Current Password: ")?
};
let new_password = if let Some(new_password) = new_password {
new_password
} else {
let new_password = rpassword::prompt_password("New Password: ")?;
if new_password != rpassword::prompt_password("Confirm: ")? {
return Err(Error::new(
eyre!("Passwords do not match"),
crate::ErrorKind::IncorrectPassword,
)
.into());
}
new_password
};
rpc_toolkit::command_helpers::call_remote(
ctx,
"auth.reset-password",
serde_json::json!({ "old-password": old_password, "new-password": new_password }),
PhantomData::<()>,
)
.await?
.result?;
Ok(())
}
pub struct SetPasswordReceipt(LockReceipt<String, ()>);
impl SetPasswordReceipt {
pub async fn new<Db: DbHandle>(db: &mut Db) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
let password_hash = crate::db::DatabaseModel::new()
.server_info()
.password_hash()
.make_locker(patch_db::LockType::Write)
.add_to_keys(locks);
move |skeleton_key| Ok(Self(password_hash.verify(skeleton_key)?))
}
}
pub async fn set_password<Db: DbHandle, Ex>(
db: &mut Db,
receipt: &SetPasswordReceipt,
secrets: &mut Ex,
password: &str,
) -> Result<(), Error>
where
for<'a> &'a mut Ex: Executor<'a, Database = Sqlite>,
{
let password = argon2::hash_encoded(
password.as_bytes(),
&rand::random::<[u8; 16]>()[..],
&argon2::Config::default(),
)
.with_kind(crate::ErrorKind::PasswordHashGeneration)?;
sqlx::query!("UPDATE account SET password = ?", password,)
.execute(secrets)
.await?;
receipt.0.set(db, password).await?;
Ok(())
}
#[command(
rename = "reset-password",
custom_cli(cli_reset_password(async, context(CliContext))),
display(display_none)
)]
#[instrument(skip(ctx, old_password, new_password))]
pub async fn reset_password(
#[context] ctx: RpcContext,
#[arg(rename = "old-password")] old_password: Option<String>,
#[arg(rename = "new-password")] new_password: Option<String>,
) -> Result<(), Error> {
let old_password = old_password.unwrap_or_default();
let new_password = new_password.unwrap_or_default();
let mut secrets = ctx.secret_store.acquire().await?;
check_password_against_db(&mut secrets, &old_password).await?;
let mut db = ctx.db.handle();
let set_password_receipt = SetPasswordReceipt::new(&mut db).await?;
set_password(&mut db, &set_password_receipt, &mut secrets, &new_password).await?;
Ok(())
}

View File

@@ -1,8 +1,11 @@
use std::collections::BTreeMap; use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use chrono::Utc; use chrono::Utc;
use clap::ArgMatches;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use helpers::AtomicFile;
use openssl::pkey::{PKey, Private}; use openssl::pkey::{PKey, Private};
use openssl::x509::X509; use openssl::x509::X509;
use patch_db::{DbHandle, LockType, PatchDbHandle, Revision}; use patch_db::{DbHandle, LockType, PatchDbHandle, Revision};
@@ -18,6 +21,7 @@ use super::PackageBackupReport;
use crate::auth::check_password_against_db; use crate::auth::check_password_against_db;
use crate::backup::{BackupReport, ServerBackupReport}; use crate::backup::{BackupReport, ServerBackupReport};
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::db::model::BackupProgress;
use crate::db::util::WithRevision; use crate::db::util::WithRevision;
use crate::disk::mount::backup::BackupMountGuard; use crate::disk::mount::backup::BackupMountGuard;
use crate::disk::mount::filesystem::ReadWrite; use crate::disk::mount::filesystem::ReadWrite;
@@ -25,10 +29,10 @@ use crate::disk::mount::guard::TmpMountGuard;
use crate::notifications::NotificationLevel; use crate::notifications::NotificationLevel;
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::status::MainStatus; use crate::status::MainStatus;
use crate::util::display_none;
use crate::util::serde::IoFormat; use crate::util::serde::IoFormat;
use crate::util::{display_none, AtomicFile};
use crate::version::VersionT; use crate::version::VersionT;
use crate::Error; use crate::{Error, ErrorKind, ResultExt};
#[derive(Debug)] #[derive(Debug)]
pub struct OsBackup { pub struct OsBackup {
@@ -112,12 +116,24 @@ impl Serialize for OsBackup {
} }
} }
fn parse_comma_separated(arg: &str, _: &ArgMatches) -> Result<BTreeSet<PackageId>, Error> {
arg.split(',')
.map(|s| s.trim().parse().map_err(Error::from))
.collect()
}
#[command(rename = "create", display(display_none))] #[command(rename = "create", display(display_none))]
#[instrument(skip(ctx, old_password, password))] #[instrument(skip(ctx, old_password, password))]
pub async fn backup_all( pub async fn backup_all(
#[context] ctx: RpcContext, #[context] ctx: RpcContext,
#[arg(rename = "target-id")] target_id: BackupTargetId, #[arg(rename = "target-id")] target_id: BackupTargetId,
#[arg(rename = "old-password", long = "old-password")] old_password: Option<String>, #[arg(rename = "old-password", long = "old-password")] old_password: Option<String>,
#[arg(
rename = "package-ids",
long = "package-ids",
parse(parse_comma_separated)
)]
package_ids: Option<BTreeSet<PackageId>>,
#[arg] password: String, #[arg] password: String,
) -> Result<WithRevision<()>, Error> { ) -> Result<WithRevision<()>, Error> {
let mut db = ctx.db.handle(); let mut db = ctx.db.handle();
@@ -130,17 +146,27 @@ pub async fn backup_all(
old_password.as_ref().unwrap_or(&password), old_password.as_ref().unwrap_or(&password),
) )
.await?; .await?;
let all_packages = crate::db::DatabaseModel::new()
.package_data()
.get(&mut db, false)
.await?
.0
.keys()
.into_iter()
.cloned()
.collect();
let package_ids = package_ids.unwrap_or(all_packages);
if old_password.is_some() { if old_password.is_some() {
backup_guard.change_password(&password)?; backup_guard.change_password(&password)?;
} }
let revision = assure_backing_up(&mut db).await?; let revision = assure_backing_up(&mut db, &package_ids).await?;
tokio::task::spawn(async move { tokio::task::spawn(async move {
let backup_res = perform_backup(&ctx, &mut db, backup_guard).await; let backup_res = perform_backup(&ctx, &mut db, backup_guard, &package_ids).await;
let status_model = crate::db::DatabaseModel::new() let backup_progress = crate::db::DatabaseModel::new()
.server_info() .server_info()
.status_info() .status_info()
.backing_up(); .backup_progress();
status_model backup_progress
.clone() .clone()
.lock(&mut db, LockType::Write) .lock(&mut db, LockType::Write)
.await .await
@@ -207,8 +233,8 @@ pub async fn backup_all(
.expect("failed to send notification"); .expect("failed to send notification");
} }
} }
status_model backup_progress
.put(&mut db, &false) .delete(&mut db)
.await .await
.expect("failed to change server status"); .expect("failed to change server status");
}); });
@@ -218,23 +244,40 @@ pub async fn backup_all(
}) })
} }
#[instrument(skip(db))] #[instrument(skip(db, packages))]
async fn assure_backing_up(db: &mut PatchDbHandle) -> Result<Option<Arc<Revision>>, Error> { async fn assure_backing_up(
db: &mut PatchDbHandle,
packages: impl IntoIterator<Item = &PackageId>,
) -> Result<Option<Arc<Revision>>, Error> {
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
let mut backing_up = crate::db::DatabaseModel::new() let mut backing_up = crate::db::DatabaseModel::new()
.server_info() .server_info()
.status_info() .status_info()
.backing_up() .backup_progress()
.get_mut(&mut tx) .get_mut(&mut tx)
.await?; .await?;
if *backing_up { if backing_up
.iter()
.flat_map(|x| x.values())
.fold(false, |acc, x| {
if !x.complete {
return true;
}
acc
})
{
return Err(Error::new( return Err(Error::new(
eyre!("Server is already backing up!"), eyre!("Server is already backing up!"),
crate::ErrorKind::InvalidRequest, crate::ErrorKind::InvalidRequest,
)); ));
} }
*backing_up = true; *backing_up = Some(
packages
.into_iter()
.map(|x| (x.clone(), BackupProgress { complete: false }))
.collect(),
);
backing_up.save(&mut tx).await?; backing_up.save(&mut tx).await?;
Ok(tx.commit(None).await?) Ok(tx.commit(None).await?)
} }
@@ -244,6 +287,7 @@ async fn perform_backup<Db: DbHandle>(
ctx: &RpcContext, ctx: &RpcContext,
mut db: Db, mut db: Db,
mut backup_guard: BackupMountGuard<TmpMountGuard>, mut backup_guard: BackupMountGuard<TmpMountGuard>,
package_ids: &BTreeSet<PackageId>,
) -> Result<BTreeMap<PackageId, PackageBackupReport>, Error> { ) -> Result<BTreeMap<PackageId, PackageBackupReport>, Error> {
let mut backup_report = BTreeMap::new(); let mut backup_report = BTreeMap::new();
@@ -251,6 +295,8 @@ async fn perform_backup<Db: DbHandle>(
.package_data() .package_data()
.keys(&mut db, false) .keys(&mut db, false)
.await? .await?
.into_iter()
.filter(|id| package_ids.contains(id))
{ {
let mut tx = db.begin().await?; // for lock scope let mut tx = db.begin().await?; // for lock scope
let installed_model = if let Some(installed_model) = crate::db::DatabaseModel::new() let installed_model = if let Some(installed_model) = crate::db::DatabaseModel::new()
@@ -268,9 +314,11 @@ async fn perform_backup<Db: DbHandle>(
main_status_model.lock(&mut tx, LockType::Write).await?; main_status_model.lock(&mut tx, LockType::Write).await?;
let (started, health) = match main_status_model.get(&mut tx, true).await?.into_owned() { let (started, health) = match main_status_model.get(&mut tx, true).await?.into_owned() {
MainStatus::Starting => (Some(Utc::now()), Default::default()), MainStatus::Starting { .. } => (Some(Utc::now()), Default::default()),
MainStatus::Running { started, health } => (Some(started), health.clone()), MainStatus::Running { started, health } => (Some(started), health.clone()),
MainStatus::Stopped | MainStatus::Stopping => (None, Default::default()), MainStatus::Stopped | MainStatus::Stopping | MainStatus::Restarting => {
(None, Default::default())
}
MainStatus::BackingUp { .. } => { MainStatus::BackingUp { .. } => {
backup_report.insert( backup_report.insert(
package_id, package_id,
@@ -318,6 +366,7 @@ async fn perform_backup<Db: DbHandle>(
.backup .backup
.create( .create(
ctx, ctx,
&mut tx,
&package_id, &package_id,
&manifest.title, &manifest.title,
&manifest.version, &manifest.version,
@@ -341,7 +390,7 @@ async fn perform_backup<Db: DbHandle>(
backup_guard backup_guard
.metadata .metadata
.package_backups .package_backups
.insert(package_id, pkg_meta); .insert(package_id.clone(), pkg_meta);
} }
main_status_model main_status_model
@@ -353,6 +402,23 @@ async fn perform_backup<Db: DbHandle>(
}, },
) )
.await?; .await?;
let mut backup_progress = crate::db::DatabaseModel::new()
.server_info()
.status_info()
.backup_progress()
.get_mut(&mut tx)
.await?;
if backup_progress.is_none() {
*backup_progress = Some(Default::default());
}
if let Some(mut backup_progress) = backup_progress
.as_mut()
.and_then(|bp| bp.get_mut(&package_id))
{
(*backup_progress).complete = true;
}
backup_progress.save(&mut tx).await?;
tx.save().await?; tx.save().await?;
} }
@@ -361,7 +427,12 @@ async fn perform_backup<Db: DbHandle>(
.await?; .await?;
let (root_ca_key, root_ca_cert) = ctx.net_controller.ssl.export_root_ca().await?; let (root_ca_key, root_ca_cert) = ctx.net_controller.ssl.export_root_ca().await?;
let mut os_backup_file = AtomicFile::new(backup_guard.as_ref().join("os-backup.cbor")).await?; let mut os_backup_file = AtomicFile::new(
backup_guard.as_ref().join("os-backup.cbor"),
None::<PathBuf>,
)
.await
.with_kind(ErrorKind::Filesystem)?;
os_backup_file os_backup_file
.write_all( .write_all(
&IoFormat::Cbor.to_vec(&OsBackup { &IoFormat::Cbor.to_vec(&OsBackup {
@@ -376,7 +447,10 @@ async fn perform_backup<Db: DbHandle>(
})?, })?,
) )
.await?; .await?;
os_backup_file.save().await?; os_backup_file
.save()
.await
.with_kind(ErrorKind::Filesystem)?;
let timestamp = Some(Utc::now()); let timestamp = Some(Utc::now());
@@ -392,6 +466,5 @@ async fn perform_backup<Db: DbHandle>(
.last_backup() .last_backup()
.put(&mut db, &timestamp) .put(&mut db, &timestamp)
.await?; .await?;
Ok(backup_report) Ok(backup_report)
} }

View File

@@ -1,9 +1,11 @@
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::path::Path; use std::path::{Path, PathBuf};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use helpers::AtomicFile;
use patch_db::{DbHandle, HasModel, LockType}; use patch_db::{DbHandle, HasModel, LockType};
use reqwest::Url;
use rpc_toolkit::command; use rpc_toolkit::command;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::{Executor, Sqlite}; use sqlx::{Executor, Sqlite};
@@ -12,18 +14,18 @@ use tokio::io::AsyncWriteExt;
use tracing::instrument; use tracing::instrument;
use self::target::PackageBackupInfo; use self::target::PackageBackupInfo;
use crate::action::{ActionImplementation, NoOutput};
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::dependencies::reconfigure_dependents_with_live_pointers; use crate::dependencies::reconfigure_dependents_with_live_pointers;
use crate::id::ImageId; use crate::id::ImageId;
use crate::install::PKG_ARCHIVE_DIR; use crate::install::PKG_ARCHIVE_DIR;
use crate::net::interface::{InterfaceId, Interfaces}; use crate::net::interface::{InterfaceId, Interfaces};
use crate::procedure::{NoOutput, PackageProcedure, ProcedureName};
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::util::serde::IoFormat; use crate::util::serde::IoFormat;
use crate::util::{AtomicFile, Version}; use crate::util::Version;
use crate::version::{Current, VersionT}; use crate::version::{Current, VersionT};
use crate::volume::{backup_dir, Volume, VolumeId, Volumes, BACKUP_DIR}; use crate::volume::{backup_dir, Volume, VolumeId, Volumes, BACKUP_DIR};
use crate::{Error, ResultExt}; use crate::{Error, ErrorKind, ResultExt};
pub mod backup_bulk; pub mod backup_bulk;
pub mod restore; pub mod restore;
@@ -60,28 +62,35 @@ pub fn package_backup() -> Result<(), Error> {
struct BackupMetadata { struct BackupMetadata {
pub timestamp: DateTime<Utc>, pub timestamp: DateTime<Utc>,
pub tor_keys: BTreeMap<InterfaceId, String>, pub tor_keys: BTreeMap<InterfaceId, String>,
pub marketplace_url: Option<Url>,
} }
#[derive(Clone, Debug, Deserialize, Serialize, HasModel)] #[derive(Clone, Debug, Deserialize, Serialize, HasModel)]
pub struct BackupActions { pub struct BackupActions {
pub create: ActionImplementation, pub create: PackageProcedure,
pub restore: ActionImplementation, pub restore: PackageProcedure,
} }
impl BackupActions { impl BackupActions {
pub fn validate(&self, volumes: &Volumes, image_ids: &BTreeSet<ImageId>) -> Result<(), Error> { pub fn validate(
&self,
eos_version: &Version,
volumes: &Volumes,
image_ids: &BTreeSet<ImageId>,
) -> Result<(), Error> {
self.create self.create
.validate(volumes, image_ids, false) .validate(eos_version, volumes, image_ids, false)
.with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Backup Create"))?; .with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Backup Create"))?;
self.restore self.restore
.validate(volumes, image_ids, false) .validate(eos_version, volumes, image_ids, false)
.with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Backup Restore"))?; .with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Backup Restore"))?;
Ok(()) Ok(())
} }
#[instrument(skip(ctx))] #[instrument(skip(ctx, db))]
pub async fn create( pub async fn create<Db: DbHandle>(
&self, &self,
ctx: &RpcContext, ctx: &RpcContext,
db: &mut Db,
pkg_id: &PackageId, pkg_id: &PackageId,
pkg_title: &str, pkg_title: &str,
pkg_version: &Version, pkg_version: &Version,
@@ -99,7 +108,7 @@ impl BackupActions {
ctx, ctx,
pkg_id, pkg_id,
pkg_version, pkg_version,
Some("CreateBackup"), ProcedureName::CreateBackup,
&volumes, &volumes,
None, None,
false, false,
@@ -119,6 +128,18 @@ impl BackupActions {
) )
}) })
.collect(); .collect();
let marketplace_url = crate::db::DatabaseModel::new()
.package_data()
.idx_model(pkg_id)
.expect(db)
.await?
.installed()
.expect(db)
.await?
.marketplace_url()
.get(db, true)
.await?
.into_owned();
let tmp_path = Path::new(BACKUP_DIR) let tmp_path = Path::new(BACKUP_DIR)
.join(pkg_id) .join(pkg_id)
.join(format!("{}.s9pk", pkg_id)); .join(format!("{}.s9pk", pkg_id));
@@ -129,7 +150,9 @@ impl BackupActions {
.join(pkg_version.as_str()) .join(pkg_version.as_str())
.join(format!("{}.s9pk", pkg_id)); .join(format!("{}.s9pk", pkg_id));
let mut infile = File::open(&s9pk_path).await?; let mut infile = File::open(&s9pk_path).await?;
let mut outfile = AtomicFile::new(&tmp_path).await?; let mut outfile = AtomicFile::new(&tmp_path, None::<PathBuf>)
.await
.with_kind(ErrorKind::Filesystem)?;
tokio::io::copy(&mut infile, &mut *outfile) tokio::io::copy(&mut infile, &mut *outfile)
.await .await
.with_ctx(|_| { .with_ctx(|_| {
@@ -138,17 +161,20 @@ impl BackupActions {
format!("cp {} -> {}", s9pk_path.display(), tmp_path.display()), format!("cp {} -> {}", s9pk_path.display(), tmp_path.display()),
) )
})?; })?;
outfile.save().await?; outfile.save().await.with_kind(ErrorKind::Filesystem)?;
let timestamp = Utc::now(); let timestamp = Utc::now();
let metadata_path = Path::new(BACKUP_DIR).join(pkg_id).join("metadata.cbor"); let metadata_path = Path::new(BACKUP_DIR).join(pkg_id).join("metadata.cbor");
let mut outfile = AtomicFile::new(&metadata_path).await?; let mut outfile = AtomicFile::new(&metadata_path, None::<PathBuf>)
.await
.with_kind(ErrorKind::Filesystem)?;
outfile outfile
.write_all(&IoFormat::Cbor.to_vec(&BackupMetadata { .write_all(&IoFormat::Cbor.to_vec(&BackupMetadata {
timestamp, timestamp,
tor_keys, tor_keys,
marketplace_url,
})?) })?)
.await?; .await?;
outfile.save().await?; outfile.save().await.with_kind(ErrorKind::Filesystem)?;
Ok(PackageBackupInfo { Ok(PackageBackupInfo {
os_version: Current::new().semver().into(), os_version: Current::new().semver().into(),
title: pkg_title.to_owned(), title: pkg_title.to_owned(),
@@ -178,7 +204,7 @@ impl BackupActions {
ctx, ctx,
pkg_id, pkg_id,
pkg_version, pkg_version,
Some("RestoreBackup"), ProcedureName::RestoreBackup,
&volumes, &volumes,
None, None,
false, false,
@@ -217,17 +243,21 @@ impl BackupActions {
.package_data() .package_data()
.lock(db, LockType::Write) .lock(db, LockType::Write)
.await?; .await?;
crate::db::DatabaseModel::new() let pde = crate::db::DatabaseModel::new()
.package_data() .package_data()
.idx_model(pkg_id) .idx_model(pkg_id)
.expect(db) .expect(db)
.await? .await?
.installed() .installed()
.expect(db) .expect(db)
.await? .await?;
pde.clone()
.interface_addresses() .interface_addresses()
.put(db, &interfaces.install(&mut *secrets, pkg_id).await?) .put(db, &interfaces.install(&mut *secrets, pkg_id).await?)
.await?; .await?;
pde.marketplace_url()
.put(db, &metadata.marketplace_url)
.await?;
let entry = crate::db::DatabaseModel::new() let entry = crate::db::DatabaseModel::new()
.package_data() .package_data()
@@ -240,7 +270,8 @@ impl BackupActions {
.get(db, true) .get(db, true)
.await?; .await?;
reconfigure_dependents_with_live_pointers(ctx, db, &entry).await?; let receipts = crate::config::ConfigReceipts::new(db).await?;
reconfigure_dependents_with_live_pointers(ctx, db, &receipts, &entry).await?;
Ok(()) Ok(())
} }

View File

@@ -27,6 +27,7 @@ use crate::disk::mount::guard::TmpMountGuard;
use crate::install::progress::InstallProgress; use crate::install::progress::InstallProgress;
use crate::install::{download_install_s9pk, PKG_PUBLIC_DIR}; use crate::install::{download_install_s9pk, PKG_PUBLIC_DIR};
use crate::net::ssl::SslManager; use crate::net::ssl::SslManager;
use crate::notifications::NotificationLevel;
use crate::s9pk::manifest::{Manifest, PackageId}; use crate::s9pk::manifest::{Manifest, PackageId};
use crate::s9pk::reader::S9pkReader; use crate::s9pk::reader::S9pkReader;
use crate::setup::RecoveryStatus; use crate::setup::RecoveryStatus;
@@ -34,43 +35,68 @@ use crate::util::display_none;
use crate::util::io::dir_size; use crate::util::io::dir_size;
use crate::util::serde::IoFormat; use crate::util::serde::IoFormat;
use crate::volume::{backup_dir, BACKUP_DIR, PKG_VOLUME_DIR}; use crate::volume::{backup_dir, BACKUP_DIR, PKG_VOLUME_DIR};
use crate::{auth::check_password_against_db, notifications::NotificationLevel};
use crate::{Error, ResultExt}; use crate::{Error, ResultExt};
fn parse_comma_separated(arg: &str, _: &ArgMatches<'_>) -> Result<Vec<PackageId>, Error> { fn parse_comma_separated(arg: &str, _: &ArgMatches) -> Result<Vec<PackageId>, Error> {
arg.split(',') arg.split(',')
.map(|s| s.trim().parse().map_err(Error::from)) .map(|s| s.trim().parse().map_err(Error::from))
.collect() .collect()
} }
#[command(rename = "restore", display(display_none))] #[command(rename = "restore", display(display_none))]
#[instrument(skip(ctx, old_password, password))] #[instrument(skip(ctx, password))]
pub async fn restore_packages_rpc( pub async fn restore_packages_rpc(
#[context] ctx: RpcContext, #[context] ctx: RpcContext,
#[arg(parse(parse_comma_separated))] ids: Vec<PackageId>, #[arg(parse(parse_comma_separated))] ids: Vec<PackageId>,
#[arg(rename = "target-id")] target_id: BackupTargetId, #[arg(rename = "target-id")] target_id: BackupTargetId,
#[arg(rename = "old-password", long = "old-password")] old_password: Option<String>,
#[arg] password: String, #[arg] password: String,
) -> Result<WithRevision<()>, Error> { ) -> Result<WithRevision<()>, Error> {
let mut db = ctx.db.handle(); let mut db = ctx.db.handle();
check_password_against_db(&mut ctx.secret_store.acquire().await?, &password).await?;
let fs = target_id let fs = target_id
.load(&mut ctx.secret_store.acquire().await?) .load(&mut ctx.secret_store.acquire().await?)
.await?; .await?;
let mut backup_guard = BackupMountGuard::mount( let backup_guard = BackupMountGuard::mount(
TmpMountGuard::mount(&fs, ReadOnly).await?, TmpMountGuard::mount(&fs, ReadOnly).await?,
old_password.as_ref().unwrap_or(&password), &password,
) )
.await?; .await?;
if old_password.is_some() {
backup_guard.change_password(&password)?;
}
let (revision, backup_guard, tasks, _) = let (revision, backup_guard, tasks, _) =
restore_packages(&ctx, &mut db, backup_guard, ids).await?; restore_packages(&ctx, &mut db, backup_guard, ids).await?;
tokio::spawn(async { tokio::spawn(async move {
futures::future::join_all(tasks).await; let res = futures::future::join_all(tasks).await;
for res in res {
match res.with_kind(crate::ErrorKind::Unknown) {
Ok((Ok(_), _)) => (),
Ok((Err(err), package_id)) => {
if let Err(err) = ctx.notification_manager.notify(
&mut db,
Some(package_id.clone()),
NotificationLevel::Error,
"Restoration Failure".to_string(), format!("Error restoring package {}: {}", package_id,err), (), None).await{
tracing::error!("Failed to notify: {}", err);
tracing::debug!("{:?}", err);
};
tracing::error!("Error restoring package {}: {}", package_id, err);
tracing::debug!("{:?}", err);
},
Err(e) => {
if let Err(err) = ctx.notification_manager.notify(
&mut db,
None,
NotificationLevel::Error,
"Restoration Failure".to_string(), format!("Error during restoration: {}", e), (), None).await {
tracing::error!("Failed to notify: {}", err);
tracing::debug!("{:?}", err);
}
tracing::error!("Error restoring packages: {}", e);
tracing::debug!("{:?}", e);
},
}
}
if let Err(e) = backup_guard.unmount().await { if let Err(e) = backup_guard.unmount().await {
tracing::error!("Error unmounting backup drive: {}", e); tracing::error!("Error unmounting backup drive: {}", e);
tracing::debug!("{:?}", e); tracing::debug!("{:?}", e);
@@ -243,7 +269,7 @@ pub async fn recover_full_embassy(
&mut db, &mut db,
None, None,
NotificationLevel::Error, NotificationLevel::Error,
"Restoration Failure".to_string(), format!("Error restoring ?: {}", e), (), None).await { "Restoration Failure".to_string(), format!("Error during restoration: {}", e), (), None).await {
tracing::error!("Failed to notify: {}", err); tracing::error!("Failed to notify: {}", err);
tracing::debug!("{:?}", err); tracing::debug!("{:?}", err);

View File

@@ -6,7 +6,7 @@ use chrono::{DateTime, Utc};
use clap::ArgMatches; use clap::ArgMatches;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use digest::generic_array::GenericArray; use digest::generic_array::GenericArray;
use digest::Digest; use digest::OutputSizeUser;
use rpc_toolkit::command; use rpc_toolkit::command;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::Sha256; use sha2::Sha256;
@@ -119,7 +119,9 @@ impl FileSystem for BackupTargetFS {
BackupTargetFS::Cifs(a) => a.mount(mountpoint, mount_type).await, BackupTargetFS::Cifs(a) => a.mount(mountpoint, mount_type).await,
} }
} }
async fn source_hash(&self) -> Result<GenericArray<u8, <Sha256 as Digest>::OutputSize>, Error> { async fn source_hash(
&self,
) -> Result<GenericArray<u8, <Sha256 as OutputSizeUser>::OutputSize>, Error> {
match self { match self {
BackupTargetFS::Disk(a) => a.source_hash().await, BackupTargetFS::Disk(a) => a.source_hash().await,
BackupTargetFS::Cifs(a) => a.source_hash().await, BackupTargetFS::Cifs(a) => a.source_hash().await,
@@ -184,7 +186,7 @@ pub struct PackageBackupInfo {
pub timestamp: DateTime<Utc>, pub timestamp: DateTime<Utc>,
} }
fn display_backup_info(info: BackupInfo, matches: &ArgMatches<'_>) { fn display_backup_info(info: BackupInfo, matches: &ArgMatches) {
use prettytable::*; use prettytable::*;
if matches.is_present("format") { if matches.is_present("format") {

View File

@@ -7,20 +7,24 @@ use rpc_toolkit::run_cli;
use rpc_toolkit::yajrc::RpcError; use rpc_toolkit::yajrc::RpcError;
use serde_json::Value; use serde_json::Value;
lazy_static::lazy_static! {
static ref VERSION_STRING: String = Current::new().semver().to_string();
}
fn inner_main() -> Result<(), Error> { fn inner_main() -> Result<(), Error> {
run_cli!({ run_cli!({
command: embassy::main_api, command: embassy::main_api,
app: app => app app: app => app
.name("Embassy CLI") .name("Embassy CLI")
.version(Current::new().semver().to_string().as_str()) .version(&**VERSION_STRING)
.arg( .arg(
clap::Arg::with_name("config") clap::Arg::with_name("config")
.short("c") .short('c')
.long("config") .long("config")
.takes_value(true), .takes_value(true),
) )
.arg(Arg::with_name("host").long("host").short("h").takes_value(true)) .arg(Arg::with_name("host").long("host").short('h').takes_value(true))
.arg(Arg::with_name("proxy").long("proxy").short("p").takes_value(true)), .arg(Arg::with_name("proxy").long("proxy").short('p').takes_value(true)),
context: matches => { context: matches => {
EmbassyLogger::init(); EmbassyLogger::init();
CliContext::init(matches)? CliContext::init(matches)?

View File

@@ -8,6 +8,7 @@ use embassy::disk::fsck::RepairStrategy;
use embassy::disk::main::DEFAULT_PASSWORD; use embassy::disk::main::DEFAULT_PASSWORD;
use embassy::disk::REPAIR_DISK_PATH; use embassy::disk::REPAIR_DISK_PATH;
use embassy::hostname::get_product_key; use embassy::hostname::get_product_key;
use embassy::init::STANDBY_MODE_PATH;
use embassy::middleware::cors::cors; use embassy::middleware::cors::cors;
use embassy::middleware::diagnostic::diagnostic; use embassy::middleware::diagnostic::diagnostic;
use embassy::middleware::encrypt::encrypt; use embassy::middleware::encrypt::encrypt;
@@ -17,7 +18,7 @@ use embassy::shutdown::Shutdown;
use embassy::sound::CHIME; use embassy::sound::CHIME;
use embassy::util::logger::EmbassyLogger; use embassy::util::logger::EmbassyLogger;
use embassy::util::Invoke; use embassy::util::Invoke;
use embassy::{Error, ResultExt}; use embassy::{Error, ErrorKind, ResultExt};
use http::StatusCode; use http::StatusCode;
use rpc_toolkit::rpc_server; use rpc_toolkit::rpc_server;
use tokio::process::Command; use tokio::process::Command;
@@ -79,7 +80,7 @@ async fn setup_or_init(cfg_path: Option<&str>) -> Result<(), Error> {
let guid_string = tokio::fs::read_to_string("/embassy-os/disk.guid") // unique identifier for volume group - keeps track of the disk that goes with your embassy let guid_string = tokio::fs::read_to_string("/embassy-os/disk.guid") // unique identifier for volume group - keeps track of the disk that goes with your embassy
.await?; .await?;
let guid = guid_string.trim(); let guid = guid_string.trim();
let reboot = embassy::disk::main::import( let requires_reboot = embassy::disk::main::import(
guid, guid,
cfg.datadir(), cfg.datadir(),
if tokio::fs::metadata(REPAIR_DISK_PATH).await.is_ok() { if tokio::fs::metadata(REPAIR_DISK_PATH).await.is_ok() {
@@ -95,7 +96,7 @@ async fn setup_or_init(cfg_path: Option<&str>) -> Result<(), Error> {
.await .await
.with_ctx(|_| (embassy::ErrorKind::Filesystem, REPAIR_DISK_PATH))?; .with_ctx(|_| (embassy::ErrorKind::Filesystem, REPAIR_DISK_PATH))?;
} }
if reboot.0 { if requires_reboot.0 {
embassy::disk::main::export(guid, cfg.datadir()).await?; embassy::disk::main::export(guid, cfg.datadir()).await?;
Command::new("reboot") Command::new("reboot")
.invoke(embassy::ErrorKind::Unknown) .invoke(embassy::ErrorKind::Unknown)
@@ -128,6 +129,13 @@ async fn run_script_if_exists<P: AsRef<Path>>(path: P) {
#[instrument] #[instrument]
async fn inner_main(cfg_path: Option<&str>) -> Result<Option<Shutdown>, Error> { async fn inner_main(cfg_path: Option<&str>) -> Result<Option<Shutdown>, Error> {
if tokio::fs::metadata(STANDBY_MODE_PATH).await.is_ok() {
tokio::fs::remove_file(STANDBY_MODE_PATH).await?;
Command::new("sync").invoke(ErrorKind::Filesystem).await?;
embassy::sound::SHUTDOWN.play().await?;
futures::future::pending::<()>().await;
}
embassy::sound::BEP.play().await?; embassy::sound::BEP.play().await?;
run_script_if_exists("/embassy-os/preinit.sh").await; run_script_if_exists("/embassy-os/preinit.sh").await;
@@ -210,7 +218,7 @@ fn main() {
let matches = clap::App::new("embassyd") let matches = clap::App::new("embassyd")
.arg( .arg(
clap::Arg::with_name("config") clap::Arg::with_name("config")
.short("c") .short('c')
.long("config") .long("config")
.takes_value(true), .takes_value(true),
) )

View File

@@ -6,21 +6,25 @@ use rpc_toolkit::run_cli;
use rpc_toolkit::yajrc::RpcError; use rpc_toolkit::yajrc::RpcError;
use serde_json::Value; use serde_json::Value;
lazy_static::lazy_static! {
static ref VERSION_STRING: String = Current::new().semver().to_string();
}
fn inner_main() -> Result<(), Error> { fn inner_main() -> Result<(), Error> {
run_cli!({ run_cli!({
command: embassy::portable_api, command: embassy::portable_api,
app: app => app app: app => app
.name("Embassy SDK") .name("Embassy SDK")
.version(Current::new().semver().to_string().as_str()) .version(&**VERSION_STRING)
.arg( .arg(
clap::Arg::with_name("config") clap::Arg::with_name("config")
.short("c") .short('c')
.long("config") .long("config")
.takes_value(true), .takes_value(true),
), ),
context: matches => { context: matches => {
if let Err(_) = std::env::var("RUST_LOG") { if let Err(_) = std::env::var("RUST_LOG") {
std::env::set_var("RUST_LOG", "embassy=warn"); std::env::set_var("RUST_LOG", "embassy=warn,js_engine=warn");
} }
EmbassyLogger::init(); EmbassyLogger::init();
SdkContext::init(matches)? SdkContext::init(matches)?

View File

@@ -81,7 +81,11 @@ async fn inner_main(cfg_path: Option<&str>) -> Result<Option<Shutdown>, Error> {
.expect("send shutdown signal"); .expect("send shutdown signal");
}); });
rpc_ctx.set_nginx_conf(&mut rpc_ctx.db.handle()).await?; let mut db = rpc_ctx.db.handle();
let receipts = embassy::context::rpc::RpcSetNginxReceipts::new(&mut db).await?;
rpc_ctx.set_nginx_conf(&mut db, receipts).await?;
drop(db);
let auth = auth(rpc_ctx.clone()); let auth = auth(rpc_ctx.clone());
let ctx = rpc_ctx.clone(); let ctx = rpc_ctx.clone();
let server = rpc_server!({ let server = rpc_server!({
@@ -283,7 +287,7 @@ fn main() {
let matches = clap::App::new("embassyd") let matches = clap::App::new("embassyd")
.arg( .arg(
clap::Arg::with_name("config") clap::Arg::with_name("config")
.short("c") .short('c')
.long("config") .long("config")
.takes_value(true), .takes_value(true),
) )
@@ -339,6 +343,7 @@ fn main() {
e, e,
) )
.await?; .await?;
let mut shutdown = ctx.shutdown.subscribe();
rpc_server!({ rpc_server!({
command: embassy::diagnostic_api, command: embassy::diagnostic_api,
context: ctx.clone(), context: ctx.clone(),
@@ -356,7 +361,7 @@ fn main() {
}) })
.await .await
.with_kind(embassy::ErrorKind::Network)?; .with_kind(embassy::ErrorKind::Network)?;
Ok::<_, Error>(None) Ok::<_, Error>(shutdown.recv().await.with_kind(crate::ErrorKind::Unknown)?)
})() })()
.await .await
} }

View File

@@ -7,10 +7,10 @@ use serde::{Deserialize, Serialize};
use tracing::instrument; use tracing::instrument;
use super::{Config, ConfigSpec}; use super::{Config, ConfigSpec};
use crate::action::ActionImplementation;
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::dependencies::Dependencies; use crate::dependencies::Dependencies;
use crate::id::ImageId; use crate::id::ImageId;
use crate::procedure::{PackageProcedure, ProcedureName};
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::status::health_check::HealthCheckId; use crate::status::health_check::HealthCheckId;
use crate::util::Version; use crate::util::Version;
@@ -26,17 +26,22 @@ pub struct ConfigRes {
#[derive(Clone, Debug, Deserialize, Serialize, HasModel)] #[derive(Clone, Debug, Deserialize, Serialize, HasModel)]
pub struct ConfigActions { pub struct ConfigActions {
pub get: ActionImplementation, pub get: PackageProcedure,
pub set: ActionImplementation, pub set: PackageProcedure,
} }
impl ConfigActions { impl ConfigActions {
#[instrument] #[instrument]
pub fn validate(&self, volumes: &Volumes, image_ids: &BTreeSet<ImageId>) -> Result<(), Error> { pub fn validate(
&self,
eos_version: &Version,
volumes: &Volumes,
image_ids: &BTreeSet<ImageId>,
) -> Result<(), Error> {
self.get self.get
.validate(volumes, image_ids, true) .validate(eos_version, volumes, image_ids, true)
.with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Config Get"))?; .with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Config Get"))?;
self.set self.set
.validate(volumes, image_ids, true) .validate(eos_version, volumes, image_ids, true)
.with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Config Set"))?; .with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Config Set"))?;
Ok(()) Ok(())
} }
@@ -53,7 +58,7 @@ impl ConfigActions {
ctx, ctx,
pkg_id, pkg_id,
pkg_version, pkg_version,
Some("GetConfig"), ProcedureName::GetConfig,
volumes, volumes,
None::<()>, None::<()>,
false, false,
@@ -81,7 +86,7 @@ impl ConfigActions {
ctx, ctx,
pkg_id, pkg_id,
pkg_version, pkg_version,
Some("SetConfig"), ProcedureName::SetConfig,
volumes, volumes,
Some(input), Some(input),
false, false,
@@ -107,6 +112,7 @@ impl ConfigActions {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct SetResult { pub struct SetResult {
#[serde(default)]
#[serde(deserialize_with = "crate::util::serde::deserialize_from_str_opt")] #[serde(deserialize_with = "crate::util::serde::deserialize_from_str_opt")]
#[serde(serialize_with = "crate::util::serde::serialize_display_opt")] #[serde(serialize_with = "crate::util::serde::serialize_display_opt")]
pub signal: Option<Signal>, pub signal: Option<Signal>,

View File

@@ -6,7 +6,7 @@ use color_eyre::eyre::eyre;
use futures::future::{BoxFuture, FutureExt}; use futures::future::{BoxFuture, FutureExt};
use indexmap::IndexSet; use indexmap::IndexSet;
use itertools::Itertools; use itertools::Itertools;
use patch_db::{DbHandle, LockType}; use patch_db::{DbHandle, LockReceipt, LockTarget, LockTargetId, LockType, Verifier};
use rand::SeedableRng; use rand::SeedableRng;
use regex::Regex; use regex::Regex;
use rpc_toolkit::command; use rpc_toolkit::command;
@@ -14,17 +14,18 @@ use serde_json::Value;
use tracing::instrument; use tracing::instrument;
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::db::model::CurrentDependencyInfo; use crate::db::model::{CurrentDependencies, CurrentDependencyInfo, CurrentDependents};
use crate::db::util::WithRevision; use crate::db::util::WithRevision;
use crate::dependencies::{ use crate::dependencies::{
add_dependent_to_current_dependents_lists, break_transitive, heal_all_dependents_transitive, add_dependent_to_current_dependents_lists, break_transitive, heal_all_dependents_transitive,
BreakageRes, DependencyError, DependencyErrors, TaggedDependencyError, BreakTransitiveReceipts, BreakageRes, Dependencies, DependencyConfig, DependencyError,
DependencyErrors, DependencyReceipt, TaggedDependencyError, TryHealReceipts,
}; };
use crate::install::cleanup::remove_from_current_dependents_lists; use crate::install::cleanup::{remove_from_current_dependents_lists, UpdateDependencyReceipts};
use crate::s9pk::manifest::{Manifest, PackageId}; use crate::s9pk::manifest::{Manifest, PackageId};
use crate::util::display_none; use crate::util::display_none;
use crate::util::serde::{display_serializable, parse_stdin_deserializable, IoFormat}; use crate::util::serde::{display_serializable, parse_stdin_deserializable, IoFormat};
use crate::{Error, ResultExt as _}; use crate::Error;
pub mod action; pub mod action;
pub mod spec; pub mod spec;
@@ -33,8 +34,8 @@ pub mod util;
pub use spec::{ConfigSpec, Defaultable}; pub use spec::{ConfigSpec, Defaultable};
use util::NumRange; use util::NumRange;
use self::action::ConfigRes; use self::action::{ConfigActions, ConfigRes};
use self::spec::{PackagePointerSpec, ValueSpecPointer}; use self::spec::{ConfigPointerReceipts, PackagePointerSpec, ValueSpecPointer};
pub type Config = serde_json::Map<String, Value>; pub type Config = serde_json::Map<String, Value>;
pub trait TypeOf { pub trait TypeOf {
@@ -163,6 +164,55 @@ pub fn config(#[arg] id: PackageId) -> Result<PackageId, Error> {
Ok(id) Ok(id)
} }
pub struct ConfigGetReceipts {
manifest_volumes: LockReceipt<crate::volume::Volumes, ()>,
manifest_version: LockReceipt<crate::util::Version, ()>,
manifest_config: LockReceipt<Option<ConfigActions>, ()>,
}
impl ConfigGetReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle, id: &PackageId) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks, id);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<LockTargetId>,
id: &PackageId,
) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let manifest_version = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|x| x.installed())
.map(|x| x.manifest().version())
.make_locker(LockType::Write)
.add_to_keys(locks);
let manifest_volumes = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|x| x.installed())
.map(|x| x.manifest().volumes())
.make_locker(LockType::Write)
.add_to_keys(locks);
let manifest_config = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|x| x.installed())
.map(|x| x.manifest().config())
.make_locker(LockType::Write)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
manifest_volumes: manifest_volumes.verify(skeleton_key)?,
manifest_version: manifest_version.verify(skeleton_key)?,
manifest_config: manifest_config.verify(skeleton_key)?,
})
}
}
}
#[command(display(display_serializable))] #[command(display(display_serializable))]
#[instrument(skip(ctx))] #[instrument(skip(ctx))]
pub async fn get( pub async fn get(
@@ -173,29 +223,16 @@ pub async fn get(
format: Option<IoFormat>, format: Option<IoFormat>,
) -> Result<ConfigRes, Error> { ) -> Result<ConfigRes, Error> {
let mut db = ctx.db.handle(); let mut db = ctx.db.handle();
let pkg_model = crate::db::DatabaseModel::new() let receipts = ConfigGetReceipts::new(&mut db, &id).await?;
.package_data() let action = receipts
.idx_model(&id) .manifest_config
.and_then(|m| m.installed()) .get(&mut db)
.expect(&mut db)
.await
.with_kind(crate::ErrorKind::NotFound)?;
let action = pkg_model
.clone()
.manifest()
.config()
.get(&mut db, true)
.await? .await?
.to_owned()
.ok_or_else(|| Error::new(eyre!("{} has no config", id), crate::ErrorKind::NotFound))?; .ok_or_else(|| Error::new(eyre!("{} has no config", id), crate::ErrorKind::NotFound))?;
let version = pkg_model
.clone() let volumes = receipts.manifest_volumes.get(&mut db).await?;
.manifest() let version = receipts.manifest_version.get(&mut db).await?;
.version() action.get(&ctx, &id, &version, &volumes).await
.get(&mut db, true)
.await?;
let volumes = pkg_model.manifest().volumes().get(&mut db, true).await?;
action.get(&ctx, &id, &*version, &*volumes).await
} }
#[command( #[command(
@@ -215,6 +252,157 @@ pub fn set(
Ok((id, config, timeout.map(|d| *d), expire_id)) Ok((id, config, timeout.map(|d| *d), expire_id))
} }
/// So, the new locking finds all the possible locks and lifts them up into a bundle of locks.
/// Then this bundle will be passed down into the functions that will need to touch the db, and
/// instead of doing the locks down in the system, we have already done the locks and can
/// do the operation on the db.
/// An UnlockedLock has two types, the type of setting and getting from the db, and the second type
/// is the keys that we need to insert on getting/setting because we have included wild cards into the paths.
pub struct ConfigReceipts {
pub dependency_receipt: DependencyReceipt,
pub config_receipts: ConfigPointerReceipts,
pub update_dependency_receipts: UpdateDependencyReceipts,
pub try_heal_receipts: TryHealReceipts,
pub break_transitive_receipts: BreakTransitiveReceipts,
configured: LockReceipt<bool, String>,
config_actions: LockReceipt<ConfigActions, String>,
dependencies: LockReceipt<Dependencies, String>,
volumes: LockReceipt<crate::volume::Volumes, String>,
version: LockReceipt<crate::util::Version, String>,
manifest: LockReceipt<Manifest, String>,
system_pointers: LockReceipt<Vec<spec::SystemPointerSpec>, String>,
pub current_dependents: LockReceipt<CurrentDependents, String>,
pub current_dependencies: LockReceipt<CurrentDependencies, String>,
dependency_errors: LockReceipt<DependencyErrors, String>,
manifest_dependencies_config: LockReceipt<DependencyConfig, (String, String)>,
}
impl ConfigReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(locks: &mut Vec<LockTargetId>) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let dependency_receipt = DependencyReceipt::setup(locks);
let config_receipts = ConfigPointerReceipts::setup(locks);
let update_dependency_receipts = UpdateDependencyReceipts::setup(locks);
let break_transitive_receipts = BreakTransitiveReceipts::setup(locks);
let try_heal_receipts = TryHealReceipts::setup(locks);
let configured: LockTarget<bool, String> = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.status().configured())
.make_locker(LockType::Write)
.add_to_keys(locks);
let config_actions = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.and_then(|x| x.manifest().config())
.make_locker(LockType::Read)
.add_to_keys(locks);
let dependencies = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest().dependencies())
.make_locker(LockType::Read)
.add_to_keys(locks);
let volumes = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest().volumes())
.make_locker(LockType::Read)
.add_to_keys(locks);
let version = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest().version())
.make_locker(LockType::Read)
.add_to_keys(locks);
let manifest = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest())
.make_locker(LockType::Read)
.add_to_keys(locks);
let system_pointers = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.system_pointers())
.make_locker(LockType::Write)
.add_to_keys(locks);
let current_dependents = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.current_dependents())
.make_locker(LockType::Write)
.add_to_keys(locks);
let current_dependencies = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.current_dependencies())
.make_locker(LockType::Write)
.add_to_keys(locks);
let dependency_errors = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.status().dependency_errors())
.make_locker(LockType::Write)
.add_to_keys(locks);
let manifest_dependencies_config = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.and_then(|x| x.manifest().dependencies().star().config())
.make_locker(LockType::Write)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
dependency_receipt: dependency_receipt(skeleton_key)?,
config_receipts: config_receipts(skeleton_key)?,
try_heal_receipts: try_heal_receipts(skeleton_key)?,
break_transitive_receipts: break_transitive_receipts(skeleton_key)?,
update_dependency_receipts: update_dependency_receipts(skeleton_key)?,
configured: configured.verify(skeleton_key)?,
config_actions: config_actions.verify(skeleton_key)?,
dependencies: dependencies.verify(skeleton_key)?,
volumes: volumes.verify(skeleton_key)?,
version: version.verify(skeleton_key)?,
manifest: manifest.verify(skeleton_key)?,
system_pointers: system_pointers.verify(skeleton_key)?,
current_dependents: current_dependents.verify(skeleton_key)?,
current_dependencies: current_dependencies.verify(skeleton_key)?,
dependency_errors: dependency_errors.verify(skeleton_key)?,
manifest_dependencies_config: manifest_dependencies_config.verify(skeleton_key)?,
})
}
}
}
#[command(rename = "dry", display(display_serializable))] #[command(rename = "dry", display(display_serializable))]
#[instrument(skip(ctx))] #[instrument(skip(ctx))]
pub async fn set_dry( pub async fn set_dry(
@@ -229,6 +417,7 @@ pub async fn set_dry(
let mut db = ctx.db.handle(); let mut db = ctx.db.handle();
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
let mut breakages = BTreeMap::new(); let mut breakages = BTreeMap::new();
let locks = ConfigReceipts::new(&mut tx).await?;
configure( configure(
&ctx, &ctx,
&mut tx, &mut tx,
@@ -238,20 +427,11 @@ pub async fn set_dry(
true, true,
&mut BTreeMap::new(), &mut BTreeMap::new(),
&mut breakages, &mut breakages,
&locks,
) )
.await?; .await?;
crate::db::DatabaseModel::new()
.package_data() locks.configured.set(&mut tx, true, &id).await?;
.idx_model(&id)
.expect(&mut tx)
.await?
.installed()
.expect(&mut tx)
.await?
.status()
.configured()
.put(&mut tx, &true)
.await?;
tx.abort().await?; tx.abort().await?;
Ok(BreakageRes(breakages)) Ok(BreakageRes(breakages))
} }
@@ -264,6 +444,7 @@ pub async fn set_impl(
let mut db = ctx.db.handle(); let mut db = ctx.db.handle();
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
let mut breakages = BTreeMap::new(); let mut breakages = BTreeMap::new();
let locks = ConfigReceipts::new(&mut tx).await?;
configure( configure(
&ctx, &ctx,
&mut tx, &mut tx,
@@ -273,6 +454,7 @@ pub async fn set_impl(
false, false,
&mut BTreeMap::new(), &mut BTreeMap::new(),
&mut breakages, &mut breakages,
&locks,
) )
.await?; .await?;
Ok(WithRevision { Ok(WithRevision {
@@ -281,34 +463,27 @@ pub async fn set_impl(
}) })
} }
#[instrument(skip(ctx, db))] #[instrument(skip(ctx, db, receipts))]
pub async fn configure<Db: DbHandle>( pub async fn configure<'a, Db: DbHandle>(
ctx: &RpcContext, ctx: &RpcContext,
db: &mut Db, db: &'a mut Db,
id: &PackageId, id: &PackageId,
config: Option<Config>, config: Option<Config>,
timeout: &Option<Duration>, timeout: &Option<Duration>,
dry_run: bool, dry_run: bool,
overrides: &mut BTreeMap<PackageId, Config>, overrides: &mut BTreeMap<PackageId, Config>,
breakages: &mut BTreeMap<PackageId, TaggedDependencyError>, breakages: &mut BTreeMap<PackageId, TaggedDependencyError>,
receipts: &ConfigReceipts,
) -> Result<(), Error> { ) -> Result<(), Error> {
configure_rec(ctx, db, id, config, timeout, dry_run, overrides, breakages).await?; configure_rec(
crate::db::DatabaseModel::new() ctx, db, id, config, timeout, dry_run, overrides, breakages, receipts,
.package_data() )
.idx_model(&id) .await?;
.expect(db) receipts.configured.set(db, true, &id).await?;
.await?
.installed()
.expect(db)
.await?
.status()
.configured()
.put(db, &true)
.await?;
Ok(()) Ok(())
} }
#[instrument(skip(ctx, db))] #[instrument(skip(ctx, db, receipts))]
pub fn configure_rec<'a, Db: DbHandle>( pub fn configure_rec<'a, Db: DbHandle>(
ctx: &'a RpcContext, ctx: &'a RpcContext,
db: &'a mut Db, db: &'a mut Db,
@@ -318,48 +493,33 @@ pub fn configure_rec<'a, Db: DbHandle>(
dry_run: bool, dry_run: bool,
overrides: &'a mut BTreeMap<PackageId, Config>, overrides: &'a mut BTreeMap<PackageId, Config>,
breakages: &'a mut BTreeMap<PackageId, TaggedDependencyError>, breakages: &'a mut BTreeMap<PackageId, TaggedDependencyError>,
receipts: &'a ConfigReceipts,
) -> BoxFuture<'a, Result<(), Error>> { ) -> BoxFuture<'a, Result<(), Error>> {
async move { async move {
crate::db::DatabaseModel::new()
.package_data()
.lock(db, LockType::Write)
.await?;
// fetch data from db // fetch data from db
let pkg_model = crate::db::DatabaseModel::new() let action = receipts
.package_data() .config_actions
.idx_model(id) .get(db, id)
.and_then(|m| m.installed())
.expect(db)
.await
.with_kind(crate::ErrorKind::NotFound)?;
let action = pkg_model
.clone()
.manifest()
.config()
.get(db, true)
.await? .await?
.to_owned() .ok_or_else(not_found)?;
.ok_or_else(|| Error::new(eyre!("{} has no config", id), crate::ErrorKind::NotFound))?; let dependencies = receipts
let version = pkg_model.clone().manifest().version().get(db, true).await?; .dependencies
let dependencies = pkg_model .get(db, id)
.clone() .await?
.manifest() .ok_or_else(not_found)?;
.dependencies() let volumes = receipts.volumes.get(db, id).await?.ok_or_else(not_found)?;
.get(db, true) let is_needs_config = !receipts
.await?; .configured
let volumes = pkg_model.clone().manifest().volumes().get(db, true).await?; .get(db, id)
let is_needs_config = !*pkg_model .await?
.clone() .ok_or_else(not_found)?;
.status() let version = receipts.version.get(db, id).await?.ok_or_else(not_found)?;
.configured()
.get(db, true)
.await?;
// get current config and current spec // get current config and current spec
let ConfigRes { let ConfigRes {
config: old_config, config: old_config,
spec, spec,
} = action.get(ctx, id, &*version, &*volumes).await?; } = action.get(ctx, id, &version, &volumes).await?;
// determine new config to use // determine new config to use
let mut config = if let Some(config) = config.or_else(|| old_config.clone()) { let mut config = if let Some(config) = config.or_else(|| old_config.clone()) {
@@ -368,45 +528,49 @@ pub fn configure_rec<'a, Db: DbHandle>(
spec.gen(&mut rand::rngs::StdRng::from_entropy(), timeout)? spec.gen(&mut rand::rngs::StdRng::from_entropy(), timeout)?
}; };
let manifest = crate::db::DatabaseModel::new() let manifest = receipts.manifest.get(db, id).await?.ok_or_else(not_found)?;
.package_data()
.idx_model(id)
.and_then(|m| m.installed())
.map::<_, Manifest>(|i| i.manifest())
.expect(db)
.await?
.get(db, true)
.await
.with_kind(crate::ErrorKind::NotFound)?;
spec.validate(&*manifest)?; spec.validate(&manifest)?;
spec.matches(&config)?; // check that new config matches spec spec.matches(&config)?; // check that new config matches spec
spec.update(ctx, db, &*manifest, &*overrides, &mut config) spec.update(
.await?; // dereference pointers in the new config ctx,
db,
&manifest,
&*overrides,
&mut config,
&receipts.config_receipts,
)
.await?; // dereference pointers in the new config
// create backreferences to pointers // create backreferences to pointers
let mut sys = pkg_model.clone().system_pointers().get_mut(db).await?; let mut sys = receipts
.system_pointers
.get(db, &id)
.await?
.ok_or_else(not_found)?;
sys.truncate(0); sys.truncate(0);
let mut current_dependencies: BTreeMap<PackageId, CurrentDependencyInfo> = dependencies let mut current_dependencies: CurrentDependencies = CurrentDependencies(
.0 dependencies
.iter() .0
.filter_map(|(id, info)| { .iter()
if info.requirement.required() { .filter_map(|(id, info)| {
Some((id.clone(), CurrentDependencyInfo::default())) if info.requirement.required() {
} else { Some((id.clone(), CurrentDependencyInfo::default()))
None } else {
} None
}) }
.collect(); })
.collect(),
);
for ptr in spec.pointers(&config)? { for ptr in spec.pointers(&config)? {
match ptr { match ptr {
ValueSpecPointer::Package(pkg_ptr) => { ValueSpecPointer::Package(pkg_ptr) => {
if let Some(current_dependency) = if let Some(current_dependency) =
current_dependencies.get_mut(pkg_ptr.package_id()) current_dependencies.0.get_mut(pkg_ptr.package_id())
{ {
current_dependency.pointers.push(pkg_ptr); current_dependency.pointers.push(pkg_ptr);
} else { } else {
current_dependencies.insert( current_dependencies.0.insert(
pkg_ptr.package_id().to_owned(), pkg_ptr.package_id().to_owned(),
CurrentDependencyInfo { CurrentDependencyInfo {
pointers: vec![pkg_ptr], pointers: vec![pkg_ptr],
@@ -418,20 +582,20 @@ pub fn configure_rec<'a, Db: DbHandle>(
ValueSpecPointer::System(s) => sys.push(s), ValueSpecPointer::System(s) => sys.push(s),
} }
} }
sys.save(db).await?; receipts.system_pointers.set(db, sys, &id).await?;
let signal = if !dry_run { let signal = if !dry_run {
// run config action // run config action
let res = action let res = action
.set(ctx, id, &*version, &*dependencies, &*volumes, &config) .set(ctx, id, &version, &dependencies, &volumes, &config)
.await?; .await?;
// track dependencies with no pointers // track dependencies with no pointers
for (package_id, health_checks) in res.depends_on.into_iter() { for (package_id, health_checks) in res.depends_on.into_iter() {
if let Some(current_dependency) = current_dependencies.get_mut(&package_id) { if let Some(current_dependency) = current_dependencies.0.get_mut(&package_id) {
current_dependency.health_checks.extend(health_checks); current_dependency.health_checks.extend(health_checks);
} else { } else {
current_dependencies.insert( current_dependencies.0.insert(
package_id, package_id,
CurrentDependencyInfo { CurrentDependencyInfo {
pointers: Vec::new(), pointers: Vec::new(),
@@ -442,79 +606,111 @@ pub fn configure_rec<'a, Db: DbHandle>(
} }
// track dependency health checks // track dependency health checks
current_dependencies = current_dependencies current_dependencies = current_dependencies.map(|x| {
.into_iter() x.into_iter()
.filter(|(dep_id, _)| { .filter(|(dep_id, _)| {
if dep_id != id && !manifest.dependencies.0.contains_key(dep_id) { if dep_id != id && !manifest.dependencies.0.contains_key(dep_id) {
tracing::warn!("Illegal dependency specified: {}", dep_id); tracing::warn!("Illegal dependency specified: {}", dep_id);
false false
} else { } else {
true true
} }
}) })
.collect(); .collect()
});
res.signal res.signal
} else { } else {
None None
}; };
// update dependencies // update dependencies
let mut deps = pkg_model.clone().current_dependencies().get_mut(db).await?; let prev_current_dependencies = receipts
remove_from_current_dependents_lists(db, id, deps.keys()).await?; // remove previous .current_dependencies
add_dependent_to_current_dependents_lists(db, id, &current_dependencies).await?; // add new .get(db, &id)
current_dependencies.remove(id); .await?
*deps = current_dependencies.clone(); .unwrap_or_default();
deps.save(db).await?; remove_from_current_dependents_lists(
let mut errs = pkg_model db,
.clone() id,
.status() &prev_current_dependencies,
.dependency_errors() &receipts.current_dependents,
.get_mut(db) )
.await?; // remove previous
add_dependent_to_current_dependents_lists(
db,
id,
&current_dependencies,
&receipts.current_dependents,
)
.await?; // add new
current_dependencies.0.remove(id);
receipts
.current_dependencies
.set(db, current_dependencies.clone(), &id)
.await?; .await?;
*errs = DependencyErrors::init(ctx, db, &*manifest, &current_dependencies).await?;
errs.save(db).await?; let errs = receipts
.dependency_errors
.get(db, &id)
.await?
.ok_or_else(not_found)?;
tracing::warn!("Dependency Errors: {:?}", errs);
let errs = DependencyErrors::init(
ctx,
db,
&manifest,
&current_dependencies,
&receipts.dependency_receipt.try_heal,
)
.await?;
receipts.dependency_errors.set(db, errs, &id).await?;
// cache current config for dependents // cache current config for dependents
overrides.insert(id.clone(), config.clone()); overrides.insert(id.clone(), config.clone());
// handle dependents // handle dependents
let dependents = pkg_model.clone().current_dependents().get(db, true).await?; let dependents = receipts
.current_dependents
.get(db, id)
.await?
.ok_or_else(not_found)?;
let prev = if is_needs_config { None } else { old_config } let prev = if is_needs_config { None } else { old_config }
.map(Value::Object) .map(Value::Object)
.unwrap_or_default(); .unwrap_or_default();
let next = Value::Object(config.clone()); let next = Value::Object(config.clone());
for (dependent, dep_info) in dependents.iter().filter(|(dep_id, _)| dep_id != &id) { for (dependent, dep_info) in dependents.0.iter().filter(|(dep_id, _)| dep_id != &id) {
// check if config passes dependent check // check if config passes dependent check
let dependent_model = crate::db::DatabaseModel::new() if let Some(cfg) = receipts
.package_data() .manifest_dependencies_config
.idx_model(dependent) .get(db, (&dependent, &id))
.and_then(|pkg| pkg.installed())
.expect(db)
.await?;
if let Some(cfg) = &*dependent_model
.clone()
.manifest()
.dependencies()
.idx_model(id)
.expect(db)
.await?
.config()
.get(db, true)
.await? .await?
{ {
let manifest = dependent_model.clone().manifest().get(db, true).await?; let manifest = receipts
.manifest
.get(db, &dependent)
.await?
.ok_or_else(not_found)?;
if let Err(error) = cfg if let Err(error) = cfg
.check( .check(
ctx, ctx,
dependent, dependent,
&manifest.version, &manifest.version,
&manifest.volumes, &manifest.volumes,
id,
&config, &config,
) )
.await? .await?
{ {
let dep_err = DependencyError::ConfigUnsatisfied { error }; let dep_err = DependencyError::ConfigUnsatisfied { error };
break_transitive(db, dependent, id, dep_err, breakages).await?; break_transitive(
db,
dependent,
id,
dep_err,
breakages,
&receipts.break_transitive_receipts,
)
.await?;
} }
// handle backreferences // handle backreferences
@@ -523,6 +719,7 @@ pub fn configure_rec<'a, Db: DbHandle>(
if cfg_ptr.select(&next) != cfg_ptr.select(&prev) { if cfg_ptr.select(&next) != cfg_ptr.select(&prev) {
if let Err(e) = configure_rec( if let Err(e) = configure_rec(
ctx, db, dependent, None, timeout, dry_run, overrides, breakages, ctx, db, dependent, None, timeout, dry_run, overrides, breakages,
receipts,
) )
.await .await
{ {
@@ -535,6 +732,7 @@ pub fn configure_rec<'a, Db: DbHandle>(
error: format!("{}", e), error: format!("{}", e),
}, },
breakages, breakages,
&receipts.break_transitive_receipts,
) )
.await?; .await?;
} else { } else {
@@ -544,7 +742,7 @@ pub fn configure_rec<'a, Db: DbHandle>(
} }
} }
} }
heal_all_dependents_transitive(ctx, db, id).await?; heal_all_dependents_transitive(ctx, db, id, &receipts.dependency_receipt).await?;
} }
} }
@@ -568,3 +766,67 @@ pub fn configure_rec<'a, Db: DbHandle>(
} }
.boxed() .boxed()
} }
#[instrument]
pub fn not_found() -> Error {
Error::new(eyre!("Could not find"), crate::ErrorKind::Incoherent)
}
/// We want to have a double check that the paths are what we expect them to be.
/// Found that earlier the paths where not what we expected them to be.
#[tokio::test]
async fn ensure_creation_of_config_paths_makes_sense() {
let mut fake = patch_db::test_utils::NoOpDb();
let config_locks = ConfigReceipts::new(&mut fake).await.unwrap();
assert_eq!(
&format!("{}", config_locks.configured.lock.glob),
"/package-data/*/installed/status/configured"
);
assert_eq!(
&format!("{}", config_locks.config_actions.lock.glob),
"/package-data/*/installed/manifest/config"
);
assert_eq!(
&format!("{}", config_locks.dependencies.lock.glob),
"/package-data/*/installed/manifest/dependencies"
);
assert_eq!(
&format!("{}", config_locks.volumes.lock.glob),
"/package-data/*/installed/manifest/volumes"
);
assert_eq!(
&format!("{}", config_locks.version.lock.glob),
"/package-data/*/installed/manifest/version"
);
assert_eq!(
&format!("{}", config_locks.volumes.lock.glob),
"/package-data/*/installed/manifest/volumes"
);
assert_eq!(
&format!("{}", config_locks.manifest.lock.glob),
"/package-data/*/installed/manifest"
);
assert_eq!(
&format!("{}", config_locks.manifest.lock.glob),
"/package-data/*/installed/manifest"
);
assert_eq!(
&format!("{}", config_locks.system_pointers.lock.glob),
"/package-data/*/installed/system-pointers"
);
assert_eq!(
&format!("{}", config_locks.current_dependents.lock.glob),
"/package-data/*/installed/current-dependents"
);
assert_eq!(
&format!("{}", config_locks.dependency_errors.lock.glob),
"/package-data/*/installed/status/dependency-errors"
);
assert_eq!(
&format!("{}", config_locks.manifest_dependencies_config.lock.glob),
"/package-data/*/installed/manifest/dependencies/*/config"
);
assert_eq!(
&format!("{}", config_locks.system_pointers.lock.glob),
"/package-data/*/installed/system-pointers"
);
}

View File

@@ -12,9 +12,10 @@ use async_trait::async_trait;
use indexmap::{IndexMap, IndexSet}; use indexmap::{IndexMap, IndexSet};
use itertools::Itertools; use itertools::Itertools;
use jsonpath_lib::Compiled as CompiledJsonPath; use jsonpath_lib::Compiled as CompiledJsonPath;
use patch_db::{DbHandle, OptionModel}; use patch_db::{DbHandle, LockReceipt, LockType};
use rand::{CryptoRng, Rng}; use rand::{CryptoRng, Rng};
use regex::Regex; use regex::Regex;
use serde::de::{MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{Number, Value}; use serde_json::{Number, Value};
use sqlx::SqlitePool; use sqlx::SqlitePool;
@@ -44,6 +45,7 @@ pub trait ValueSpec {
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError>; ) -> Result<(), ConfigurationError>;
// returns all pointers that are live in the provided config // returns all pointers that are live in the provided config
fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath>; fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath>;
@@ -160,9 +162,10 @@ where
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
self.inner self.inner
.update(ctx, db, manifest, config_overrides, value) .update(ctx, db, manifest, config_overrides, value, receipts)
.await .await
} }
fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> { fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> {
@@ -204,9 +207,10 @@ where
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
self.inner self.inner
.update(ctx, db, manifest, config_overrides, value) .update(ctx, db, manifest, config_overrides, value, receipts)
.await .await
} }
fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> { fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> {
@@ -281,9 +285,10 @@ where
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
self.inner self.inner
.update(ctx, db, manifest, config_overrides, value) .update(ctx, db, manifest, config_overrides, value, receipts)
.await .await
} }
fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> { fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> {
@@ -343,7 +348,7 @@ pub enum ValueSpecAny {
Pointer(WithDescription<ValueSpecPointer>), Pointer(WithDescription<ValueSpecPointer>),
} }
impl ValueSpecAny { impl ValueSpecAny {
pub fn name<'a>(&'a self) -> &'a str { pub fn name(&self) -> &'_ str {
match self { match self {
ValueSpecAny::Boolean(b) => b.name.as_str(), ValueSpecAny::Boolean(b) => b.name.as_str(),
ValueSpecAny::Enum(e) => e.name.as_str(), ValueSpecAny::Enum(e) => e.name.as_str(),
@@ -395,16 +400,41 @@ impl ValueSpec for ValueSpecAny {
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
match self { match self {
ValueSpecAny::Boolean(a) => a.update(ctx, db, manifest, config_overrides, value).await, ValueSpecAny::Boolean(a) => {
ValueSpecAny::Enum(a) => a.update(ctx, db, manifest, config_overrides, value).await, a.update(ctx, db, manifest, config_overrides, value, receipts)
ValueSpecAny::List(a) => a.update(ctx, db, manifest, config_overrides, value).await, .await
ValueSpecAny::Number(a) => a.update(ctx, db, manifest, config_overrides, value).await, }
ValueSpecAny::Object(a) => a.update(ctx, db, manifest, config_overrides, value).await, ValueSpecAny::Enum(a) => {
ValueSpecAny::String(a) => a.update(ctx, db, manifest, config_overrides, value).await, a.update(ctx, db, manifest, config_overrides, value, receipts)
ValueSpecAny::Union(a) => a.update(ctx, db, manifest, config_overrides, value).await, .await
ValueSpecAny::Pointer(a) => a.update(ctx, db, manifest, config_overrides, value).await, }
ValueSpecAny::List(a) => {
a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
}
ValueSpecAny::Number(a) => {
a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
}
ValueSpecAny::Object(a) => {
a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
}
ValueSpecAny::String(a) => {
a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
}
ValueSpecAny::Union(a) => {
a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
}
ValueSpecAny::Pointer(a) => {
a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
}
} }
} }
fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> { fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> {
@@ -489,6 +519,7 @@ impl ValueSpec for ValueSpecBoolean {
_manifest: &Manifest, _manifest: &Manifest,
_config_overrides: &BTreeMap<PackageId, Config>, _config_overrides: &BTreeMap<PackageId, Config>,
_value: &mut Value, _value: &mut Value,
_receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
Ok(()) Ok(())
} }
@@ -578,6 +609,7 @@ impl ValueSpec for ValueSpecEnum {
_manifest: &Manifest, _manifest: &Manifest,
_config_overrides: &BTreeMap<PackageId, Config>, _config_overrides: &BTreeMap<PackageId, Config>,
_value: &mut Value, _value: &mut Value,
_receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
Ok(()) Ok(())
} }
@@ -664,12 +696,13 @@ where
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
if let Value::Array(ref mut ls) = value { if let Value::Array(ref mut ls) = value {
for (i, val) in ls.into_iter().enumerate() { for (i, val) in ls.into_iter().enumerate() {
match self match self
.spec .spec
.update(ctx, db, manifest, config_overrides, val) .update(ctx, db, manifest, config_overrides, val, receipts)
.await .await
{ {
Err(ConfigurationError::NoMatch(e)) => { Err(ConfigurationError::NoMatch(e)) => {
@@ -771,13 +804,29 @@ impl ValueSpec for ValueSpecList {
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
match self { match self {
ValueSpecList::Enum(a) => a.update(ctx, db, manifest, config_overrides, value).await, ValueSpecList::Enum(a) => {
ValueSpecList::Number(a) => a.update(ctx, db, manifest, config_overrides, value).await, a.update(ctx, db, manifest, config_overrides, value, receipts)
ValueSpecList::Object(a) => a.update(ctx, db, manifest, config_overrides, value).await, .await
ValueSpecList::String(a) => a.update(ctx, db, manifest, config_overrides, value).await, }
ValueSpecList::Union(a) => a.update(ctx, db, manifest, config_overrides, value).await, ValueSpecList::Number(a) => {
a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
}
ValueSpecList::Object(a) => {
a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
}
ValueSpecList::String(a) => {
a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
}
ValueSpecList::Union(a) => {
a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
}
} }
} }
fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> { fn pointers(&self, value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> {
@@ -898,6 +947,7 @@ impl ValueSpec for ValueSpecNumber {
_manifest: &Manifest, _manifest: &Manifest,
_config_overrides: &BTreeMap<PackageId, Config>, _config_overrides: &BTreeMap<PackageId, Config>,
_value: &mut Value, _value: &mut Value,
_receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
Ok(()) Ok(())
} }
@@ -961,10 +1011,11 @@ impl ValueSpec for ValueSpecObject {
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
if let Value::Object(o) = value { if let Value::Object(o) = value {
self.spec self.spec
.update(ctx, db, manifest, config_overrides, o) .update(ctx, db, manifest, config_overrides, o, receipts)
.await .await
} else { } else {
Err(ConfigurationError::NoMatch(NoMatchWithPath::new( Err(ConfigurationError::NoMatch(NoMatchWithPath::new(
@@ -1063,16 +1114,20 @@ impl ConfigSpec {
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
cfg: &mut Config, cfg: &mut Config,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
for (k, vs) in self.0.iter() { for (k, vs) in self.0.iter() {
match cfg.get_mut(k) { match cfg.get_mut(k) {
None => { None => {
let mut v = Value::Null; let mut v = Value::Null;
vs.update(ctx, db, manifest, config_overrides, &mut v) vs.update(ctx, db, manifest, config_overrides, &mut v, receipts)
.await?; .await?;
cfg.insert(k.clone(), v); cfg.insert(k.clone(), v);
} }
Some(v) => match vs.update(ctx, db, manifest, config_overrides, v).await { Some(v) => match vs
.update(ctx, db, manifest, config_overrides, v, receipts)
.await
{
Err(ConfigurationError::NoMatch(e)) => { Err(ConfigurationError::NoMatch(e)) => {
Err(ConfigurationError::NoMatch(e.prepend(k.clone()))) Err(ConfigurationError::NoMatch(e.prepend(k.clone())))
} }
@@ -1113,18 +1168,95 @@ pub struct Pattern {
pub pattern_description: String, pub pattern_description: String,
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct ValueSpecString { pub struct ValueSpecString {
#[serde(flatten)] #[serde(flatten)]
pub pattern: Option<Pattern>, pub pattern: Option<Pattern>,
#[serde(default)] pub textarea: bool,
pub copyable: bool, pub copyable: bool,
#[serde(default)]
pub masked: bool, pub masked: bool,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub placeholder: Option<String>, pub placeholder: Option<String>,
} }
impl<'de> Deserialize<'de> for ValueSpecString {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<ValueSpecString, D::Error> {
struct ValueSpecStringVisitor;
impl<'de> Visitor<'de> for ValueSpecStringVisitor {
type Value = ValueSpecString;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("struct ValueSpecString")
}
fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<ValueSpecString, V::Error> {
let mut pattern = None;
let mut pattern_description = None;
let mut textarea = false;
let mut copyable = false;
let mut masked = false;
let mut placeholder = None;
while let Some::<String>(key) = map.next_key()? {
if &key == "pattern" {
if pattern.is_some() {
return Err(serde::de::Error::duplicate_field("pattern"));
} else {
pattern = Some(
Regex::new(&map.next_value::<String>()?)
.map_err(serde::de::Error::custom)?,
);
}
} else if &key == "pattern-description" {
if pattern_description.is_some() {
return Err(serde::de::Error::duplicate_field("pattern-description"));
} else {
pattern_description = Some(map.next_value()?);
}
} else if &key == "textarea" {
textarea = map.next_value()?;
} else if &key == "copyable" {
copyable = map.next_value()?;
} else if &key == "masked" {
masked = map.next_value()?;
} else if &key == "placeholder" {
if placeholder.is_some() {
return Err(serde::de::Error::duplicate_field("placeholder"));
} else {
placeholder = Some(map.next_value()?);
}
}
}
let regex = match (pattern, pattern_description) {
(None, None) => None,
(Some(p), Some(d)) => Some(Pattern {
pattern: p,
pattern_description: d,
}),
(Some(_), None) => {
return Err(serde::de::Error::missing_field("pattern-description"));
}
(None, Some(_)) => {
return Err(serde::de::Error::missing_field("pattern"));
}
};
Ok(ValueSpecString {
pattern: regex,
textarea,
copyable,
masked,
placeholder,
})
}
}
const FIELDS: &'static [&'static str] = &[
"pattern",
"pattern-description",
"textarea",
"copyable",
"masked",
"placeholder",
];
deserializer.deserialize_struct("ValueSpecString", FIELDS, ValueSpecStringVisitor)
}
}
#[async_trait] #[async_trait]
impl ValueSpec for ValueSpecString { impl ValueSpec for ValueSpecString {
fn matches(&self, value: &Value) -> Result<(), NoMatchWithPath> { fn matches(&self, value: &Value) -> Result<(), NoMatchWithPath> {
@@ -1160,6 +1292,7 @@ impl ValueSpec for ValueSpecString {
_manifest: &Manifest, _manifest: &Manifest,
_config_overrides: &BTreeMap<PackageId, Config>, _config_overrides: &BTreeMap<PackageId, Config>,
_value: &mut Value, _value: &mut Value,
_receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
Ok(()) Ok(())
} }
@@ -1192,10 +1325,7 @@ impl DefaultableWith for ValueSpecString {
let candidate = spec.gen(rng); let candidate = spec.gen(rng);
match (spec, &self.pattern) { match (spec, &self.pattern) {
(DefaultString::Entropy(_), Some(pattern)) (DefaultString::Entropy(_), Some(pattern))
if !pattern.pattern.is_match(&candidate) => if !pattern.pattern.is_match(&candidate) => {}
{
()
}
_ => { _ => {
return Ok(Value::String(candidate)); return Ok(Value::String(candidate));
} }
@@ -1371,6 +1501,7 @@ impl ValueSpec for ValueSpecUnion {
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
if let Value::Object(o) = value { if let Value::Object(o) = value {
match o.get(&self.tag.id) { match o.get(&self.tag.id) {
@@ -1381,7 +1512,10 @@ impl ValueSpec for ValueSpecUnion {
None => Err(ConfigurationError::NoMatch(NoMatchWithPath::new( None => Err(ConfigurationError::NoMatch(NoMatchWithPath::new(
MatchError::Union(tag.clone(), self.variants.keys().cloned().collect()), MatchError::Union(tag.clone(), self.variants.keys().cloned().collect()),
))), ))),
Some(spec) => spec.update(ctx, db, manifest, config_overrides, o).await, Some(spec) => {
spec.update(ctx, db, manifest, config_overrides, o, receipts)
.await
}
}, },
Some(other) => Err(ConfigurationError::NoMatch( Some(other) => Err(ConfigurationError::NoMatch(
NoMatchWithPath::new(MatchError::InvalidType("string", other.type_of())) NoMatchWithPath::new(MatchError::InvalidType("string", other.type_of()))
@@ -1513,13 +1647,16 @@ impl ValueSpec for ValueSpecPointer {
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
match self { match self {
ValueSpecPointer::Package(a) => { ValueSpecPointer::Package(a) => {
a.update(ctx, db, manifest, config_overrides, value).await a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
} }
ValueSpecPointer::System(a) => { ValueSpecPointer::System(a) => {
a.update(ctx, db, manifest, config_overrides, value).await a.update(ctx, db, manifest, config_overrides, value, receipts)
.await
} }
} }
} }
@@ -1563,12 +1700,17 @@ impl PackagePointerSpec {
db: &mut Db, db: &mut Db,
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
receipts: &ConfigPointerReceipts,
) -> Result<Value, ConfigurationError> { ) -> Result<Value, ConfigurationError> {
match &self { match &self {
PackagePointerSpec::TorKey(key) => key.deref(&manifest.id, &ctx.secret_store).await, PackagePointerSpec::TorKey(key) => key.deref(&manifest.id, &ctx.secret_store).await,
PackagePointerSpec::TorAddress(tor) => tor.deref(db).await, PackagePointerSpec::TorAddress(tor) => {
PackagePointerSpec::LanAddress(lan) => lan.deref(db).await, tor.deref(db, &receipts.interface_addresses_receipt).await
PackagePointerSpec::Config(cfg) => cfg.deref(ctx, db, config_overrides).await, }
PackagePointerSpec::LanAddress(lan) => {
lan.deref(db, &receipts.interface_addresses_receipt).await
}
PackagePointerSpec::Config(cfg) => cfg.deref(ctx, db, config_overrides, receipts).await,
} }
} }
} }
@@ -1616,8 +1758,11 @@ impl ValueSpec for PackagePointerSpec {
manifest: &Manifest, manifest: &Manifest,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
*value = self.deref(ctx, db, manifest, config_overrides).await?; *value = self
.deref(ctx, db, manifest, config_overrides, receipts)
.await?;
Ok(()) Ok(())
} }
fn pointers(&self, _value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> { fn pointers(&self, _value: &Value) -> Result<BTreeSet<ValueSpecPointer>, NoMatchWithPath> {
@@ -1640,16 +1785,17 @@ pub struct TorAddressPointer {
interface: InterfaceId, interface: InterfaceId,
} }
impl TorAddressPointer { impl TorAddressPointer {
async fn deref<Db: DbHandle>(&self, db: &mut Db) -> Result<Value, ConfigurationError> { async fn deref<Db: DbHandle>(
let addr = crate::db::DatabaseModel::new() &self,
.package_data() db: &mut Db,
.idx_model(&self.package_id) receipt: &InterfaceAddressesReceipt,
.and_then(|pde| pde.installed()) ) -> Result<Value, ConfigurationError> {
.and_then(|installed| installed.interface_addresses().idx_model(&self.interface)) let addr = receipt
.and_then(|addresses| addresses.tor_address()) .interface_addresses
.get(db, true) .get(db, (&self.package_id, &self.interface))
.await .await
.map_err(|e| ConfigurationError::SystemError(Error::from(e)))?; .map_err(|e| ConfigurationError::SystemError(Error::from(e)))?
.and_then(|addresses| addresses.tor_address);
Ok(addr.to_owned().map(Value::String).unwrap_or(Value::Null)) Ok(addr.to_owned().map(Value::String).unwrap_or(Value::Null))
} }
} }
@@ -1664,6 +1810,39 @@ impl fmt::Display for TorAddressPointer {
} }
} }
pub struct InterfaceAddressesReceipt {
interface_addresses: LockReceipt<crate::db::model::InterfaceAddresses, (String, String)>,
}
impl InterfaceAddressesReceipt {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
// let cleanup_receipts = CleanupFailedReceipts::setup(locks);
let interface_addresses = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.interface_addresses().star())
.make_locker(LockType::Read)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
// cleanup_receipts: cleanup_receipts(skeleton_key)?,
interface_addresses: interface_addresses.verify(skeleton_key)?,
})
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct LanAddressPointer { pub struct LanAddressPointer {
@@ -1672,28 +1851,81 @@ pub struct LanAddressPointer {
} }
impl fmt::Display for LanAddressPointer { impl fmt::Display for LanAddressPointer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { let LanAddressPointer {
LanAddressPointer { package_id,
package_id, interface,
interface, } = self;
} => write!(f, "{}: lan-address: {}", package_id, interface), write!(f, "{}: lan-address: {}", package_id, interface)
}
} }
} }
impl LanAddressPointer { impl LanAddressPointer {
async fn deref<Db: DbHandle>(&self, db: &mut Db) -> Result<Value, ConfigurationError> { async fn deref<Db: DbHandle>(
let addr = crate::db::DatabaseModel::new() &self,
.package_data() db: &mut Db,
.idx_model(&self.package_id) receipts: &InterfaceAddressesReceipt,
.and_then(|pde| pde.installed()) ) -> Result<Value, ConfigurationError> {
.and_then(|installed| installed.interface_addresses().idx_model(&self.interface)) let addr = receipts
.and_then(|addresses| addresses.lan_address()) .interface_addresses
.get(db, true) .get(db, (&self.package_id, &self.interface))
.await .await
.map_err(|e| ConfigurationError::SystemError(Error::from(e)))?; .ok()
.flatten()
.and_then(|x| x.lan_address);
Ok(addr.to_owned().map(Value::String).unwrap_or(Value::Null)) Ok(addr.to_owned().map(Value::String).unwrap_or(Value::Null))
} }
} }
pub struct ConfigPointerReceipts {
interface_addresses_receipt: InterfaceAddressesReceipt,
manifest_volumes: LockReceipt<crate::volume::Volumes, String>,
manifest_version: LockReceipt<crate::util::Version, String>,
config_actions: LockReceipt<super::action::ConfigActions, String>,
}
impl ConfigPointerReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
let interface_addresses_receipt = InterfaceAddressesReceipt::setup(locks);
let manifest_volumes = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest().volumes())
.make_locker(LockType::Read)
.add_to_keys(locks);
let manifest_version = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest().version())
.make_locker(LockType::Read)
.add_to_keys(locks);
let config_actions = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.and_then(|x| x.manifest().config())
.make_locker(LockType::Read)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
interface_addresses_receipt: interface_addresses_receipt(skeleton_key)?,
manifest_volumes: manifest_volumes.verify(skeleton_key)?,
config_actions: config_actions.verify(skeleton_key)?,
manifest_version: manifest_version.verify(skeleton_key)?,
})
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct ConfigPointer { pub struct ConfigPointer {
@@ -1710,40 +1942,22 @@ impl ConfigPointer {
ctx: &RpcContext, ctx: &RpcContext,
db: &mut Db, db: &mut Db,
config_overrides: &BTreeMap<PackageId, Config>, config_overrides: &BTreeMap<PackageId, Config>,
receipts: &ConfigPointerReceipts,
) -> Result<Value, ConfigurationError> { ) -> Result<Value, ConfigurationError> {
if let Some(cfg) = config_overrides.get(&self.package_id) { if let Some(cfg) = config_overrides.get(&self.package_id) {
Ok(self.select(&Value::Object(cfg.clone()))) Ok(self.select(&Value::Object(cfg.clone())))
} else { } else {
let manifest_model: OptionModel<Manifest> = crate::db::DatabaseModel::new() let id = &self.package_id;
.package_data() let version = receipts.manifest_version.get(db, id).await.ok().flatten();
.idx_model(&self.package_id) let cfg_actions = receipts.config_actions.get(db, id).await.ok().flatten();
.and_then(|pde| pde.installed()) let volumes = receipts.manifest_volumes.get(db, id).await.ok().flatten();
.map(|installed| installed.manifest())
.into();
let version = manifest_model
.clone()
.map(|manifest| manifest.version())
.get(db, true)
.await
.map_err(|e| ConfigurationError::SystemError(Error::from(e)))?;
let cfg_actions = manifest_model
.clone()
.and_then(|manifest| manifest.config())
.get(db, true)
.await
.map_err(|e| ConfigurationError::SystemError(Error::from(e)))?;
let volumes = manifest_model
.map(|manifest| manifest.volumes())
.get(db, true)
.await
.map_err(|e| ConfigurationError::SystemError(Error::from(e)))?;
if let (Some(version), Some(cfg_actions), Some(volumes)) = if let (Some(version), Some(cfg_actions), Some(volumes)) =
(&*version, &*cfg_actions, &*volumes) (&version, &cfg_actions, &volumes)
{ {
let cfg_res = cfg_actions let cfg_res = cfg_actions
.get(&ctx, &self.package_id, version, volumes) .get(ctx, &self.package_id, version, volumes)
.await .await
.map_err(|e| ConfigurationError::SystemError(Error::from(e)))?; .map_err(|e| ConfigurationError::SystemError(e))?;
if let Some(cfg) = cfg_res.config { if let Some(cfg) = cfg_res.config {
Ok(self.select(&Value::Object(cfg))) Ok(self.select(&Value::Object(cfg)))
} else { } else {
@@ -1757,13 +1971,12 @@ impl ConfigPointer {
} }
impl fmt::Display for ConfigPointer { impl fmt::Display for ConfigPointer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { let ConfigPointer {
ConfigPointer { package_id,
package_id, selector,
selector, ..
.. } = self;
} => write!(f, "{}: config: {}", package_id, selector), write!(f, "{}: config: {}", package_id, selector)
}
} }
} }
@@ -1909,6 +2122,8 @@ impl ValueSpec for SystemPointerSpec {
_manifest: &Manifest, _manifest: &Manifest,
_config_overrides: &BTreeMap<PackageId, Config>, _config_overrides: &BTreeMap<PackageId, Config>,
value: &mut Value, value: &mut Value,
_receipts: &ConfigPointerReceipts,
) -> Result<(), ConfigurationError> { ) -> Result<(), ConfigurationError> {
*value = self.deref(db).await?; *value = self.deref(db).await?;
Ok(()) Ok(())
@@ -1926,3 +2141,42 @@ impl ValueSpec for SystemPointerSpec {
false false
} }
} }
#[test]
fn invalid_regex_produces_error() {
assert!(
serde_yaml::from_reader::<_, ConfigSpec>(std::io::Cursor::new(include_bytes!(
"../../test/config-spec/lnd-invalid-regex.yaml"
)))
.is_err()
)
}
#[test]
fn missing_pattern_description_produces_error() {
assert!(
serde_yaml::from_reader::<_, ConfigSpec>(std::io::Cursor::new(include_bytes!(
"../../test/config-spec/lnd-missing-pattern-description.yaml"
)))
.is_err()
)
}
#[test]
fn missing_pattern_produces_error() {
assert!(
serde_yaml::from_reader::<_, ConfigSpec>(std::io::Cursor::new(include_bytes!(
"../../test/config-spec/lnd-missing-pattern.yaml"
)))
.is_err()
)
}
#[test]
fn regex_control() {
let spec = serde_yaml::from_reader::<_, ConfigSpec>(std::io::Cursor::new(include_bytes!(
"../../test/config-spec/lnd-correct.yaml"
)))
.unwrap();
println!("{}", serde_json::to_string_pretty(&spec).unwrap());
}

View File

@@ -16,7 +16,7 @@ impl CharSet {
self.0.iter().any(|r| r.0.contains(c)) self.0.iter().any(|r| r.0.contains(c))
} }
pub fn gen<R: Rng>(&self, rng: &mut R) -> char { pub fn gen<R: Rng>(&self, rng: &mut R) -> char {
let mut idx = rng.gen_range(0, self.1); let mut idx = rng.gen_range(0..self.1);
for r in &self.0 { for r in &self.0 {
if idx < r.1 { if idx < r.1 {
return std::convert::TryFrom::try_from( return std::convert::TryFrom::try_from(

View File

@@ -15,6 +15,7 @@ use rpc_toolkit::Context;
use serde::Deserialize; use serde::Deserialize;
use tracing::instrument; use tracing::instrument;
use crate::util::config::{load_config_from_paths, local_config_path};
use crate::ResultExt; use crate::ResultExt;
#[derive(Debug, Default, Deserialize)] #[derive(Debug, Default, Deserialize)]
@@ -23,6 +24,7 @@ pub struct CliContextConfig {
pub bind_rpc: Option<SocketAddr>, pub bind_rpc: Option<SocketAddr>,
pub host: Option<Url>, pub host: Option<Url>,
#[serde(deserialize_with = "crate::util::serde::deserialize_from_str_opt")] #[serde(deserialize_with = "crate::util::serde::deserialize_from_str_opt")]
#[serde(default)]
pub proxy: Option<Url>, pub proxy: Option<Url>,
pub cookie_path: Option<PathBuf>, pub cookie_path: Option<PathBuf>,
} }
@@ -38,6 +40,10 @@ pub struct CliContextSeed {
impl Drop for CliContextSeed { impl Drop for CliContextSeed {
fn drop(&mut self) { fn drop(&mut self) {
let tmp = format!("{}.tmp", self.cookie_path.display()); let tmp = format!("{}.tmp", self.cookie_path.display());
let parent_dir = self.cookie_path.parent().unwrap_or(Path::new("/"));
if !parent_dir.exists() {
std::fs::create_dir_all(&parent_dir).unwrap();
}
let mut writer = fd_lock_rs::FdLock::lock( let mut writer = fd_lock_rs::FdLock::lock(
File::create(&tmp).unwrap(), File::create(&tmp).unwrap(),
fd_lock_rs::LockType::Exclusive, fd_lock_rs::LockType::Exclusive,
@@ -60,16 +66,16 @@ impl CliContext {
/// BLOCKING /// BLOCKING
#[instrument(skip(matches))] #[instrument(skip(matches))]
pub fn init(matches: &ArgMatches) -> Result<Self, crate::Error> { pub fn init(matches: &ArgMatches) -> Result<Self, crate::Error> {
let cfg_path = Path::new(matches.value_of("config").unwrap_or(crate::CONFIG_PATH)); let local_config_path = local_config_path();
let base = if cfg_path.exists() { let base: CliContextConfig = load_config_from_paths(
serde_yaml::from_reader( matches
File::open(cfg_path) .values_of("config")
.with_ctx(|_| (crate::ErrorKind::Filesystem, cfg_path.display().to_string()))?, .into_iter()
) .flatten()
.with_kind(crate::ErrorKind::Deserialization)? .map(|p| Path::new(p))
} else { .chain(local_config_path.as_deref().into_iter())
CliContextConfig::default() .chain(std::iter::once(Path::new(crate::util::config::CONFIG_PATH))),
}; )?;
let mut url = if let Some(host) = matches.value_of("host") { let mut url = if let Some(host) = matches.value_of("host") {
host.parse()? host.parse()?
} else if let Some(host) = base.host { } else if let Some(host) = base.host {
@@ -88,7 +94,9 @@ impl CliContext {
}; };
let cookie_path = base.cookie_path.unwrap_or_else(|| { let cookie_path = base.cookie_path.unwrap_or_else(|| {
cfg_path local_config_path
.as_deref()
.unwrap_or_else(|| Path::new(crate::util::config::CONFIG_PATH))
.parent() .parent()
.unwrap_or(Path::new("/")) .unwrap_or(Path::new("/"))
.join(".cookies.json") .join(".cookies.json")
@@ -149,3 +157,13 @@ impl Context for CliContext {
&self.0.client &self.0.client
} }
} }
/// When we had an empty proxy the system wasn't working like it used to, which allowed empty proxy
#[test]
fn test_cli_proxy_empty() {
serde_yaml::from_str::<CliContextConfig>(
"
bind_rpc:
",
)
.unwrap();
}

View File

@@ -28,7 +28,7 @@ impl DiagnosticContextConfig {
let cfg_path = path let cfg_path = path
.as_ref() .as_ref()
.map(|p| p.as_ref()) .map(|p| p.as_ref())
.unwrap_or(Path::new(crate::CONFIG_PATH)); .unwrap_or(Path::new(crate::util::config::CONFIG_PATH));
if let Some(f) = File::maybe_open(cfg_path) if let Some(f) = File::maybe_open(cfg_path)
.await .await
.with_ctx(|_| (crate::ErrorKind::Filesystem, cfg_path.display().to_string()))? .with_ctx(|_| (crate::ErrorKind::Filesystem, cfg_path.display().to_string()))?

View File

@@ -7,9 +7,9 @@ use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use bollard::Docker; use bollard::Docker;
use color_eyre::eyre::eyre; use helpers::to_tmp_path;
use patch_db::json_ptr::JsonPointer; use patch_db::json_ptr::JsonPointer;
use patch_db::{DbHandle, LockType, PatchDb, Revision}; use patch_db::{DbHandle, LockReceipt, LockType, PatchDb, Revision};
use reqwest::Url; use reqwest::Url;
use rpc_toolkit::url::Host; use rpc_toolkit::url::Host;
use rpc_toolkit::Context; use rpc_toolkit::Context;
@@ -24,7 +24,7 @@ use tracing::instrument;
use crate::core::rpc_continuations::{RequestGuid, RpcContinuation}; use crate::core::rpc_continuations::{RequestGuid, RpcContinuation};
use crate::db::model::{Database, InstalledPackageDataEntry, PackageDataEntry}; use crate::db::model::{Database, InstalledPackageDataEntry, PackageDataEntry};
use crate::hostname::{derive_hostname, derive_id, get_product_key}; use crate::hostname::{derive_hostname, derive_id, get_product_key};
use crate::install::cleanup::{cleanup_failed, uninstall}; use crate::install::cleanup::{cleanup_failed, uninstall, CleanupFailedReceipts};
use crate::manager::ManagerMap; use crate::manager::ManagerMap;
use crate::middleware::auth::HashSessionToken; use crate::middleware::auth::HashSessionToken;
use crate::net::tor::os_key; use crate::net::tor::os_key;
@@ -36,7 +36,7 @@ use crate::shutdown::Shutdown;
use crate::status::{MainStatus, Status}; use crate::status::{MainStatus, Status};
use crate::util::io::from_yaml_async_reader; use crate::util::io::from_yaml_async_reader;
use crate::util::{AsyncFileExt, Invoke}; use crate::util::{AsyncFileExt, Invoke};
use crate::{Error, ResultExt}; use crate::{Error, ErrorKind, ResultExt};
#[derive(Debug, Default, Deserialize)] #[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
@@ -46,6 +46,7 @@ pub struct RpcContextConfig {
pub bind_static: Option<SocketAddr>, pub bind_static: Option<SocketAddr>,
pub tor_control: Option<SocketAddr>, pub tor_control: Option<SocketAddr>,
pub tor_socks: Option<SocketAddr>, pub tor_socks: Option<SocketAddr>,
pub dns_bind: Option<Vec<SocketAddr>>,
pub revision_cache_size: Option<usize>, pub revision_cache_size: Option<usize>,
pub datadir: Option<PathBuf>, pub datadir: Option<PathBuf>,
pub log_server: Option<Url>, pub log_server: Option<Url>,
@@ -55,7 +56,7 @@ impl RpcContextConfig {
let cfg_path = path let cfg_path = path
.as_ref() .as_ref()
.map(|p| p.as_ref()) .map(|p| p.as_ref())
.unwrap_or(Path::new(crate::CONFIG_PATH)); .unwrap_or(Path::new(crate::util::config::CONFIG_PATH));
if let Some(f) = File::maybe_open(cfg_path) if let Some(f) = File::maybe_open(cfg_path)
.await .await
.with_ctx(|_| (crate::ErrorKind::Filesystem, cfg_path.display().to_string()))? .with_ctx(|_| (crate::ErrorKind::Filesystem, cfg_path.display().to_string()))?
@@ -132,6 +133,71 @@ pub struct RpcContextSeed {
pub wifi_manager: Arc<RwLock<WpaCli>>, pub wifi_manager: Arc<RwLock<WpaCli>>,
} }
pub struct RpcCleanReceipts {
cleanup_receipts: CleanupFailedReceipts,
packages: LockReceipt<crate::db::model::AllPackageData, ()>,
package: LockReceipt<crate::db::model::PackageDataEntry, String>,
}
impl RpcCleanReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
let cleanup_receipts = CleanupFailedReceipts::setup(locks);
let packages = crate::db::DatabaseModel::new()
.package_data()
.make_locker(LockType::Write)
.add_to_keys(locks);
let package = crate::db::DatabaseModel::new()
.package_data()
.star()
.make_locker(LockType::Write)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
cleanup_receipts: cleanup_receipts(skeleton_key)?,
packages: packages.verify(skeleton_key)?,
package: package.verify(skeleton_key)?,
})
}
}
}
pub struct RpcSetNginxReceipts {
server_info: LockReceipt<crate::db::model::ServerInfo, ()>,
}
impl RpcSetNginxReceipts {
pub async fn new(db: &'_ mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
let server_info = crate::db::DatabaseModel::new()
.server_info()
.make_locker(LockType::Read)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
server_info: server_info.verify(skeleton_key)?,
})
}
}
}
#[derive(Clone)] #[derive(Clone)]
pub struct RpcContext(Arc<RpcContextSeed>); pub struct RpcContext(Arc<RpcContextSeed>);
impl RpcContext { impl RpcContext {
@@ -158,6 +224,10 @@ impl RpcContext {
crate::net::tor::os_key(&mut secret_store.acquire().await?).await?, crate::net::tor::os_key(&mut secret_store.acquire().await?).await?,
base.tor_control base.tor_control
.unwrap_or(SocketAddr::from(([127, 0, 0, 1], 9051))), .unwrap_or(SocketAddr::from(([127, 0, 0, 1], 9051))),
base.dns_bind
.as_ref()
.map(|v| v.as_slice())
.unwrap_or(&[SocketAddr::from(([127, 0, 0, 1], 53))]),
secret_store.clone(), secret_store.clone(),
None, None,
) )
@@ -203,13 +273,15 @@ impl RpcContext {
tracing::info!("Initialized Package Managers"); tracing::info!("Initialized Package Managers");
Ok(res) Ok(res)
} }
#[instrument(skip(self, db))]
pub async fn set_nginx_conf<Db: DbHandle>(&self, db: &mut Db) -> Result<(), Error> { #[instrument(skip(self, db, receipts))]
pub async fn set_nginx_conf<Db: DbHandle>(
&self,
db: &mut Db,
receipts: RpcSetNginxReceipts,
) -> Result<(), Error> {
tokio::fs::write("/etc/nginx/sites-available/default", { tokio::fs::write("/etc/nginx/sites-available/default", {
let info = crate::db::DatabaseModel::new() let info = receipts.server_info.get(db).await?;
.server_info()
.get(db, true)
.await?;
format!( format!(
include_str!("../nginx/main-ui.conf.template"), include_str!("../nginx/main-ui.conf.template"),
lan_hostname = info.lan_address.host_str().unwrap(), lan_hostname = info.lan_address.host_str().unwrap(),
@@ -237,34 +309,19 @@ impl RpcContext {
self.is_closed.store(true, Ordering::SeqCst); self.is_closed.store(true, Ordering::SeqCst);
Ok(()) Ok(())
} }
#[instrument(skip(self))] #[instrument(skip(self))]
pub async fn cleanup(&self) -> Result<(), Error> { pub async fn cleanup(&self) -> Result<(), Error> {
let mut db = self.db.handle(); let mut db = self.db.handle();
crate::db::DatabaseModel::new() let receipts = RpcCleanReceipts::new(&mut db).await?;
.package_data() for (package_id, package) in receipts.packages.get(&mut db).await?.0 {
.lock(&mut db, LockType::Write)
.await?;
for package_id in crate::db::DatabaseModel::new()
.package_data()
.keys(&mut db, true)
.await?
{
if let Err(e) = async { if let Err(e) = async {
let mut pde = crate::db::DatabaseModel::new() match package {
.package_data()
.idx_model(&package_id)
.get_mut(&mut db)
.await?;
match pde.as_mut().ok_or_else(|| {
Error::new(
eyre!("Node does not exist: /package-data/{}", package_id),
crate::ErrorKind::Database,
)
})? {
PackageDataEntry::Installing { .. } PackageDataEntry::Installing { .. }
| PackageDataEntry::Restoring { .. } | PackageDataEntry::Restoring { .. }
| PackageDataEntry::Updating { .. } => { | PackageDataEntry::Updating { .. } => {
cleanup_failed(self, &mut db, &package_id).await?; cleanup_failed(self, &mut db, &package_id, &receipts.cleanup_receipts)
.await?;
} }
PackageDataEntry::Removing { .. } => { PackageDataEntry::Removing { .. } => {
uninstall( uninstall(
@@ -276,30 +333,48 @@ impl RpcContext {
.await?; .await?;
} }
PackageDataEntry::Installed { PackageDataEntry::Installed {
installed: installed,
InstalledPackageDataEntry { static_files,
status: Status { main, .. }, manifest,
..
},
..
} => { } => {
let new_main = match std::mem::replace( for (volume_id, volume_info) in &*manifest.volumes {
main, let tmp_path = to_tmp_path(volume_info.path_for(
MainStatus::Stopped, /* placeholder */ &self.datadir,
) { &package_id,
&manifest.version,
&volume_id,
))
.with_kind(ErrorKind::Filesystem)?;
if tokio::fs::metadata(&tmp_path).await.is_ok() {
tokio::fs::remove_dir_all(&tmp_path).await?;
}
}
let status = installed.status;
let main = match status.main {
MainStatus::BackingUp { started, .. } => { MainStatus::BackingUp { started, .. } => {
if let Some(_) = started { if let Some(_) = started {
MainStatus::Starting MainStatus::Starting { restarting: false }
} else { } else {
MainStatus::Stopped MainStatus::Stopped
} }
} }
MainStatus::Running { .. } => MainStatus::Starting, MainStatus::Running { .. } => {
a => a, MainStatus::Starting { restarting: false }
}
a => a.clone(),
}; };
*main = new_main; let new_package = PackageDataEntry::Installed {
installed: InstalledPackageDataEntry {
pde.save(&mut db).await?; status: Status { main, ..status },
..installed
},
static_files,
manifest,
};
receipts
.package
.set(&mut db, new_package, &package_id)
.await?;
} }
} }
Ok::<_, Error>(()) Ok::<_, Error>(())

View File

@@ -1,5 +1,3 @@
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
@@ -9,6 +7,7 @@ use rpc_toolkit::Context;
use serde::Deserialize; use serde::Deserialize;
use tracing::instrument; use tracing::instrument;
use crate::util::config::{load_config_from_paths, local_config_path};
use crate::{Error, ResultExt}; use crate::{Error, ResultExt};
#[derive(Debug, Default, Deserialize)] #[derive(Debug, Default, Deserialize)]
@@ -28,22 +27,24 @@ impl SdkContext {
/// BLOCKING /// BLOCKING
#[instrument(skip(matches))] #[instrument(skip(matches))]
pub fn init(matches: &ArgMatches) -> Result<Self, crate::Error> { pub fn init(matches: &ArgMatches) -> Result<Self, crate::Error> {
let cfg_path = Path::new(matches.value_of("config").unwrap_or(crate::CONFIG_PATH)); let local_config_path = local_config_path();
let base = if cfg_path.exists() { let base: SdkContextConfig = load_config_from_paths(
serde_yaml::from_reader( matches
File::open(cfg_path) .values_of("config")
.with_ctx(|_| (crate::ErrorKind::Filesystem, cfg_path.display().to_string()))?, .into_iter()
) .flatten()
.with_kind(crate::ErrorKind::Deserialization)? .map(|p| Path::new(p))
} else { .chain(local_config_path.as_deref().into_iter())
SdkContextConfig::default() .chain(std::iter::once(Path::new(crate::util::config::CONFIG_PATH))),
}; )?;
Ok(SdkContext(Arc::new(SdkContextSeed { Ok(SdkContext(Arc::new(SdkContextSeed {
developer_key_path: base.developer_key_path.unwrap_or_else(|| { developer_key_path: base.developer_key_path.unwrap_or_else(|| {
cfg_path local_config_path
.as_deref()
.unwrap_or_else(|| Path::new(crate::util::config::CONFIG_PATH))
.parent() .parent()
.unwrap_or(Path::new("/")) .unwrap_or(Path::new("/"))
.join(".developer_key") .join("developer.key.pem")
}), }),
}))) })))
} }
@@ -53,9 +54,17 @@ impl SdkContext {
if !self.developer_key_path.exists() { if !self.developer_key_path.exists() {
return Err(Error::new(eyre!("Developer Key does not exist! Please run `embassy-sdk init` before running this command."), crate::ErrorKind::Uninitialized)); return Err(Error::new(eyre!("Developer Key does not exist! Please run `embassy-sdk init` before running this command."), crate::ErrorKind::Uninitialized));
} }
let mut keypair_buf = [0; ed25519_dalek::KEYPAIR_LENGTH]; let pair = <ed25519::KeypairBytes as ed25519::pkcs8::DecodePrivateKey>::from_pkcs8_pem(
File::open(&self.developer_key_path)?.read_exact(&mut keypair_buf)?; &std::fs::read_to_string(&self.developer_key_path)?,
Ok(ed25519_dalek::Keypair::from_bytes(&keypair_buf)?) )
.with_kind(crate::ErrorKind::Pem)?;
let secret = ed25519_dalek::SecretKey::from_bytes(&pair.secret_key[..])?;
let public = if let Some(public) = pair.public_key {
ed25519_dalek::PublicKey::from_bytes(&public[..])?
} else {
(&secret).into()
};
Ok(ed25519_dalek::Keypair { secret, public })
} }
} }
impl std::ops::Deref for SdkContext { impl std::ops::Deref for SdkContext {

View File

@@ -45,7 +45,7 @@ impl SetupContextConfig {
let cfg_path = path let cfg_path = path
.as_ref() .as_ref()
.map(|p| p.as_ref()) .map(|p| p.as_ref())
.unwrap_or(Path::new(crate::CONFIG_PATH)); .unwrap_or(Path::new(crate::util::config::CONFIG_PATH));
if let Some(f) = File::maybe_open(cfg_path) if let Some(f) = File::maybe_open(cfg_path)
.await .await
.with_ctx(|_| (crate::ErrorKind::Filesystem, cfg_path.display().to_string()))? .with_ctx(|_| (crate::ErrorKind::Filesystem, cfg_path.display().to_string()))?

View File

@@ -1,7 +1,7 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use patch_db::{DbHandle, LockType}; use patch_db::{DbHandle, LockReceipt, LockType};
use rpc_toolkit::command; use rpc_toolkit::command;
use tracing::instrument; use tracing::instrument;
@@ -9,13 +9,57 @@ use crate::context::RpcContext;
use crate::db::util::WithRevision; use crate::db::util::WithRevision;
use crate::dependencies::{ use crate::dependencies::{
break_all_dependents_transitive, heal_all_dependents_transitive, BreakageRes, DependencyError, break_all_dependents_transitive, heal_all_dependents_transitive, BreakageRes, DependencyError,
TaggedDependencyError, DependencyReceipt, TaggedDependencyError,
}; };
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::status::MainStatus; use crate::status::MainStatus;
use crate::util::display_none; use crate::util::display_none;
use crate::util::serde::display_serializable; use crate::util::serde::display_serializable;
use crate::{Error, ResultExt}; use crate::Error;
#[derive(Clone)]
pub struct StartReceipts {
dependency_receipt: DependencyReceipt,
status: LockReceipt<MainStatus, ()>,
version: LockReceipt<crate::util::Version, ()>,
}
impl StartReceipts {
pub async fn new(db: &mut impl DbHandle, id: &PackageId) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks, id);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
id: &PackageId,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
let dependency_receipt = DependencyReceipt::setup(locks);
let status = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|x| x.installed())
.map(|x| x.status().main())
.make_locker(LockType::Write)
.add_to_keys(locks);
let version = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|x| x.installed())
.map(|x| x.manifest().version())
.make_locker(LockType::Read)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
dependency_receipt: dependency_receipt(skeleton_key)?,
status: status.verify(skeleton_key)?,
version: version.verify(skeleton_key)?,
})
}
}
}
#[command(display(display_none))] #[command(display(display_none))]
#[instrument(skip(ctx))] #[instrument(skip(ctx))]
@@ -25,37 +69,16 @@ pub async fn start(
) -> Result<WithRevision<()>, Error> { ) -> Result<WithRevision<()>, Error> {
let mut db = ctx.db.handle(); let mut db = ctx.db.handle();
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
crate::db::DatabaseModel::new() let receipts = StartReceipts::new(&mut tx, &id).await?;
.package_data() let version = receipts.version.get(&mut tx).await?;
.lock(&mut tx, LockType::Write) receipts
.status
.set(&mut tx, MainStatus::Starting { restarting: false })
.await?; .await?;
let installed = crate::db::DatabaseModel::new() heal_all_dependents_transitive(&ctx, &mut tx, &id, &receipts.dependency_receipt).await?;
.package_data()
.idx_model(&id)
.and_then(|pkg| pkg.installed())
.expect(&mut tx)
.await
.with_ctx(|_| {
(
crate::ErrorKind::NotFound,
format!("{} is not installed", id),
)
})?;
installed.lock(&mut tx, LockType::Read).await?;
let version = installed
.clone()
.manifest()
.version()
.get(&mut tx, true)
.await?
.to_owned();
let mut status = installed.status().main().get_mut(&mut tx).await?;
*status = MainStatus::Starting;
status.save(&mut tx).await?;
heal_all_dependents_transitive(&ctx, &mut tx, &id).await?;
let revision = tx.commit(None).await?; let revision = tx.commit(None).await?;
drop(receipts);
ctx.managers ctx.managers
.get(&(id, version)) .get(&(id, version))
@@ -69,6 +92,40 @@ pub async fn start(
response: (), response: (),
}) })
} }
#[derive(Clone)]
pub struct StopReceipts {
breaks: crate::dependencies::BreakTransitiveReceipts,
status: LockReceipt<MainStatus, ()>,
}
impl StopReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle, id: &PackageId) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks, id);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
id: &PackageId,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
let breaks = crate::dependencies::BreakTransitiveReceipts::setup(locks);
let status = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|x| x.installed())
.map(|x| x.status().main())
.make_locker(LockType::Write)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
breaks: breaks(skeleton_key)?,
status: status.verify(skeleton_key)?,
})
}
}
}
#[instrument(skip(db))] #[instrument(skip(db))]
async fn stop_common<Db: DbHandle>( async fn stop_common<Db: DbHandle>(
@@ -77,27 +134,18 @@ async fn stop_common<Db: DbHandle>(
breakages: &mut BTreeMap<PackageId, TaggedDependencyError>, breakages: &mut BTreeMap<PackageId, TaggedDependencyError>,
) -> Result<(), Error> { ) -> Result<(), Error> {
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
let mut status = crate::db::DatabaseModel::new() let receipts = StopReceipts::new(&mut tx, id).await?;
.package_data() receipts.status.set(&mut tx, MainStatus::Stopping).await?;
.idx_model(&id)
.and_then(|pkg| pkg.installed())
.expect(&mut tx)
.await
.with_ctx(|_| {
(
crate::ErrorKind::NotFound,
format!("{} is not installed", id),
)
})?
.status()
.main()
.get_mut(&mut tx)
.await?;
*status = MainStatus::Stopping;
status.save(&mut tx).await?;
tx.save().await?; tx.save().await?;
break_all_dependents_transitive(db, &id, DependencyError::NotRunning, breakages).await?; break_all_dependents_transitive(
db,
id,
DependencyError::NotRunning,
breakages,
&receipts.breaks,
)
.await?;
Ok(()) Ok(())
} }
@@ -136,3 +184,33 @@ pub async fn stop_impl(ctx: RpcContext, id: PackageId) -> Result<WithRevision<()
response: (), response: (),
}) })
} }
#[command(display(display_none))]
pub async fn restart(
#[context] ctx: RpcContext,
#[arg] id: PackageId,
) -> Result<WithRevision<()>, Error> {
let mut db = ctx.db.handle();
let mut tx = db.begin().await?;
let mut status = crate::db::DatabaseModel::new()
.package_data()
.idx_model(&id)
.and_then(|pde| pde.installed())
.map(|i| i.status().main())
.get_mut(&mut tx)
.await?;
if !matches!(&*status, Some(MainStatus::Running { .. })) {
return Err(Error::new(
eyre!("{} is not running", id),
crate::ErrorKind::InvalidRequest,
));
}
*status = Some(MainStatus::Restarting);
status.save(&mut tx).await?;
Ok(WithRevision {
revision: tx.commit(None).await?,
response: (),
})
}

View File

@@ -51,7 +51,7 @@ impl Database {
.parse() .parse()
.unwrap(), .unwrap(),
status_info: ServerStatus { status_info: ServerStatus {
backing_up: false, backup_progress: None,
updated: false, updated: false,
update_progress: None, update_progress: None,
}, },
@@ -99,10 +99,16 @@ pub struct ServerInfo {
pub password_hash: String, pub password_hash: String,
} }
#[derive(Debug, Default, Deserialize, Serialize, HasModel)]
pub struct BackupProgress {
pub complete: bool,
}
#[derive(Debug, Default, Deserialize, Serialize, HasModel)] #[derive(Debug, Default, Deserialize, Serialize, HasModel)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct ServerStatus { pub struct ServerStatus {
pub backing_up: bool, #[model]
pub backup_progress: Option<BTreeMap<PackageId, BackupProgress>>,
pub updated: bool, pub updated: bool,
#[model] #[model]
pub update_progress: Option<UpdateProgress>, pub update_progress: Option<UpdateProgress>,
@@ -260,17 +266,66 @@ pub struct InstalledPackageDataEntry {
#[model] #[model]
pub manifest: Manifest, pub manifest: Manifest,
pub last_backup: Option<DateTime<Utc>>, pub last_backup: Option<DateTime<Utc>>,
#[model]
pub system_pointers: Vec<SystemPointerSpec>, pub system_pointers: Vec<SystemPointerSpec>,
#[model] #[model]
pub dependency_info: BTreeMap<PackageId, StaticDependencyInfo>, pub dependency_info: BTreeMap<PackageId, StaticDependencyInfo>,
#[model] #[model]
pub current_dependents: BTreeMap<PackageId, CurrentDependencyInfo>, pub current_dependents: CurrentDependents,
#[model] #[model]
pub current_dependencies: BTreeMap<PackageId, CurrentDependencyInfo>, pub current_dependencies: CurrentDependencies,
#[model] #[model]
pub interface_addresses: InterfaceAddressMap, pub interface_addresses: InterfaceAddressMap,
} }
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CurrentDependents(pub BTreeMap<PackageId, CurrentDependencyInfo>);
impl CurrentDependents {
pub fn map(
mut self,
transform: impl Fn(
BTreeMap<PackageId, CurrentDependencyInfo>,
) -> BTreeMap<PackageId, CurrentDependencyInfo>,
) -> Self {
self.0 = transform(self.0);
self
}
}
impl Map for CurrentDependents {
type Key = PackageId;
type Value = CurrentDependencyInfo;
fn get(&self, key: &Self::Key) -> Option<&Self::Value> {
self.0.get(key)
}
}
impl HasModel for CurrentDependents {
type Model = MapModel<Self>;
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct CurrentDependencies(pub BTreeMap<PackageId, CurrentDependencyInfo>);
impl CurrentDependencies {
pub fn map(
mut self,
transform: impl Fn(
BTreeMap<PackageId, CurrentDependencyInfo>,
) -> BTreeMap<PackageId, CurrentDependencyInfo>,
) -> Self {
self.0 = transform(self.0);
self
}
}
impl Map for CurrentDependencies {
type Key = PackageId;
type Value = CurrentDependencyInfo;
fn get(&self, key: &Self::Key) -> Option<&Self::Value> {
self.0.get(key)
}
}
impl HasModel for CurrentDependencies {
type Model = MapModel<Self>;
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, HasModel)] #[derive(Clone, Debug, Default, Deserialize, Serialize, HasModel)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct StaticDependencyInfo { pub struct StaticDependencyInfo {

View File

@@ -1,25 +1,75 @@
use patch_db::DbHandle; use patch_db::{DbHandle, LockReceipt, LockTargetId, LockType, Verifier};
use crate::s9pk::manifest::{Manifest, PackageId}; use crate::s9pk::manifest::{Manifest, PackageId};
use crate::Error; use crate::Error;
pub async fn get_packages<Db: DbHandle>(db: &mut Db) -> Result<Vec<PackageId>, Error> { pub struct PackageReceipts {
let packages = crate::db::DatabaseModel::new() package_data: LockReceipt<super::model::AllPackageData, ()>,
.package_data() }
.get(db, false)
.await?; impl PackageReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(locks: &mut Vec<LockTargetId>) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let package_data = crate::db::DatabaseModel::new()
.package_data()
.make_locker(LockType::Read)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
package_data: package_data.verify(&skeleton_key)?,
})
}
}
}
pub async fn get_packages<Db: DbHandle>(
db: &mut Db,
receipts: &PackageReceipts,
) -> Result<Vec<PackageId>, Error> {
let packages = receipts.package_data.get(db).await?;
Ok(packages.0.keys().cloned().collect()) Ok(packages.0.keys().cloned().collect())
} }
pub struct ManifestReceipts {
manifest: LockReceipt<Manifest, String>,
}
impl ManifestReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle, id: &PackageId) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks, id);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<LockTargetId>,
_id: &PackageId,
) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let manifest = crate::db::DatabaseModel::new()
.package_data()
.star()
.manifest()
.make_locker(LockType::Read)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
manifest: manifest.verify(&skeleton_key)?,
})
}
}
}
pub async fn get_manifest<Db: DbHandle>( pub async fn get_manifest<Db: DbHandle>(
db: &mut Db, db: &mut Db,
pkg: &PackageId, pkg: &PackageId,
receipts: &ManifestReceipts,
) -> Result<Option<Manifest>, Error> { ) -> Result<Option<Manifest>, Error> {
let mpde = crate::db::DatabaseModel::new() Ok(receipts.manifest.get(db, pkg).await?)
.package_data()
.idx_model(pkg)
.get(db, false)
.await?
.into_owned();
Ok(mpde.map(|pde| pde.manifest()))
} }

View File

@@ -6,19 +6,20 @@ use color_eyre::eyre::eyre;
use emver::VersionRange; use emver::VersionRange;
use futures::future::BoxFuture; use futures::future::BoxFuture;
use futures::FutureExt; use futures::FutureExt;
use patch_db::{DbHandle, HasModel, LockType, Map, MapModel, PatchDbHandle}; use patch_db::{
DbHandle, HasModel, LockReceipt, LockTargetId, LockType, Map, MapModel, PatchDbHandle, Verifier,
};
use rand::SeedableRng; use rand::SeedableRng;
use rpc_toolkit::command; use rpc_toolkit::command;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::instrument; use tracing::instrument;
use crate::action::{ActionImplementation, NoOutput}; use crate::config::action::{ConfigActions, ConfigRes};
use crate::config::action::ConfigRes;
use crate::config::spec::PackagePointerSpec; use crate::config::spec::PackagePointerSpec;
use crate::config::{Config, ConfigSpec}; use crate::config::{not_found, Config, ConfigReceipts, ConfigSpec};
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::db::model::{CurrentDependencyInfo, InstalledPackageDataEntry}; use crate::db::model::{CurrentDependencies, CurrentDependents, InstalledPackageDataEntry};
use crate::error::ResultExt; use crate::procedure::{NoOutput, PackageProcedure, ProcedureName};
use crate::s9pk::manifest::{Manifest, PackageId}; use crate::s9pk::manifest::{Manifest, PackageId};
use crate::status::health_check::{HealthCheckId, HealthCheckResult}; use crate::status::health_check::{HealthCheckId, HealthCheckResult};
use crate::status::{MainStatus, Status}; use crate::status::{MainStatus, Status};
@@ -55,6 +56,72 @@ pub enum DependencyError {
Transitive, // { "type": "transitive" } Transitive, // { "type": "transitive" }
} }
#[derive(Clone)]
pub struct TryHealReceipts {
status: LockReceipt<Status, String>,
manifest: LockReceipt<Manifest, String>,
manifest_version: LockReceipt<Version, String>,
current_dependencies: LockReceipt<CurrentDependencies, String>,
dependency_errors: LockReceipt<DependencyErrors, String>,
}
impl TryHealReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(locks: &mut Vec<LockTargetId>) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let manifest_version = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest().version())
.make_locker(LockType::Write)
.add_to_keys(locks);
let status = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.status())
.make_locker(LockType::Write)
.add_to_keys(locks);
let manifest = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest())
.make_locker(LockType::Write)
.add_to_keys(locks);
let current_dependencies = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.current_dependencies())
.make_locker(LockType::Write)
.add_to_keys(locks);
let dependency_errors = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.status().dependency_errors())
.make_locker(LockType::Write)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
status: status.verify(skeleton_key)?,
manifest_version: manifest_version.verify(skeleton_key)?,
current_dependencies: current_dependencies.verify(skeleton_key)?,
manifest: manifest.verify(skeleton_key)?,
dependency_errors: dependency_errors.verify(skeleton_key)?,
})
}
}
}
impl DependencyError { impl DependencyError {
pub fn cmp_priority(&self, other: &DependencyError) -> std::cmp::Ordering { pub fn cmp_priority(&self, other: &DependencyError) -> std::cmp::Ordering {
use std::cmp::Ordering::*; use std::cmp::Ordering::*;
@@ -114,7 +181,7 @@ impl DependencyError {
(DependencyError::Transitive, _) => DependencyError::Transitive, (DependencyError::Transitive, _) => DependencyError::Transitive,
} }
} }
#[instrument(skip(ctx, db))] #[instrument(skip(ctx, db, receipts))]
pub fn try_heal<'a, Db: DbHandle>( pub fn try_heal<'a, Db: DbHandle>(
self, self,
ctx: &'a RpcContext, ctx: &'a RpcContext,
@@ -123,42 +190,33 @@ impl DependencyError {
dependency: &'a PackageId, dependency: &'a PackageId,
mut dependency_config: Option<Config>, mut dependency_config: Option<Config>,
info: &'a DepInfo, info: &'a DepInfo,
receipts: &'a TryHealReceipts,
) -> BoxFuture<'a, Result<Option<Self>, Error>> { ) -> BoxFuture<'a, Result<Option<Self>, Error>> {
async move { async move {
Ok(match self { Ok(match self {
DependencyError::NotInstalled => { DependencyError::NotInstalled => {
if crate::db::DatabaseModel::new() if receipts.status.get(db, dependency).await?.is_some() {
.package_data()
.idx_model(dependency)
.and_then(|m| m.installed())
.exists(db, true)
.await?
{
DependencyError::IncorrectVersion { DependencyError::IncorrectVersion {
expected: info.version.clone(), expected: info.version.clone(),
received: Default::default(), received: Default::default(),
} }
.try_heal(ctx, db, id, dependency, dependency_config, info) .try_heal(ctx, db, id, dependency, dependency_config, info, receipts)
.await? .await?
} else { } else {
Some(DependencyError::NotInstalled) Some(DependencyError::NotInstalled)
} }
} }
DependencyError::IncorrectVersion { expected, .. } => { DependencyError::IncorrectVersion { expected, .. } => {
let version: Version = crate::db::DatabaseModel::new() let version: Version = receipts
.package_data() .manifest_version
.idx_model(dependency) .get(db, dependency)
.and_then(|m| m.installed())
.map(|m| m.manifest().version())
.get(db, true)
.await? .await?
.into_owned()
.unwrap_or_default(); .unwrap_or_default();
if version.satisfies(&expected) { if version.satisfies(&expected) {
DependencyError::ConfigUnsatisfied { DependencyError::ConfigUnsatisfied {
error: String::new(), error: String::new(),
} }
.try_heal(ctx, db, id, dependency, dependency_config, info) .try_heal(ctx, db, id, dependency, dependency_config, info, receipts)
.await? .await?
} else { } else {
Some(DependencyError::IncorrectVersion { Some(DependencyError::IncorrectVersion {
@@ -168,24 +226,14 @@ impl DependencyError {
} }
} }
DependencyError::ConfigUnsatisfied { .. } => { DependencyError::ConfigUnsatisfied { .. } => {
let dependent_manifest = crate::db::DatabaseModel::new() let dependent_manifest =
.package_data() receipts.manifest.get(db, id).await?.ok_or_else(not_found)?;
.idx_model(id) let dependency_manifest = receipts
.and_then(|m| m.installed()) .manifest
.map::<_, Manifest>(|m| m.manifest()) .get(db, dependency)
.expect(db)
.await? .await?
.get(db, true) .ok_or_else(not_found)?;
.await?;
let dependency_manifest = crate::db::DatabaseModel::new()
.package_data()
.idx_model(dependency)
.and_then(|m| m.installed())
.map::<_, Manifest>(|m| m.manifest())
.expect(db)
.await?
.get(db, true)
.await?;
let dependency_config = if let Some(cfg) = dependency_config.take() { let dependency_config = if let Some(cfg) = dependency_config.take() {
cfg cfg
} else if let Some(cfg_info) = &dependency_manifest.config { } else if let Some(cfg_info) = &dependency_manifest.config {
@@ -209,6 +257,7 @@ impl DependencyError {
id, id,
&dependent_manifest.version, &dependent_manifest.version,
&dependent_manifest.volumes, &dependent_manifest.volumes,
dependency,
&dependency_config, &dependency_config,
) )
.await? .await?
@@ -217,40 +266,39 @@ impl DependencyError {
} }
} }
DependencyError::NotRunning DependencyError::NotRunning
.try_heal(ctx, db, id, dependency, Some(dependency_config), info) .try_heal(
ctx,
db,
id,
dependency,
Some(dependency_config),
info,
receipts,
)
.await? .await?
} }
DependencyError::NotRunning => { DependencyError::NotRunning => {
let status = crate::db::DatabaseModel::new() let status = receipts
.package_data() .status
.idx_model(dependency) .get(db, dependency)
.and_then(|m| m.installed())
.map::<_, Status>(|m| m.status())
.expect(db)
.await? .await?
.get(db, true) .ok_or_else(not_found)?;
.await?;
if status.main.running() { if status.main.running() {
DependencyError::HealthChecksFailed { DependencyError::HealthChecksFailed {
failures: BTreeMap::new(), failures: BTreeMap::new(),
} }
.try_heal(ctx, db, id, dependency, dependency_config, info) .try_heal(ctx, db, id, dependency, dependency_config, info, receipts)
.await? .await?
} else { } else {
Some(DependencyError::NotRunning) Some(DependencyError::NotRunning)
} }
} }
DependencyError::HealthChecksFailed { .. } => { DependencyError::HealthChecksFailed { .. } => {
let status = crate::db::DatabaseModel::new() let status = receipts
.package_data() .status
.idx_model(dependency) .get(db, dependency)
.and_then(|m| m.installed())
.map::<_, Status>(|m| m.status())
.expect(db)
.await? .await?
.get(db, true) .ok_or_else(not_found)?;
.await?
.into_owned();
match status.main { match status.main {
MainStatus::BackingUp { MainStatus::BackingUp {
started: Some(_), started: Some(_),
@@ -260,19 +308,14 @@ impl DependencyError {
let mut failures = BTreeMap::new(); let mut failures = BTreeMap::new();
for (check, res) in health { for (check, res) in health {
if !matches!(res, HealthCheckResult::Success) if !matches!(res, HealthCheckResult::Success)
&& crate::db::DatabaseModel::new() && receipts
.package_data() .current_dependencies
.idx_model(id) .get(db, id)
.and_then(|m| m.installed())
.and_then::<_, CurrentDependencyInfo>(|m| {
m.current_dependencies().idx_model(dependency)
})
.get(db, true)
.await? .await?
.into_owned() .ok_or_else(not_found)?
.map(|i| i.health_checks) .get(dependency)
.unwrap_or_default() .map(|x| x.health_checks.contains(&check))
.contains(&check) .unwrap_or(false)
{ {
failures.insert(check.clone(), res.clone()); failures.insert(check.clone(), res.clone());
} }
@@ -281,27 +324,39 @@ impl DependencyError {
Some(DependencyError::HealthChecksFailed { failures }) Some(DependencyError::HealthChecksFailed { failures })
} else { } else {
DependencyError::Transitive DependencyError::Transitive
.try_heal(ctx, db, id, dependency, dependency_config, info) .try_heal(
ctx,
db,
id,
dependency,
dependency_config,
info,
receipts,
)
.await? .await?
} }
} }
MainStatus::Starting => { MainStatus::Starting { .. } | MainStatus::Restarting => {
DependencyError::Transitive DependencyError::Transitive
.try_heal(ctx, db, id, dependency, dependency_config, info) .try_heal(
ctx,
db,
id,
dependency,
dependency_config,
info,
receipts,
)
.await? .await?
} }
_ => return Ok(Some(DependencyError::NotRunning)), _ => return Ok(Some(DependencyError::NotRunning)),
} }
} }
DependencyError::Transitive => { DependencyError::Transitive => {
if crate::db::DatabaseModel::new() if receipts
.package_data() .dependency_errors
.idx_model(dependency) .get(db, dependency)
.and_then(|m| m.installed())
.map::<_, DependencyErrors>(|m| m.status().dependency_errors())
.get(db, true)
.await? .await?
.into_owned()
.unwrap_or_default() .unwrap_or_default()
.0 .0
.is_empty() .is_empty()
@@ -406,6 +461,7 @@ impl DepInfo {
dependency_id: &PackageId, dependency_id: &PackageId,
dependency_config: Option<Config>, // fetch if none dependency_config: Option<Config>, // fetch if none
dependent_id: &PackageId, dependent_id: &PackageId,
receipts: &TryHealReceipts,
) -> Result<Result<(), DependencyError>, Error> { ) -> Result<Result<(), DependencyError>, Error> {
Ok( Ok(
if let Some(err) = DependencyError::NotInstalled if let Some(err) = DependencyError::NotInstalled
@@ -416,6 +472,7 @@ impl DepInfo {
dependency_id, dependency_id,
dependency_config, dependency_config,
self, self,
receipts,
) )
.await? .await?
{ {
@@ -430,8 +487,8 @@ impl DepInfo {
#[derive(Clone, Debug, Deserialize, Serialize, HasModel)] #[derive(Clone, Debug, Deserialize, Serialize, HasModel)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct DependencyConfig { pub struct DependencyConfig {
check: ActionImplementation, check: PackageProcedure,
auto_configure: ActionImplementation, auto_configure: PackageProcedure,
} }
impl DependencyConfig { impl DependencyConfig {
pub async fn check( pub async fn check(
@@ -440,6 +497,7 @@ impl DependencyConfig {
dependent_id: &PackageId, dependent_id: &PackageId,
dependent_version: &Version, dependent_version: &Version,
dependent_volumes: &Volumes, dependent_volumes: &Volumes,
dependency_id: &PackageId,
dependency_config: &Config, dependency_config: &Config,
) -> Result<Result<NoOutput, String>, Error> { ) -> Result<Result<NoOutput, String>, Error> {
Ok(self Ok(self
@@ -451,6 +509,7 @@ impl DependencyConfig {
dependent_volumes, dependent_volumes,
Some(dependency_config), Some(dependency_config),
None, None,
ProcedureName::Check(dependency_id.clone()),
) )
.await? .await?
.map_err(|(_, e)| e)) .map_err(|(_, e)| e))
@@ -471,12 +530,97 @@ impl DependencyConfig {
dependent_volumes, dependent_volumes,
Some(old), Some(old),
None, None,
ProcedureName::AutoConfig(dependent_id.clone()),
) )
.await? .await?
.map_err(|e| Error::new(eyre!("{}", e.1), crate::ErrorKind::AutoConfigure)) .map_err(|e| Error::new(eyre!("{}", e.1), crate::ErrorKind::AutoConfigure))
} }
} }
pub struct DependencyConfigReceipts {
config: ConfigReceipts,
dependencies: LockReceipt<Dependencies, ()>,
dependency_volumes: LockReceipt<Volumes, ()>,
dependency_version: LockReceipt<Version, ()>,
dependency_config_action: LockReceipt<ConfigActions, ()>,
package_volumes: LockReceipt<Volumes, ()>,
package_version: LockReceipt<Version, ()>,
}
impl DependencyConfigReceipts {
pub async fn new<'a>(
db: &'a mut impl DbHandle,
package_id: &PackageId,
dependency_id: &PackageId,
) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks, package_id, dependency_id);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<LockTargetId>,
package_id: &PackageId,
dependency_id: &PackageId,
) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let config = ConfigReceipts::setup(locks);
let dependencies = crate::db::DatabaseModel::new()
.package_data()
.idx_model(package_id)
.and_then(|x| x.installed())
.map(|x| x.manifest().dependencies())
.make_locker(LockType::Write)
.add_to_keys(locks);
let dependency_volumes = crate::db::DatabaseModel::new()
.package_data()
.idx_model(dependency_id)
.and_then(|x| x.installed())
.map(|x| x.manifest().volumes())
.make_locker(LockType::Write)
.add_to_keys(locks);
let dependency_version = crate::db::DatabaseModel::new()
.package_data()
.idx_model(dependency_id)
.and_then(|x| x.installed())
.map(|x| x.manifest().version())
.make_locker(LockType::Write)
.add_to_keys(locks);
let dependency_config_action = crate::db::DatabaseModel::new()
.package_data()
.idx_model(dependency_id)
.and_then(|x| x.installed())
.and_then(|x| x.manifest().config())
.make_locker(LockType::Write)
.add_to_keys(locks);
let package_volumes = crate::db::DatabaseModel::new()
.package_data()
.idx_model(package_id)
.and_then(|x| x.installed())
.map(|x| x.manifest().volumes())
.make_locker(LockType::Write)
.add_to_keys(locks);
let package_version = crate::db::DatabaseModel::new()
.package_data()
.idx_model(package_id)
.and_then(|x| x.installed())
.map(|x| x.manifest().version())
.make_locker(LockType::Write)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
config: config(skeleton_key)?,
dependencies: dependencies.verify(&skeleton_key)?,
dependency_volumes: dependency_volumes.verify(&skeleton_key)?,
dependency_version: dependency_version.verify(&skeleton_key)?,
dependency_config_action: dependency_config_action.verify(&skeleton_key)?,
package_volumes: package_volumes.verify(&skeleton_key)?,
package_version: package_version.verify(&skeleton_key)?,
})
}
}
}
#[command( #[command(
subcommands(self(configure_impl(async)), configure_dry), subcommands(self(configure_impl(async)), configure_dry),
display(display_none) display(display_none)
@@ -493,11 +637,14 @@ pub async fn configure_impl(
(pkg_id, dep_id): (PackageId, PackageId), (pkg_id, dep_id): (PackageId, PackageId),
) -> Result<(), Error> { ) -> Result<(), Error> {
let mut db = ctx.db.handle(); let mut db = ctx.db.handle();
let receipts = DependencyConfigReceipts::new(&mut db, &pkg_id, &dep_id).await?;
let ConfigDryRes { let ConfigDryRes {
old_config: _, old_config: _,
new_config, new_config,
spec: _, spec: _,
} = configure_logic(ctx.clone(), &mut db, (pkg_id, dep_id.clone())).await?; } = configure_logic(ctx.clone(), &mut db, (pkg_id, dep_id.clone()), &receipts).await?;
let locks = &receipts.config;
Ok(crate::config::configure( Ok(crate::config::configure(
&ctx, &ctx,
&mut db, &mut db,
@@ -507,6 +654,7 @@ pub async fn configure_impl(
false, false,
&mut BTreeMap::new(), &mut BTreeMap::new(),
&mut BTreeMap::new(), &mut BTreeMap::new(),
locks,
) )
.await?) .await?)
} }
@@ -526,67 +674,25 @@ pub async fn configure_dry(
#[parent_data] (pkg_id, dependency_id): (PackageId, PackageId), #[parent_data] (pkg_id, dependency_id): (PackageId, PackageId),
) -> Result<ConfigDryRes, Error> { ) -> Result<ConfigDryRes, Error> {
let mut db = ctx.db.handle(); let mut db = ctx.db.handle();
configure_logic(ctx, &mut db, (pkg_id, dependency_id)).await let receipts = DependencyConfigReceipts::new(&mut db, &pkg_id, &dependency_id).await?;
configure_logic(ctx, &mut db, (pkg_id, dependency_id), &receipts).await
} }
pub async fn configure_logic( pub async fn configure_logic(
ctx: RpcContext, ctx: RpcContext,
db: &mut PatchDbHandle, db: &mut PatchDbHandle,
(pkg_id, dependency_id): (PackageId, PackageId), (pkg_id, dependency_id): (PackageId, PackageId),
receipts: &DependencyConfigReceipts,
) -> Result<ConfigDryRes, Error> { ) -> Result<ConfigDryRes, Error> {
crate::db::DatabaseModel::new() let pkg_version = receipts.package_version.get(db).await?;
.package_data() let pkg_volumes = receipts.package_volumes.get(db).await?;
.lock(db, LockType::Read) let dependency_config_action = receipts.dependency_config_action.get(db).await?;
.await?; let dependency_version = receipts.dependency_version.get(db).await?;
let pkg_model = crate::db::DatabaseModel::new() let dependency_volumes = receipts.dependency_volumes.get(db).await?;
.package_data() let dependencies = receipts.dependencies.get(db).await?;
.idx_model(&pkg_id)
.and_then(|m| m.installed())
.expect(db)
.await
.with_kind(crate::ErrorKind::NotFound)?;
let pkg_version = pkg_model.clone().manifest().version().get(db, true).await?;
let pkg_volumes = pkg_model.clone().manifest().volumes().get(db, true).await?;
let dependency_model = crate::db::DatabaseModel::new()
.package_data()
.idx_model(&dependency_id)
.and_then(|m| m.installed())
.expect(db)
.await
.with_kind(crate::ErrorKind::NotFound)?;
let dependency_config_action = dependency_model
.clone()
.manifest()
.config()
.get(db, true)
.await?
.to_owned()
.ok_or_else(|| {
Error::new(
eyre!("{} has no config", dependency_id),
crate::ErrorKind::NotFound,
)
})?;
let dependency_version = dependency_model
.clone()
.manifest()
.version()
.get(db, true)
.await?;
let dependency_volumes = dependency_model
.clone()
.manifest()
.volumes()
.get(db, true)
.await?;
let dependencies = pkg_model
.clone()
.manifest()
.dependencies()
.get(db, true)
.await?;
let dependency = dependencies let dependency = dependencies
.0
.get(&dependency_id) .get(&dependency_id)
.ok_or_else(|| { .ok_or_else(|| {
Error::new( Error::new(
@@ -617,8 +723,8 @@ pub async fn configure_logic(
.get( .get(
&ctx, &ctx,
&dependency_id, &dependency_id,
&*dependency_version, &dependency_version,
&*dependency_volumes, &dependency_volumes,
) )
.await?; .await?;
@@ -640,6 +746,7 @@ pub async fn configure_logic(
&pkg_volumes, &pkg_volumes,
Some(&old_config), Some(&old_config),
None, None,
ProcedureName::AutoConfig(dependency_id.clone()),
) )
.await? .await?
.map_err(|e| Error::new(eyre!("{}", e.1), crate::ErrorKind::AutoConfigure))?; .map_err(|e| Error::new(eyre!("{}", e.1), crate::ErrorKind::AutoConfigure))?;
@@ -650,29 +757,22 @@ pub async fn configure_logic(
spec, spec,
}) })
} }
#[instrument(skip(db, current_dependencies, current_dependent_receipt))]
#[instrument(skip(db, current_dependencies))] pub async fn add_dependent_to_current_dependents_lists<'a, Db: DbHandle>(
pub async fn add_dependent_to_current_dependents_lists<
'a,
Db: DbHandle,
I: IntoIterator<Item = (&'a PackageId, &'a CurrentDependencyInfo)>,
>(
db: &mut Db, db: &mut Db,
dependent_id: &PackageId, dependent_id: &PackageId,
current_dependencies: I, current_dependencies: &CurrentDependencies,
current_dependent_receipt: &LockReceipt<CurrentDependents, String>,
) -> Result<(), Error> { ) -> Result<(), Error> {
for (dependency, dep_info) in current_dependencies { for (dependency, dep_info) in &current_dependencies.0 {
if let Some(dependency_model) = crate::db::DatabaseModel::new() if let Some(mut dependency_dependents) =
.package_data() current_dependent_receipt.get(db, dependency).await?
.idx_model(&dependency)
.and_then(|pkg| pkg.installed())
.check(db)
.await?
{ {
dependency_model dependency_dependents
.current_dependents() .0
.idx_model(dependent_id) .insert(dependent_id.clone(), dep_info.clone());
.put(db, &dep_info) current_dependent_receipt
.set(db, dependency_dependents, dependency)
.await?; .await?;
} }
} }
@@ -696,10 +796,11 @@ impl DependencyErrors {
ctx: &RpcContext, ctx: &RpcContext,
db: &mut Db, db: &mut Db,
manifest: &Manifest, manifest: &Manifest,
current_dependencies: &BTreeMap<PackageId, CurrentDependencyInfo>, current_dependencies: &CurrentDependencies,
receipts: &TryHealReceipts,
) -> Result<DependencyErrors, Error> { ) -> Result<DependencyErrors, Error> {
let mut res = BTreeMap::new(); let mut res = BTreeMap::new();
for (dependency_id, info) in current_dependencies.keys().filter_map(|dependency_id| { for (dependency_id, info) in current_dependencies.0.keys().filter_map(|dependency_id| {
manifest manifest
.dependencies .dependencies
.0 .0
@@ -707,7 +808,7 @@ impl DependencyErrors {
.map(|info| (dependency_id, info)) .map(|info| (dependency_id, info))
}) { }) {
if let Err(e) = info if let Err(e) = info
.satisfied(ctx, db, dependency_id, None, &manifest.id) .satisfied(ctx, db, dependency_id, None, &manifest.id, receipts)
.await? .await?
{ {
res.insert(dependency_id.clone(), e); res.insert(dependency_id.clone(), e);
@@ -735,49 +836,86 @@ pub async fn break_all_dependents_transitive<'a, Db: DbHandle>(
id: &'a PackageId, id: &'a PackageId,
error: DependencyError, error: DependencyError,
breakages: &'a mut BTreeMap<PackageId, TaggedDependencyError>, breakages: &'a mut BTreeMap<PackageId, TaggedDependencyError>,
receipts: &'a BreakTransitiveReceipts,
) -> Result<(), Error> { ) -> Result<(), Error> {
for dependent in crate::db::DatabaseModel::new() for dependent in receipts
.package_data() .current_dependents
.idx_model(id) .get(db, id)
.and_then(|m| m.installed())
.expect(db)
.await? .await?
.current_dependents() .iter()
.keys(db, true) .flat_map(|x| x.0.keys())
.await? .filter(|dependent| id != *dependent)
.into_iter()
.filter(|dependent| id != dependent)
{ {
break_transitive(db, &dependent, id, error.clone(), breakages).await?; break_transitive(db, dependent, id, error.clone(), breakages, receipts).await?;
} }
Ok(()) Ok(())
} }
#[instrument(skip(db))] #[derive(Clone)]
pub struct BreakTransitiveReceipts {
pub dependency_receipt: DependencyReceipt,
dependency_errors: LockReceipt<DependencyErrors, String>,
current_dependents: LockReceipt<CurrentDependents, String>,
}
impl BreakTransitiveReceipts {
pub async fn new(db: &'_ mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(locks: &mut Vec<LockTargetId>) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let dependency_receipt = DependencyReceipt::setup(locks);
let dependency_errors = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.status().dependency_errors())
.make_locker(LockType::Write)
.add_to_keys(locks);
let current_dependents = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.current_dependents())
.make_locker(LockType::Exist)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
dependency_receipt: dependency_receipt(skeleton_key)?,
dependency_errors: dependency_errors.verify(skeleton_key)?,
current_dependents: current_dependents.verify(skeleton_key)?,
})
}
}
}
#[instrument(skip(db, receipts))]
pub fn break_transitive<'a, Db: DbHandle>( pub fn break_transitive<'a, Db: DbHandle>(
db: &'a mut Db, db: &'a mut Db,
id: &'a PackageId, id: &'a PackageId,
dependency: &'a PackageId, dependency: &'a PackageId,
error: DependencyError, error: DependencyError,
breakages: &'a mut BTreeMap<PackageId, TaggedDependencyError>, breakages: &'a mut BTreeMap<PackageId, TaggedDependencyError>,
receipts: &'a BreakTransitiveReceipts,
) -> BoxFuture<'a, Result<(), Error>> { ) -> BoxFuture<'a, Result<(), Error>> {
async move { async move {
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
let model = crate::db::DatabaseModel::new() let mut dependency_errors = receipts
.package_data() .dependency_errors
.idx_model(id) .get(&mut tx, id)
.and_then(|m| m.installed()) .await?
.expect(&mut tx) .ok_or_else(not_found)?;
.await?;
let mut status = model.clone().status().get_mut(&mut tx).await?;
let old = status.dependency_errors.0.remove(dependency); let old = dependency_errors.0.remove(dependency);
let newly_broken = if let Some(e) = &old { let newly_broken = if let Some(e) = &old {
error.cmp_priority(&e) == Ordering::Greater error.cmp_priority(&e) == Ordering::Greater
} else { } else {
true true
}; };
status.dependency_errors.0.insert( dependency_errors.0.insert(
dependency.clone(), dependency.clone(),
if let Some(old) = old { if let Some(old) = old {
old.merge_with(error.clone()) old.merge_with(error.clone())
@@ -793,12 +931,25 @@ pub fn break_transitive<'a, Db: DbHandle>(
error: error.clone(), error: error.clone(),
}, },
); );
status.save(&mut tx).await?; receipts
.dependency_errors
.set(&mut tx, dependency_errors, id)
.await?;
tx.save().await?; tx.save().await?;
break_all_dependents_transitive(db, id, DependencyError::Transitive, breakages).await?; break_all_dependents_transitive(
db,
id,
DependencyError::Transitive,
breakages,
receipts,
)
.await?;
} else { } else {
status.save(&mut tx).await?; receipts
.dependency_errors
.set(&mut tx, dependency_errors, id)
.await?;
tx.save().await?; tx.save().await?;
} }
@@ -808,68 +959,52 @@ pub fn break_transitive<'a, Db: DbHandle>(
.boxed() .boxed()
} }
#[instrument(skip(ctx, db))] #[instrument(skip(ctx, db, locks))]
pub async fn heal_all_dependents_transitive<'a, Db: DbHandle>( pub async fn heal_all_dependents_transitive<'a, Db: DbHandle>(
ctx: &'a RpcContext, ctx: &'a RpcContext,
db: &'a mut Db, db: &'a mut Db,
id: &'a PackageId, id: &'a PackageId,
locks: &'a DependencyReceipt,
) -> Result<(), Error> { ) -> Result<(), Error> {
for dependent in crate::db::DatabaseModel::new() let dependents = locks
.package_data() .current_dependents
.idx_model(id) .get(db, id)
.and_then(|m| m.installed())
.expect(db)
.await? .await?
.current_dependents() .ok_or_else(not_found)?;
.keys(db, true) for dependent in dependents.0.keys().filter(|dependent| id != *dependent) {
.await? heal_transitive(ctx, db, dependent, id, locks).await?;
.into_iter()
.filter(|dependent| id != dependent)
{
heal_transitive(ctx, db, &dependent, id).await?;
} }
Ok(()) Ok(())
} }
#[instrument(skip(ctx, db))] #[instrument(skip(ctx, db, receipts))]
pub fn heal_transitive<'a, Db: DbHandle>( pub fn heal_transitive<'a, Db: DbHandle>(
ctx: &'a RpcContext, ctx: &'a RpcContext,
db: &'a mut Db, db: &'a mut Db,
id: &'a PackageId, id: &'a PackageId,
dependency: &'a PackageId, dependency: &'a PackageId,
receipts: &'a DependencyReceipt,
) -> BoxFuture<'a, Result<(), Error>> { ) -> BoxFuture<'a, Result<(), Error>> {
async move { async move {
let mut tx = db.begin().await?; let mut status = receipts.status.get(db, id).await?.ok_or_else(not_found)?;
let model = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|m| m.installed())
.expect(&mut tx)
.await?;
let mut status = model.clone().status().get_mut(&mut tx).await?;
let old = status.dependency_errors.0.remove(dependency); let old = status.dependency_errors.0.remove(dependency);
if let Some(old) = old { if let Some(old) = old {
let info = model let info = receipts
.manifest() .dependency
.dependencies() .get(db, (id, dependency))
.idx_model(dependency)
.expect(&mut tx)
.await? .await?
.get(&mut tx, true) .ok_or_else(not_found)?;
.await?;
if let Some(new) = old if let Some(new) = old
.try_heal(ctx, &mut tx, id, dependency, None, &*info) .try_heal(ctx, db, id, dependency, None, &info, &receipts.try_heal)
.await? .await?
{ {
status.dependency_errors.0.insert(dependency.clone(), new); status.dependency_errors.0.insert(dependency.clone(), new);
status.save(&mut tx).await?; receipts.status.set(db, status, id).await?;
tx.save().await?;
} else { } else {
status.save(&mut tx).await?; receipts.status.set(db, status, id).await?;
tx.save().await?; heal_all_dependents_transitive(ctx, db, id, receipts).await?;
heal_all_dependents_transitive(ctx, db, id).await?;
} }
} }
@@ -881,11 +1016,12 @@ pub fn heal_transitive<'a, Db: DbHandle>(
pub async fn reconfigure_dependents_with_live_pointers( pub async fn reconfigure_dependents_with_live_pointers(
ctx: &RpcContext, ctx: &RpcContext,
mut tx: impl DbHandle, mut tx: impl DbHandle,
receipts: &ConfigReceipts,
pde: &InstalledPackageDataEntry, pde: &InstalledPackageDataEntry,
) -> Result<(), Error> { ) -> Result<(), Error> {
let dependents = &pde.current_dependents; let dependents = &pde.current_dependents;
let me = &pde.manifest.id; let me = &pde.manifest.id;
for (dependent_id, dependency_info) in dependents { for (dependent_id, dependency_info) in &dependents.0 {
if dependency_info.pointers.iter().any(|ptr| match ptr { if dependency_info.pointers.iter().any(|ptr| match ptr {
// dependency id matches the package being uninstalled // dependency id matches the package being uninstalled
PackagePointerSpec::TorAddress(ptr) => &ptr.package_id == me && dependent_id != me, PackagePointerSpec::TorAddress(ptr) => &ptr.package_id == me && dependent_id != me,
@@ -903,9 +1039,60 @@ pub async fn reconfigure_dependents_with_live_pointers(
false, false,
&mut BTreeMap::new(), &mut BTreeMap::new(),
&mut BTreeMap::new(), &mut BTreeMap::new(),
receipts,
) )
.await?; .await?;
} }
} }
Ok(()) Ok(())
} }
#[derive(Clone)]
pub struct DependencyReceipt {
pub try_heal: TryHealReceipts,
current_dependents: LockReceipt<CurrentDependents, String>,
status: LockReceipt<Status, String>,
dependency: LockReceipt<DepInfo, (String, String)>,
}
impl DependencyReceipt {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(locks: &mut Vec<LockTargetId>) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let try_heal = TryHealReceipts::setup(locks);
let dependency = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest().dependencies().star())
.make_locker(LockType::Read)
.add_to_keys(locks);
let current_dependents = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.current_dependents())
.make_locker(LockType::Write)
.add_to_keys(locks);
let status = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.status())
.make_locker(LockType::Write)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
try_heal: try_heal(skeleton_key)?,
current_dependents: current_dependents.verify(skeleton_key)?,
status: status.verify(skeleton_key)?,
dependency: dependency.verify(skeleton_key)?,
})
}
}
}

View File

@@ -2,6 +2,7 @@ use std::fs::File;
use std::io::Write; use std::io::Write;
use std::path::Path; use std::path::Path;
use ed25519::pkcs8::EncodePrivateKey;
use ed25519_dalek::Keypair; use ed25519_dalek::Keypair;
use rpc_toolkit::command; use rpc_toolkit::command;
use tracing::instrument; use tracing::instrument;
@@ -20,10 +21,19 @@ pub fn init(#[context] ctx: SdkContext) -> Result<(), Error> {
.with_ctx(|_| (crate::ErrorKind::Filesystem, parent.display().to_string()))?; .with_ctx(|_| (crate::ErrorKind::Filesystem, parent.display().to_string()))?;
} }
tracing::info!("Generating new developer key..."); tracing::info!("Generating new developer key...");
let keypair = Keypair::generate(&mut rand::thread_rng()); let keypair = Keypair::generate(&mut rand_old::thread_rng());
tracing::info!("Writing key to {}", ctx.developer_key_path.display()); tracing::info!("Writing key to {}", ctx.developer_key_path.display());
let keypair_bytes = ed25519::KeypairBytes {
secret_key: keypair.secret.to_bytes(),
public_key: Some(keypair.public.to_bytes()),
};
let mut dev_key_file = File::create(&ctx.developer_key_path)?; let mut dev_key_file = File::create(&ctx.developer_key_path)?;
dev_key_file.write_all(&keypair.to_bytes())?; dev_key_file.write_all(
keypair_bytes
.to_pkcs8_pem(base64ct::LineEnding::default())
.with_kind(crate::ErrorKind::Pem)?
.as_bytes(),
)?;
dev_key_file.sync_all()?; dev_key_file.sync_all()?;
} }
Ok(()) Ok(())

View File

@@ -7,7 +7,7 @@ use futures::FutureExt;
use tokio::process::Command; use tokio::process::Command;
use tracing::instrument; use tracing::instrument;
use crate::{Error, ResultExt}; use crate::Error;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
#[must_use] #[must_use]

View File

@@ -11,7 +11,7 @@ use crate::disk::mount::filesystem::block_dev::mount;
use crate::disk::mount::filesystem::ReadWrite; use crate::disk::mount::filesystem::ReadWrite;
use crate::disk::mount::util::unmount; use crate::disk::mount::util::unmount;
use crate::util::Invoke; use crate::util::Invoke;
use crate::{Error, ResultExt}; use crate::{Error, ErrorKind, ResultExt};
pub const PASSWORD_PATH: &'static str = "/etc/embassy/password"; pub const PASSWORD_PATH: &'static str = "/etc/embassy/password";
pub const DEFAULT_PASSWORD: &'static str = "password"; pub const DEFAULT_PASSWORD: &'static str = "password";
@@ -183,6 +183,7 @@ pub async fn unmount_all_fs<P: AsRef<Path>>(guid: &str, datadir: P) -> Result<()
#[instrument(skip(datadir))] #[instrument(skip(datadir))]
pub async fn export<P: AsRef<Path>>(guid: &str, datadir: P) -> Result<(), Error> { pub async fn export<P: AsRef<Path>>(guid: &str, datadir: P) -> Result<(), Error> {
Command::new("sync").invoke(ErrorKind::Filesystem).await?;
unmount_all_fs(guid, datadir).await?; unmount_all_fs(guid, datadir).await?;
Command::new("vgchange") Command::new("vgchange")
.arg("-an") .arg("-an")

View File

@@ -20,7 +20,7 @@ pub fn disk() -> Result<(), Error> {
Ok(()) Ok(())
} }
fn display_disk_info(info: DiskListResponse, matches: &ArgMatches<'_>) { fn display_disk_info(info: DiskListResponse, matches: &ArgMatches) {
use prettytable::*; use prettytable::*;
if matches.is_present("format") { if matches.is_present("format") {

View File

@@ -1,6 +1,7 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use helpers::AtomicFile;
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
use tracing::instrument; use tracing::instrument;
@@ -14,9 +15,9 @@ use crate::disk::util::EmbassyOsRecoveryInfo;
use crate::middleware::encrypt::{decrypt_slice, encrypt_slice}; use crate::middleware::encrypt::{decrypt_slice, encrypt_slice};
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::util::serde::IoFormat; use crate::util::serde::IoFormat;
use crate::util::{AtomicFile, FileLock}; use crate::util::FileLock;
use crate::volume::BACKUP_DIR; use crate::volume::BACKUP_DIR;
use crate::{Error, ResultExt}; use crate::{Error, ErrorKind, ResultExt};
pub struct BackupMountGuard<G: GenericMountGuard> { pub struct BackupMountGuard<G: GenericMountGuard> {
backup_disk_mount_guard: Option<G>, backup_disk_mount_guard: Option<G>,
@@ -162,16 +163,20 @@ impl<G: GenericMountGuard> BackupMountGuard<G> {
pub async fn save(&self) -> Result<(), Error> { pub async fn save(&self) -> Result<(), Error> {
let metadata_path = self.as_ref().join("metadata.cbor"); let metadata_path = self.as_ref().join("metadata.cbor");
let backup_disk_path = self.backup_disk_path(); let backup_disk_path = self.backup_disk_path();
let mut file = AtomicFile::new(&metadata_path).await?; let mut file = AtomicFile::new(&metadata_path, None::<PathBuf>)
.await
.with_kind(ErrorKind::Filesystem)?;
file.write_all(&IoFormat::Cbor.to_vec(&self.metadata)?) file.write_all(&IoFormat::Cbor.to_vec(&self.metadata)?)
.await?; .await?;
file.save().await?; file.save().await.with_kind(ErrorKind::Filesystem)?;
let unencrypted_metadata_path = let unencrypted_metadata_path =
backup_disk_path.join("EmbassyBackups/unencrypted-metadata.cbor"); backup_disk_path.join("EmbassyBackups/unencrypted-metadata.cbor");
let mut file = AtomicFile::new(&unencrypted_metadata_path).await?; let mut file = AtomicFile::new(&unencrypted_metadata_path, None::<PathBuf>)
.await
.with_kind(ErrorKind::Filesystem)?;
file.write_all(&IoFormat::Cbor.to_vec(&self.unencrypted_metadata)?) file.write_all(&IoFormat::Cbor.to_vec(&self.unencrypted_metadata)?)
.await?; .await?;
file.save().await?; file.save().await.with_kind(ErrorKind::Filesystem)?;
Ok(()) Ok(())
} }

View File

@@ -3,7 +3,7 @@ use std::path::Path;
use async_trait::async_trait; use async_trait::async_trait;
use digest::generic_array::GenericArray; use digest::generic_array::GenericArray;
use digest::Digest; use digest::{Digest, OutputSizeUser};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::Sha256; use sha2::Sha256;
@@ -45,7 +45,9 @@ impl<LogicalName: AsRef<Path> + Send + Sync> FileSystem for BlockDev<LogicalName
) -> Result<(), Error> { ) -> Result<(), Error> {
mount(self.logicalname.as_ref(), mountpoint, mount_type).await mount(self.logicalname.as_ref(), mountpoint, mount_type).await
} }
async fn source_hash(&self) -> Result<GenericArray<u8, <Sha256 as Digest>::OutputSize>, Error> { async fn source_hash(
&self,
) -> Result<GenericArray<u8, <Sha256 as OutputSizeUser>::OutputSize>, Error> {
let mut sha = Sha256::new(); let mut sha = Sha256::new();
sha.update("BlockDev"); sha.update("BlockDev");
sha.update( sha.update(

View File

@@ -4,7 +4,7 @@ use std::path::{Path, PathBuf};
use async_trait::async_trait; use async_trait::async_trait;
use digest::generic_array::GenericArray; use digest::generic_array::GenericArray;
use digest::Digest; use digest::{Digest, OutputSizeUser};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::Sha256; use sha2::Sha256;
use tokio::process::Command; use tokio::process::Command;
@@ -18,7 +18,7 @@ use crate::Error;
async fn resolve_hostname(hostname: &str) -> Result<IpAddr, Error> { async fn resolve_hostname(hostname: &str) -> Result<IpAddr, Error> {
#[cfg(feature = "avahi")] #[cfg(feature = "avahi")]
if hostname.ends_with(".local") { if hostname.ends_with(".local") {
return Ok(crate::net::mdns::resolve_mdns(hostname).await?); return Ok(IpAddr::V4(crate::net::mdns::resolve_mdns(hostname).await?));
} }
Ok(String::from_utf8( Ok(String::from_utf8(
Command::new("nmblookup") Command::new("nmblookup")
@@ -93,7 +93,9 @@ impl FileSystem for Cifs {
) )
.await .await
} }
async fn source_hash(&self) -> Result<GenericArray<u8, <Sha256 as Digest>::OutputSize>, Error> { async fn source_hash(
&self,
) -> Result<GenericArray<u8, <Sha256 as OutputSizeUser>::OutputSize>, Error> {
let mut sha = Sha256::new(); let mut sha = Sha256::new();
sha.update("Cifs"); sha.update("Cifs");
sha.update(self.hostname.as_bytes()); sha.update(self.hostname.as_bytes());

View File

@@ -4,7 +4,7 @@ use std::path::Path;
use async_trait::async_trait; use async_trait::async_trait;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use digest::generic_array::GenericArray; use digest::generic_array::GenericArray;
use digest::Digest; use digest::{Digest, OutputSizeUser};
use sha2::Sha256; use sha2::Sha256;
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -63,7 +63,9 @@ impl<EncryptedDir: AsRef<Path> + Send + Sync, Key: AsRef<str> + Send + Sync> Fil
) -> Result<(), Error> { ) -> Result<(), Error> {
mount_ecryptfs(self.encrypted_dir.as_ref(), mountpoint, self.key.as_ref()).await mount_ecryptfs(self.encrypted_dir.as_ref(), mountpoint, self.key.as_ref()).await
} }
async fn source_hash(&self) -> Result<GenericArray<u8, <Sha256 as Digest>::OutputSize>, Error> { async fn source_hash(
&self,
) -> Result<GenericArray<u8, <Sha256 as OutputSizeUser>::OutputSize>, Error> {
let mut sha = Sha256::new(); let mut sha = Sha256::new();
sha.update("EcryptFS"); sha.update("EcryptFS");
sha.update( sha.update(

View File

@@ -2,7 +2,7 @@ use std::path::Path;
use async_trait::async_trait; use async_trait::async_trait;
use digest::generic_array::GenericArray; use digest::generic_array::GenericArray;
use digest::Digest; use digest::{Digest, OutputSizeUser};
use sha2::Sha256; use sha2::Sha256;
use super::{FileSystem, MountType, ReadOnly}; use super::{FileSystem, MountType, ReadOnly};
@@ -41,7 +41,9 @@ impl<S: AsRef<str> + Send + Sync> FileSystem for Label<S> {
) -> Result<(), Error> { ) -> Result<(), Error> {
mount_label(self.label.as_ref(), mountpoint, mount_type).await mount_label(self.label.as_ref(), mountpoint, mount_type).await
} }
async fn source_hash(&self) -> Result<GenericArray<u8, <Sha256 as Digest>::OutputSize>, Error> { async fn source_hash(
&self,
) -> Result<GenericArray<u8, <Sha256 as OutputSizeUser>::OutputSize>, Error> {
let mut sha = Sha256::new(); let mut sha = Sha256::new();
sha.update("Label"); sha.update("Label");
sha.update(self.label.as_ref().as_bytes()); sha.update(self.label.as_ref().as_bytes());

View File

@@ -2,7 +2,7 @@ use std::path::Path;
use async_trait::async_trait; use async_trait::async_trait;
use digest::generic_array::GenericArray; use digest::generic_array::GenericArray;
use digest::Digest; use digest::OutputSizeUser;
use sha2::Sha256; use sha2::Sha256;
use crate::Error; use crate::Error;
@@ -27,5 +27,7 @@ pub trait FileSystem {
mountpoint: P, mountpoint: P,
mount_type: MountType, mount_type: MountType,
) -> Result<(), Error>; ) -> Result<(), Error>;
async fn source_hash(&self) -> Result<GenericArray<u8, <Sha256 as Digest>::OutputSize>, Error>; async fn source_hash(
&self,
) -> Result<GenericArray<u8, <Sha256 as OutputSizeUser>::OutputSize>, Error>;
} }

View File

@@ -1,14 +1,14 @@
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::num::ParseIntError; use std::num::ParseIntError;
use std::path::Path; use std::path::{Path, PathBuf};
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use helpers::AtomicFile;
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
use tracing::instrument; use tracing::instrument;
use super::BOOT_RW_PATH; use super::BOOT_RW_PATH;
use crate::util::AtomicFile; use crate::{Error, ErrorKind, ResultExt};
use crate::Error;
pub const QUIRK_PATH: &'static str = "/sys/module/usb_storage/parameters/quirks"; pub const QUIRK_PATH: &'static str = "/sys/module/usb_storage/parameters/quirks";
@@ -160,11 +160,13 @@ pub async fn save_quirks(quirks: &Quirks) -> Result<(), Error> {
tokio::fs::copy(&target_path, &orig_path).await?; tokio::fs::copy(&target_path, &orig_path).await?;
} }
let cmdline = tokio::fs::read_to_string(&orig_path).await?; let cmdline = tokio::fs::read_to_string(&orig_path).await?;
let mut target = AtomicFile::new(&target_path).await?; let mut target = AtomicFile::new(&target_path, None::<PathBuf>)
.await
.with_kind(ErrorKind::Filesystem)?;
target target
.write_all(format!("usb-storage.quirks={} {}", quirks, cmdline).as_bytes()) .write_all(format!("usb-storage.quirks={} {}", quirks, cmdline).as_bytes())
.await?; .await?;
target.save().await?; target.save().await.with_kind(ErrorKind::Filesystem)?;
Ok(()) Ok(())
} }

View File

@@ -1,6 +1,7 @@
use std::fmt::Display; use std::fmt::Display;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use models::InvalidId;
use patch_db::Revision; use patch_db::Revision;
use rpc_toolkit::yajrc::RpcError; use rpc_toolkit::yajrc::RpcError;
@@ -30,7 +31,7 @@ pub enum ErrorKind {
InvalidOnionAddress = 22, InvalidOnionAddress = 22,
Pack = 23, Pack = 23,
ValidateS9pk = 24, ValidateS9pk = 24,
DiskCorrupted = 25, DiskCorrupted = 25, // Remove
Tor = 26, Tor = 26,
ConfigGen = 27, ConfigGen = 27,
ParseNumber = 28, ParseNumber = 28,
@@ -64,6 +65,8 @@ pub enum ErrorKind {
InvalidBackupTargetId = 56, InvalidBackupTargetId = 56,
ProductKeyMismatch = 57, ProductKeyMismatch = 57,
LanPortConflict = 58, LanPortConflict = 58,
Javascript = 59,
Pem = 60,
} }
impl ErrorKind { impl ErrorKind {
pub fn as_str(&self) -> &'static str { pub fn as_str(&self) -> &'static str {
@@ -126,7 +129,9 @@ impl ErrorKind {
Incoherent => "Incoherent", Incoherent => "Incoherent",
InvalidBackupTargetId => "Invalid Backup Target ID", InvalidBackupTargetId => "Invalid Backup Target ID",
ProductKeyMismatch => "Incompatible Product Keys", ProductKeyMismatch => "Incompatible Product Keys",
LanPortConflict => "Incompatible LAN port configuration", LanPortConflict => "Incompatible LAN Port Configuration",
Javascript => "Javascript Engine Error",
Pem => "PEM Encoding Error",
} }
} }
} }
@@ -142,6 +147,7 @@ pub struct Error {
pub kind: ErrorKind, pub kind: ErrorKind,
pub revision: Option<Revision>, pub revision: Option<Revision>,
} }
impl Display for Error { impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.kind.as_str(), self.source) write!(f, "{}: {}", self.kind.as_str(), self.source)
@@ -156,6 +162,11 @@ impl Error {
} }
} }
} }
impl From<InvalidId> for Error {
fn from(err: InvalidId) -> Self {
Error::new(err, crate::error::ErrorKind::InvalidPackageId)
}
}
impl From<std::io::Error> for Error { impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self { fn from(e: std::io::Error) -> Self {
Error::new(e, ErrorKind::Filesystem) Error::new(e, ErrorKind::Filesystem)

View File

@@ -1,142 +1,13 @@
use std::borrow::{Borrow, Cow};
use std::fmt::Debug; use std::fmt::Debug;
use std::str::FromStr; use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::{Deserialize, Deserializer, Serialize};
use crate::util::Version; use crate::util::Version;
use crate::Error;
pub const SYSTEM_ID: Id<&'static str> = Id("x_system"); pub use models::{Id, InvalidId, IdUnchecked, SYSTEM_ID};
#[derive(Debug, thiserror::Error)]
#[error("Invalid ID")]
pub struct InvalidId;
impl From<InvalidId> for Error {
fn from(err: InvalidId) -> Self {
Error::new(err, crate::error::ErrorKind::InvalidPackageId)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct IdUnchecked<S: AsRef<str>>(pub S);
impl<'de> Deserialize<'de> for IdUnchecked<Cow<'de, str>> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = IdUnchecked<Cow<'de, str>>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(formatter, "a valid ID")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(IdUnchecked(Cow::Owned(v.to_owned())))
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(IdUnchecked(Cow::Owned(v)))
}
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(IdUnchecked(Cow::Borrowed(v)))
}
}
deserializer.deserialize_any(Visitor)
}
}
impl<'de> Deserialize<'de> for IdUnchecked<String> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(IdUnchecked(String::deserialize(deserializer)?))
}
}
impl<'de> Deserialize<'de> for IdUnchecked<&'de str> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(IdUnchecked(<&'de str>::deserialize(deserializer)?))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id<S: AsRef<str> = String>(S);
impl<S: AsRef<str>> Id<S> {
pub fn try_from(value: S) -> Result<Self, InvalidId> {
if value
.as_ref()
.chars()
.all(|c| c.is_ascii_lowercase() || c == '-')
{
Ok(Id(value))
} else {
Err(InvalidId)
}
}
}
impl<'a> Id<&'a str> {
pub fn owned(&self) -> Id {
Id(self.0.to_owned())
}
}
impl From<Id> for String {
fn from(value: Id) -> Self {
value.0
}
}
impl<S: AsRef<str>> std::ops::Deref for Id<S> {
type Target = S;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<S: AsRef<str>> std::fmt::Display for Id<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.as_ref())
}
}
impl<S: AsRef<str>> AsRef<str> for Id<S> {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl<S: AsRef<str>> Borrow<str> for Id<S> {
fn borrow(&self) -> &str {
self.0.as_ref()
}
}
impl<'de, S> Deserialize<'de> for Id<S>
where
S: AsRef<str>,
IdUnchecked<S>: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let unchecked: IdUnchecked<S> = Deserialize::deserialize(deserializer)?;
Id::try_from(unchecked.0).map_err(serde::de::Error::custom)
}
}
impl<S: AsRef<str>> Serialize for Id<S> {
fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
where
Ser: Serializer,
{
serializer.serialize_str(self.as_ref())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct ImageId<S: AsRef<str> = String>(Id<S>); pub struct ImageId<S: AsRef<str> = String>(Id<S>);

View File

@@ -1,5 +1,6 @@
use std::time::Duration; use std::time::Duration;
use patch_db::{DbHandle, LockReceipt, LockType};
use tokio::process::Command; use tokio::process::Command;
use crate::context::rpc::RpcContextConfig; use crate::context::rpc::RpcContextConfig;
@@ -9,6 +10,7 @@ use crate::util::Invoke;
use crate::Error; use crate::Error;
pub const SYSTEM_REBUILD_PATH: &str = "/embassy-os/system-rebuild"; pub const SYSTEM_REBUILD_PATH: &str = "/embassy-os/system-rebuild";
pub const STANDBY_MODE_PATH: &str = "/embassy-os/standby";
pub async fn check_time_is_synchronized() -> Result<bool, Error> { pub async fn check_time_is_synchronized() -> Result<bool, Error> {
Ok(String::from_utf8( Ok(String::from_utf8(
@@ -23,6 +25,48 @@ pub async fn check_time_is_synchronized() -> Result<bool, Error> {
== "NTPSynchronized=yes") == "NTPSynchronized=yes")
} }
pub struct InitReceipts {
pub server_version: LockReceipt<crate::util::Version, ()>,
pub version_range: LockReceipt<emver::VersionRange, ()>,
pub last_wifi_region: LockReceipt<Option<isocountry::CountryCode>, ()>,
pub status_info: LockReceipt<ServerStatus, ()>,
}
impl InitReceipts {
pub async fn new(db: &mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let server_version = crate::db::DatabaseModel::new()
.server_info()
.version()
.make_locker(LockType::Write)
.add_to_keys(&mut locks);
let version_range = crate::db::DatabaseModel::new()
.server_info()
.eos_version_compat()
.make_locker(LockType::Write)
.add_to_keys(&mut locks);
let last_wifi_region = crate::db::DatabaseModel::new()
.server_info()
.last_wifi_region()
.make_locker(LockType::Write)
.add_to_keys(&mut locks);
let status_info = crate::db::DatabaseModel::new()
.server_info()
.status_info()
.into_model()
.make_locker(LockType::Write)
.add_to_keys(&mut locks);
let skeleton_key = db.lock_all(locks).await?;
Ok(Self {
server_version: server_version.verify(&skeleton_key)?,
version_range: version_range.verify(&skeleton_key)?,
status_info: status_info.verify(&skeleton_key)?,
last_wifi_region: last_wifi_region.verify(&skeleton_key)?,
})
}
}
pub async fn init(cfg: &RpcContextConfig, product_key: &str) -> Result<(), Error> { pub async fn init(cfg: &RpcContextConfig, product_key: &str) -> Result<(), Error> {
let should_rebuild = tokio::fs::metadata(SYSTEM_REBUILD_PATH).await.is_ok(); let should_rebuild = tokio::fs::metadata(SYSTEM_REBUILD_PATH).await.is_ok();
let secret_store = cfg.secret_store().await?; let secret_store = cfg.secret_store().await?;
@@ -82,38 +126,30 @@ pub async fn init(cfg: &RpcContextConfig, product_key: &str) -> Result<(), Error
tracing::info!("Loaded Package Docker Images"); tracing::info!("Loaded Package Docker Images");
} }
crate::ssh::sync_keys_from_db(&secret_store, "/root/.ssh/authorized_keys").await?; crate::ssh::sync_keys_from_db(&secret_store, "/home/start9/.ssh/authorized_keys").await?;
tracing::info!("Synced SSH Keys"); tracing::info!("Synced SSH Keys");
let db = cfg.db(&secret_store, product_key).await?; let db = cfg.db(&secret_store, product_key).await?;
let mut handle = db.handle(); let mut handle = db.handle();
let receipts = InitReceipts::new(&mut handle).await?;
crate::net::wifi::synchronize_wpa_supplicant_conf( crate::net::wifi::synchronize_wpa_supplicant_conf(
&cfg.datadir().join("main"), &cfg.datadir().join("main"),
&*crate::db::DatabaseModel::new() &receipts.last_wifi_region.get(&mut handle).await?,
.server_info()
.last_wifi_region()
.get(&mut handle, false)
.await
.map_err(|_e| {
Error::new(
color_eyre::eyre::eyre!("Could not find the last wifi region"),
crate::ErrorKind::NotFound,
)
})?,
) )
.await?; .await?;
tracing::info!("Synchronized wpa_supplicant.conf"); tracing::info!("Synchronized wpa_supplicant.conf");
let mut info = crate::db::DatabaseModel::new() receipts
.server_info() .status_info
.get_mut(&mut handle) .set(
&mut handle,
ServerStatus {
updated: false,
update_progress: None,
backup_progress: None,
},
)
.await?; .await?;
info.status_info = ServerStatus {
backing_up: false,
updated: false,
update_progress: None,
};
info.save(&mut handle).await?;
let mut warn_time_not_synced = true; let mut warn_time_not_synced = true;
for _ in 0..60 { for _ in 0..60 {
@@ -125,13 +161,17 @@ pub async fn init(cfg: &RpcContextConfig, product_key: &str) -> Result<(), Error
} }
if warn_time_not_synced { if warn_time_not_synced {
tracing::warn!("Timed out waiting for system time to synchronize"); tracing::warn!("Timed out waiting for system time to synchronize");
} else {
tracing::info!("Syncronized system clock");
} }
crate::version::init(&mut handle).await?; crate::version::init(&mut handle, &receipts).await?;
if should_rebuild { if should_rebuild {
tokio::fs::remove_file(SYSTEM_REBUILD_PATH).await?; tokio::fs::remove_file(SYSTEM_REBUILD_PATH).await?;
} }
tracing::info!("System initialized.");
Ok(()) Ok(())
} }

View File

@@ -1,74 +1,96 @@
use std::collections::{BTreeMap, HashMap}; use std::collections::HashMap;
use bollard::image::ListImagesOptions; use bollard::image::ListImagesOptions;
use color_eyre::eyre::eyre; use patch_db::{DbHandle, LockReceipt, LockTargetId, LockType, PatchDbHandle, Verifier};
use patch_db::{DbHandle, LockType, PatchDbHandle};
use sqlx::{Executor, Sqlite}; use sqlx::{Executor, Sqlite};
use tracing::instrument; use tracing::instrument;
use super::{PKG_ARCHIVE_DIR, PKG_DOCKER_DIR}; use super::{PKG_ARCHIVE_DIR, PKG_DOCKER_DIR};
use crate::config::{not_found, ConfigReceipts};
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::db::model::{CurrentDependencyInfo, InstalledPackageDataEntry, PackageDataEntry}; use crate::db::model::{
use crate::dependencies::reconfigure_dependents_with_live_pointers; AllPackageData, CurrentDependencies, CurrentDependents, InstalledPackageDataEntry,
PackageDataEntry,
};
use crate::dependencies::{
reconfigure_dependents_with_live_pointers, DependencyErrors, TryHealReceipts,
};
use crate::error::ErrorCollection; use crate::error::ErrorCollection;
use crate::s9pk::manifest::{Manifest, PackageId}; use crate::s9pk::manifest::{Manifest, PackageId};
use crate::util::{Apply, Version}; use crate::util::{Apply, Version};
use crate::volume::{asset_dir, script_dir};
use crate::Error; use crate::Error;
#[instrument(skip(ctx, db, deps))] pub struct UpdateDependencyReceipts {
pub async fn update_dependency_errors_of_dependents< try_heal: TryHealReceipts,
'a, dependency_errors: LockReceipt<DependencyErrors, String>,
Db: DbHandle, manifest: LockReceipt<Manifest, String>,
I: IntoIterator<Item = &'a PackageId>, }
>( impl UpdateDependencyReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(locks: &mut Vec<LockTargetId>) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let dependency_errors = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.status().dependency_errors())
.make_locker(LockType::Write)
.add_to_keys(locks);
let manifest = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest())
.make_locker(LockType::Write)
.add_to_keys(locks);
let try_heal = TryHealReceipts::setup(locks);
move |skeleton_key| {
Ok(Self {
dependency_errors: dependency_errors.verify(skeleton_key)?,
manifest: manifest.verify(skeleton_key)?,
try_heal: try_heal(skeleton_key)?,
})
}
}
}
#[instrument(skip(ctx, db, deps, receipts))]
pub async fn update_dependency_errors_of_dependents<'a, Db: DbHandle>(
ctx: &RpcContext, ctx: &RpcContext,
db: &mut Db, db: &mut Db,
id: &PackageId, id: &PackageId,
deps: I, deps: &CurrentDependents,
receipts: &UpdateDependencyReceipts,
) -> Result<(), Error> { ) -> Result<(), Error> {
for dep in deps { for dep in deps.0.keys() {
if let Some(man) = &*crate::db::DatabaseModel::new() if let Some(man) = receipts.manifest.get(db, dep).await? {
.package_data()
.idx_model(&dep)
.and_then(|m| m.installed())
.map::<_, Manifest>(|m| m.manifest())
.get(db, true)
.await?
{
if let Err(e) = if let Some(info) = man.dependencies.0.get(id) { if let Err(e) = if let Some(info) = man.dependencies.0.get(id) {
info.satisfied(ctx, db, id, None, dep).await? info.satisfied(ctx, db, id, None, dep, &receipts.try_heal)
.await?
} else { } else {
Ok(()) Ok(())
} { } {
let mut errs = crate::db::DatabaseModel::new() let mut errs = receipts
.package_data() .dependency_errors
.idx_model(&dep) .get(db, dep)
.expect(db)
.await? .await?
.installed() .ok_or_else(not_found)?;
.expect(db)
.await?
.status()
.dependency_errors()
.get_mut(db)
.await?;
errs.0.insert(id.clone(), e); errs.0.insert(id.clone(), e);
errs.save(db).await?; receipts.dependency_errors.set(db, errs, dep).await?
} else { } else {
let mut errs = crate::db::DatabaseModel::new() let mut errs = receipts
.package_data() .dependency_errors
.idx_model(&dep) .get(db, dep)
.expect(db)
.await? .await?
.installed() .ok_or_else(not_found)?;
.expect(db)
.await?
.status()
.dependency_errors()
.get_mut(db)
.await?;
errs.0.remove(id); errs.0.remove(id);
errs.save(db).await?; receipts.dependency_errors.set(db, errs, dep).await?
} }
} }
} }
@@ -123,28 +145,66 @@ pub async fn cleanup(ctx: &RpcContext, id: &PackageId, version: &Version) -> Res
.await .await
.apply(|res| errors.handle(res)); .apply(|res| errors.handle(res));
} }
let assets_path = asset_dir(&ctx.datadir, id, version);
if tokio::fs::metadata(&assets_path).await.is_ok() {
tokio::fs::remove_dir_all(&assets_path)
.await
.apply(|res| errors.handle(res));
}
let scripts_path = script_dir(&ctx.datadir, id, version);
if tokio::fs::metadata(&scripts_path).await.is_ok() {
tokio::fs::remove_dir_all(&scripts_path)
.await
.apply(|res| errors.handle(res));
}
errors.into_result() errors.into_result()
} }
#[instrument(skip(ctx, db))] pub struct CleanupFailedReceipts {
package_data_entry: LockReceipt<PackageDataEntry, String>,
package_entries: LockReceipt<AllPackageData, ()>,
}
impl CleanupFailedReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(locks: &mut Vec<LockTargetId>) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let package_data_entry = crate::db::DatabaseModel::new()
.package_data()
.star()
.make_locker(LockType::Write)
.add_to_keys(locks);
let package_entries = crate::db::DatabaseModel::new()
.package_data()
.make_locker(LockType::Write)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
package_data_entry: package_data_entry.verify(skeleton_key).unwrap(),
package_entries: package_entries.verify(skeleton_key).unwrap(),
})
}
}
}
#[instrument(skip(ctx, db, receipts))]
pub async fn cleanup_failed<Db: DbHandle>( pub async fn cleanup_failed<Db: DbHandle>(
ctx: &RpcContext, ctx: &RpcContext,
db: &mut Db, db: &mut Db,
id: &PackageId, id: &PackageId,
receipts: &CleanupFailedReceipts,
) -> Result<(), Error> { ) -> Result<(), Error> {
crate::db::DatabaseModel::new() let pde = receipts
.package_data() .package_data_entry
.lock(db, LockType::Write) .get(db, id)
.await?;
let pde = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.expect(db)
.await? .await?
.get(db, true) .ok_or_else(not_found)?;
.await?
.into_owned();
if let Some(manifest) = match &pde { if let Some(manifest) = match &pde {
PackageDataEntry::Installing { manifest, .. } PackageDataEntry::Installing { manifest, .. }
| PackageDataEntry::Restoring { manifest, .. } => Some(manifest), | PackageDataEntry::Restoring { manifest, .. } => Some(manifest),
@@ -173,26 +233,25 @@ pub async fn cleanup_failed<Db: DbHandle>(
match pde { match pde {
PackageDataEntry::Installing { .. } | PackageDataEntry::Restoring { .. } => { PackageDataEntry::Installing { .. } | PackageDataEntry::Restoring { .. } => {
crate::db::DatabaseModel::new() let mut entries = receipts.package_entries.get(db).await?;
.package_data() entries.0.remove(id);
.remove(db, id) receipts.package_entries.set(db, entries).await?;
.await?;
} }
PackageDataEntry::Updating { PackageDataEntry::Updating {
installed, installed,
static_files, static_files,
.. ..
} => { } => {
crate::db::DatabaseModel::new() receipts
.package_data() .package_data_entry
.idx_model(id) .set(
.put(
db, db,
&PackageDataEntry::Installed { PackageDataEntry::Installed {
manifest: installed.manifest.clone(), manifest: installed.manifest.clone(),
installed, installed,
static_files, static_files,
}, },
id,
) )
.await?; .await?;
} }
@@ -202,38 +261,74 @@ pub async fn cleanup_failed<Db: DbHandle>(
Ok(()) Ok(())
} }
#[instrument(skip(db, current_dependencies))] #[instrument(skip(db, current_dependencies, current_dependent_receipt))]
pub async fn remove_from_current_dependents_lists< pub async fn remove_from_current_dependents_lists<'a, Db: DbHandle>(
'a,
Db: DbHandle,
I: IntoIterator<Item = &'a PackageId>,
>(
db: &mut Db, db: &mut Db,
id: &'a PackageId, id: &'a PackageId,
current_dependencies: I, current_dependencies: &'a CurrentDependencies,
current_dependent_receipt: &LockReceipt<CurrentDependents, String>,
) -> Result<(), Error> { ) -> Result<(), Error> {
for dep in current_dependencies.into_iter().chain(std::iter::once(id)) { for dep in current_dependencies.0.keys().chain(std::iter::once(id)) {
if let Some(current_dependents) = crate::db::DatabaseModel::new() if let Some(mut current_dependents) = current_dependent_receipt.get(db, dep).await? {
.package_data() if current_dependents.0.remove(id).is_some() {
.idx_model(dep) current_dependent_receipt
.and_then(|m| m.installed()) .set(db, current_dependents, dep)
.map::<_, BTreeMap<PackageId, CurrentDependencyInfo>>(|m| m.current_dependents()) .await?;
.check(db)
.await?
{
if current_dependents
.clone()
.idx_model(id)
.exists(db, true)
.await?
{
current_dependents.remove(db, id).await?
} }
} }
} }
Ok(()) Ok(())
} }
pub struct UninstallReceipts {
config: ConfigReceipts,
removing: LockReceipt<InstalledPackageDataEntry, ()>,
packages: LockReceipt<AllPackageData, ()>,
current_dependents: LockReceipt<CurrentDependents, String>,
update_depenency_receipts: UpdateDependencyReceipts,
}
impl UninstallReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle, id: &PackageId) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks, id);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<LockTargetId>,
id: &PackageId,
) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let config = ConfigReceipts::setup(locks);
let removing = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|pde| pde.removing())
.make_locker(LockType::Write)
.add_to_keys(locks);
let current_dependents = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.current_dependents())
.make_locker(LockType::Write)
.add_to_keys(locks);
let packages = crate::db::DatabaseModel::new()
.package_data()
.make_locker(LockType::Write)
.add_to_keys(locks);
let update_depenency_receipts = UpdateDependencyReceipts::setup(locks);
move |skeleton_key| {
Ok(Self {
config: config(skeleton_key)?,
removing: removing.verify(skeleton_key)?,
current_dependents: current_dependents.verify(skeleton_key)?,
update_depenency_receipts: update_depenency_receipts(skeleton_key)?,
packages: packages.verify(skeleton_key)?,
})
}
}
}
#[instrument(skip(ctx, secrets, db))] #[instrument(skip(ctx, secrets, db))]
pub async fn uninstall<Ex>( pub async fn uninstall<Ex>(
ctx: &RpcContext, ctx: &RpcContext,
@@ -245,44 +340,32 @@ where
for<'a> &'a mut Ex: Executor<'a, Database = Sqlite>, for<'a> &'a mut Ex: Executor<'a, Database = Sqlite>,
{ {
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
crate::db::DatabaseModel::new() let receipts = UninstallReceipts::new(&mut tx, id).await?;
.package_data() let entry = receipts.removing.get(&mut tx).await?;
.lock(&mut tx, LockType::Write)
.await?;
let entry = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|pde| pde.removing())
.get(&mut tx, true)
.await?
.into_owned()
.ok_or_else(|| {
Error::new(
eyre!("Package not in removing state: {}", id),
crate::ErrorKind::NotFound,
)
})?;
cleanup(ctx, &entry.manifest.id, &entry.manifest.version).await?; cleanup(ctx, &entry.manifest.id, &entry.manifest.version).await?;
crate::db::DatabaseModel::new() let packages = {
.package_data() let mut packages = receipts.packages.get(&mut tx).await?;
.remove(&mut tx, id) packages.0.remove(id);
.await?; packages
};
receipts.packages.set(&mut tx, packages).await?;
// once we have removed the package entry, we can change all the dependent pointers to null // once we have removed the package entry, we can change all the dependent pointers to null
reconfigure_dependents_with_live_pointers(ctx, &mut tx, &entry).await?; reconfigure_dependents_with_live_pointers(ctx, &mut tx, &receipts.config, &entry).await?;
remove_from_current_dependents_lists( remove_from_current_dependents_lists(
&mut tx, &mut tx,
&entry.manifest.id, &entry.manifest.id,
entry.current_dependencies.keys(), &entry.current_dependencies,
&receipts.current_dependents,
) )
.await?; .await?;
update_dependency_errors_of_dependents( update_dependency_errors_of_dependents(
ctx, ctx,
&mut tx, &mut tx,
&entry.manifest.id, &entry.manifest.id,
entry.current_dependents.keys(), &entry.current_dependents,
&receipts.update_depenency_receipts,
) )
.await?; .await?;
let volumes = ctx let volumes = ctx

View File

@@ -1,4 +1,4 @@
use std::collections::{BTreeMap, BTreeSet}; use std::collections::BTreeMap;
use std::io::SeekFrom; use std::io::SeekFrom;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -14,7 +14,7 @@ use futures::{FutureExt, StreamExt, TryStreamExt};
use http::header::CONTENT_LENGTH; use http::header::CONTENT_LENGTH;
use http::{Request, Response, StatusCode}; use http::{Request, Response, StatusCode};
use hyper::Body; use hyper::Body;
use patch_db::{DbHandle, LockType}; use patch_db::{DbHandle, LockReceipt, LockType};
use reqwest::Url; use reqwest::Url;
use rpc_toolkit::yajrc::RpcError; use rpc_toolkit::yajrc::RpcError;
use rpc_toolkit::{command, Context}; use rpc_toolkit::{command, Context};
@@ -25,16 +25,18 @@ use tokio_stream::wrappers::ReadDirStream;
use tracing::instrument; use tracing::instrument;
use self::cleanup::{cleanup_failed, remove_from_current_dependents_lists}; use self::cleanup::{cleanup_failed, remove_from_current_dependents_lists};
use crate::config::ConfigReceipts;
use crate::context::{CliContext, RpcContext}; use crate::context::{CliContext, RpcContext};
use crate::core::rpc_continuations::{RequestGuid, RpcContinuation}; use crate::core::rpc_continuations::{RequestGuid, RpcContinuation};
use crate::db::model::{ use crate::db::model::{
CurrentDependencyInfo, InstalledPackageDataEntry, PackageDataEntry, RecoveredPackageInfo, CurrentDependencies, CurrentDependencyInfo, CurrentDependents, InstalledPackageDataEntry,
StaticDependencyInfo, StaticFiles, PackageDataEntry, RecoveredPackageInfo, StaticDependencyInfo, StaticFiles,
}; };
use crate::db::util::WithRevision; use crate::db::util::WithRevision;
use crate::dependencies::{ use crate::dependencies::{
add_dependent_to_current_dependents_lists, break_all_dependents_transitive, add_dependent_to_current_dependents_lists, break_all_dependents_transitive,
reconfigure_dependents_with_live_pointers, BreakageRes, DependencyError, DependencyErrors, reconfigure_dependents_with_live_pointers, BreakTransitiveReceipts, BreakageRes,
DependencyError, DependencyErrors,
}; };
use crate::install::cleanup::{cleanup, update_dependency_errors_of_dependents}; use crate::install::cleanup::{cleanup, update_dependency_errors_of_dependents};
use crate::install::progress::{InstallProgress, InstallProgressTracker}; use crate::install::progress::{InstallProgress, InstallProgressTracker};
@@ -43,20 +45,20 @@ use crate::s9pk::manifest::{Manifest, PackageId};
use crate::s9pk::reader::S9pkReader; use crate::s9pk::reader::S9pkReader;
use crate::status::{MainStatus, Status}; use crate::status::{MainStatus, Status};
use crate::util::io::{copy_and_shutdown, response_to_reader}; use crate::util::io::{copy_and_shutdown, response_to_reader};
use crate::util::serde::{display_serializable, IoFormat, Port}; use crate::util::serde::{display_serializable, Port};
use crate::util::{display_none, AsyncFileExt, Version}; use crate::util::{display_none, AsyncFileExt, Version};
use crate::version::{Current, VersionT}; use crate::version::{Current, VersionT};
use crate::volume::asset_dir; use crate::volume::{asset_dir, script_dir};
use crate::{Error, ErrorKind, ResultExt}; use crate::{Error, ErrorKind, ResultExt};
pub mod cleanup; pub mod cleanup;
pub mod progress; pub mod progress;
pub mod update; pub mod update;
pub const PKG_ARCHIVE_DIR: &'static str = "package-data/archive"; pub const PKG_ARCHIVE_DIR: &str = "package-data/archive";
pub const PKG_PUBLIC_DIR: &'static str = "package-data/public"; pub const PKG_PUBLIC_DIR: &str = "package-data/public";
pub const PKG_DOCKER_DIR: &'static str = "package-data/docker"; pub const PKG_DOCKER_DIR: &str = "package-data/docker";
pub const PKG_WASM_DIR: &'static str = "package-data/wasm"; pub const PKG_WASM_DIR: &str = "package-data/wasm";
#[command(display(display_serializable))] #[command(display(display_serializable))]
pub async fn list(#[context] ctx: RpcContext) -> Result<Vec<(PackageId, Version)>, Error> { pub async fn list(#[context] ctx: RpcContext) -> Result<Vec<(PackageId, Version)>, Error> {
@@ -119,9 +121,9 @@ impl std::fmt::Display for MinMax {
pub async fn install( pub async fn install(
#[context] ctx: RpcContext, #[context] ctx: RpcContext,
#[arg] id: String, #[arg] id: String,
#[arg(short = "m", long = "marketplace-url", rename = "marketplace-url")] #[arg(short = 'm', long = "marketplace-url", rename = "marketplace-url")]
marketplace_url: Option<Url>, marketplace_url: Option<Url>,
#[arg(short = "v", long = "version-spec", rename = "version-spec")] version_spec: Option< #[arg(short = 'v', long = "version-spec", rename = "version-spec")] version_spec: Option<
String, String,
>, >,
#[arg(long = "version-priority", rename = "version-priority")] version_priority: Option<MinMax>, #[arg(long = "version-priority", rename = "version-priority")] version_priority: Option<MinMax>,
@@ -141,7 +143,7 @@ pub async fn install(
version, version,
version_priority, version_priority,
Current::new().compat(), Current::new().compat(),
platforms::TARGET_ARCH, &*crate::ARCH,
)) ))
.await .await
.with_kind(crate::ErrorKind::Registry)? .with_kind(crate::ErrorKind::Registry)?
@@ -157,7 +159,7 @@ pub async fn install(
man.version, man.version,
version_priority, version_priority,
Current::new().compat(), Current::new().compat(),
platforms::TARGET_ARCH, &*crate::ARCH,
)) ))
.await .await
.with_kind(crate::ErrorKind::Registry)? .with_kind(crate::ErrorKind::Registry)?
@@ -189,9 +191,10 @@ pub async fn install(
id, id,
man.version, man.version,
Current::new().compat(), Current::new().compat(),
platforms::TARGET_ARCH, &*crate::ARCH,
)) ))
.await?, .await?
.error_for_status()?,
), ),
&mut File::create(public_dir_path.join("LICENSE.md")).await?, &mut File::create(public_dir_path.join("LICENSE.md")).await?,
) )
@@ -207,9 +210,10 @@ pub async fn install(
id, id,
man.version, man.version,
Current::new().compat(), Current::new().compat(),
platforms::TARGET_ARCH, &*crate::ARCH,
)) ))
.await?, .await?
.error_for_status()?,
), ),
&mut File::create(public_dir_path.join("INSTRUCTIONS.md")).await?, &mut File::create(public_dir_path.join("INSTRUCTIONS.md")).await?,
) )
@@ -225,9 +229,10 @@ pub async fn install(
id, id,
man.version, man.version,
Current::new().compat(), Current::new().compat(),
platforms::TARGET_ARCH, &*crate::ARCH,
)) ))
.await?, .await?
.error_for_status()?,
), ),
&mut File::create(public_dir_path.join(format!("icon.{}", icon_type))).await?, &mut File::create(public_dir_path.join(format!("icon.{}", icon_type))).await?,
) )
@@ -329,9 +334,37 @@ pub async fn install(
pub async fn sideload( pub async fn sideload(
#[context] ctx: RpcContext, #[context] ctx: RpcContext,
#[arg] manifest: Manifest, #[arg] manifest: Manifest,
#[arg] icon: Option<String>,
) -> Result<RequestGuid, Error> { ) -> Result<RequestGuid, Error> {
let new_ctx = ctx.clone(); let new_ctx = ctx.clone();
let guid = RequestGuid::new(); let guid = RequestGuid::new();
if let Some(icon) = icon {
use tokio::io::AsyncWriteExt;
let public_dir_path = ctx
.datadir
.join(PKG_PUBLIC_DIR)
.join(&manifest.id)
.join(manifest.version.as_str());
tokio::fs::create_dir_all(&public_dir_path).await?;
let invalid_data_url =
|| Error::new(eyre!("Invalid Icon Data URL"), ErrorKind::InvalidRequest);
let data = icon
.strip_prefix(&format!(
"data:image/{};base64,",
manifest.assets.icon_type()
))
.ok_or_else(&invalid_data_url)?;
let mut icon_file =
File::create(public_dir_path.join(format!("icon.{}", manifest.assets.icon_type())))
.await?;
icon_file
.write_all(&base64::decode(data).with_kind(ErrorKind::InvalidRequest)?)
.await?;
icon_file.sync_all().await?;
}
let handler = Box::new(|req: Request<Body>| { let handler = Box::new(|req: Request<Body>| {
async move { async move {
let content_length = match req.headers().get(CONTENT_LENGTH).map(|a| a.to_str()) { let content_length = match req.headers().get(CONTENT_LENGTH).map(|a| a.to_str()) {
@@ -447,7 +480,7 @@ pub async fn sideload(
}); });
let cont = RpcContinuation { let cont = RpcContinuation {
created_at: Instant::now(), // TODO created_at: Instant::now(), // TODO
handler: handler, handler,
}; };
// gc the map // gc the map
let mut guard = ctx.rpc_stream_continuations.lock().await; let mut guard = ctx.rpc_stream_continuations.lock().await;
@@ -477,14 +510,21 @@ async fn cli_install(
let path = PathBuf::from(target); let path = PathBuf::from(target);
// inspect manifest no verify // inspect manifest no verify
let manifest = crate::inspect::manifest(path.clone(), true, Some(IoFormat::Json)).await?; let mut reader = S9pkReader::open(&path, false).await?;
let manifest = reader.manifest().await?;
let icon = reader.icon().await?.to_vec().await?;
let icon_str = format!(
"data:image/{};base64,{}",
manifest.assets.icon_type(),
base64::encode(&icon)
);
// rpc call remote sideload // rpc call remote sideload
tracing::debug!("calling package.sideload"); tracing::debug!("calling package.sideload");
let guid = rpc_toolkit::command_helpers::call_remote( let guid = rpc_toolkit::command_helpers::call_remote(
ctx.clone(), ctx.clone(),
"package.sideload", "package.sideload",
serde_json::json!({ "manifest": manifest }), serde_json::json!({ "manifest": manifest, "icon": icon_str }),
PhantomData::<RequestGuid>, PhantomData::<RequestGuid>,
) )
.await? .await?
@@ -495,8 +535,8 @@ async fn cli_install(
let file = tokio::fs::File::open(path).await?; let file = tokio::fs::File::open(path).await?;
let content_length = file.metadata().await?.len(); let content_length = file.metadata().await?.len();
let body = Body::wrap_stream(tokio_util::io::ReaderStream::new(file)); let body = Body::wrap_stream(tokio_util::io::ReaderStream::new(file));
let client = reqwest::Client::new(); let res = ctx
let res = client .client
.post(format!( .post(format!(
"{}://{}/rest/rpc/{}", "{}://{}/rest/rpc/{}",
ctx.protocol(), ctx.protocol(),
@@ -562,8 +602,15 @@ pub async fn uninstall_dry(
let mut db = ctx.db.handle(); let mut db = ctx.db.handle();
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
let mut breakages = BTreeMap::new(); let mut breakages = BTreeMap::new();
break_all_dependents_transitive(&mut tx, &id, DependencyError::NotInstalled, &mut breakages) let receipts = BreakTransitiveReceipts::new(&mut tx).await?;
.await?; break_all_dependents_transitive(
&mut tx,
&id,
DependencyError::NotInstalled,
&mut breakages,
&receipts,
)
.await?;
tx.abort().await?; tx.abort().await?;
@@ -678,6 +725,35 @@ pub async fn delete_recovered(
}) })
} }
pub struct DownloadInstallReceipts {
package_receipts: crate::db::package::PackageReceipts,
manifest_receipts: crate::db::package::ManifestReceipts,
}
impl DownloadInstallReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle, id: &PackageId) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks, id);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
id: &PackageId,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
let package_receipts = crate::db::package::PackageReceipts::setup(locks);
let manifest_receipts = crate::db::package::ManifestReceipts::setup(locks, id);
move |skeleton_key| {
Ok(Self {
package_receipts: package_receipts(skeleton_key)?,
manifest_receipts: manifest_receipts(skeleton_key)?,
})
}
}
}
#[instrument(skip(ctx, temp_manifest, s9pk))] #[instrument(skip(ctx, temp_manifest, s9pk))]
pub async fn download_install_s9pk( pub async fn download_install_s9pk(
ctx: &RpcContext, ctx: &RpcContext,
@@ -692,14 +768,14 @@ pub async fn download_install_s9pk(
if let Err(e) = async { if let Err(e) = async {
let mut db_handle = ctx.db.handle(); let mut db_handle = ctx.db.handle();
let mut tx = db_handle.begin().await?; let mut tx = db_handle.begin().await?;
let receipts = DownloadInstallReceipts::new(&mut tx, &pkg_id).await?;
// Build set of existing manifests // Build set of existing manifests
let mut manifests = Vec::new(); let mut manifests = Vec::new();
for pkg in crate::db::package::get_packages(&mut tx).await? { for pkg in crate::db::package::get_packages(&mut tx, &receipts.package_receipts).await? {
match crate::db::package::get_manifest(&mut tx, &pkg).await? { if let Some(m) =
Some(m) => { crate::db::package::get_manifest(&mut tx, &pkg, &receipts.manifest_receipts).await?
manifests.push(m); {
} manifests.push(m);
None => {}
} }
} }
// Build map of current port -> ssl mappings // Build map of current port -> ssl mappings
@@ -732,6 +808,7 @@ pub async fn download_install_s9pk(
} }
} }
} }
drop(receipts);
tx.save().await?; tx.save().await?;
drop(db_handle); drop(db_handle);
@@ -792,8 +869,9 @@ pub async fn download_install_s9pk(
{ {
let mut handle = ctx.db.handle(); let mut handle = ctx.db.handle();
let mut tx = handle.begin().await?; let mut tx = handle.begin().await?;
let receipts = cleanup::CleanupFailedReceipts::new(&mut tx).await?;
if let Err(e) = cleanup_failed(&ctx, &mut tx, pkg_id).await { if let Err(e) = cleanup_failed(&ctx, &mut tx, pkg_id, &receipts).await {
tracing::error!("Failed to clean up {}@{}: {}", pkg_id, version, e); tracing::error!("Failed to clean up {}@{}: {}", pkg_id, version, e);
tracing::debug!("{:?}", e); tracing::debug!("{:?}", e);
} else { } else {
@@ -805,6 +883,39 @@ pub async fn download_install_s9pk(
} }
} }
pub struct InstallS9Receipts {
config: ConfigReceipts,
recovered_packages: LockReceipt<BTreeMap<PackageId, RecoveredPackageInfo>, ()>,
}
impl InstallS9Receipts {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
let config = ConfigReceipts::setup(locks);
let recovered_packages = crate::db::DatabaseModel::new()
.recovered_packages()
.make_locker(LockType::Write)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
config: config(skeleton_key)?,
recovered_packages: recovered_packages.verify(skeleton_key)?,
})
}
}
}
#[instrument(skip(ctx, rdr))] #[instrument(skip(ctx, rdr))]
pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>( pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
ctx: &RpcContext, ctx: &RpcContext,
@@ -848,7 +959,7 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
dep, dep,
info.version, info.version,
Current::new().compat(), Current::new().compat(),
platforms::TARGET_ARCH, &*crate::ARCH,
)) ))
.await .await
.with_kind(crate::ErrorKind::Registry)? .with_kind(crate::ErrorKind::Registry)?
@@ -883,7 +994,7 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
dep, dep,
info.version, info.version,
Current::new().compat(), Current::new().compat(),
platforms::TARGET_ARCH, &*crate::ARCH,
)) ))
.await .await
.with_kind(crate::ErrorKind::Registry)?; .with_kind(crate::ErrorKind::Registry)?;
@@ -1046,6 +1157,18 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
let mut tar = tokio_tar::Archive::new(rdr.assets().await?); let mut tar = tokio_tar::Archive::new(rdr.assets().await?);
tar.unpack(asset_dir).await?; tar.unpack(asset_dir).await?;
let script_dir = script_dir(&ctx.datadir, pkg_id, version);
if tokio::fs::metadata(&script_dir).await.is_err() {
tokio::fs::create_dir_all(&script_dir).await?;
}
if let Some(mut hdl) = rdr.scripts().await? {
tokio::io::copy(
&mut hdl,
&mut File::create(dbg!(script_dir.join("embassy.js"))).await?,
)
.await?;
}
Ok(()) Ok(())
}) })
.await?; .await?;
@@ -1082,18 +1205,20 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
tracing::info!("Install {}@{}: Created manager", pkg_id, version); tracing::info!("Install {}@{}: Created manager", pkg_id, version);
let static_files = StaticFiles::local(pkg_id, version, manifest.assets.icon_type()); let static_files = StaticFiles::local(pkg_id, version, manifest.assets.icon_type());
let current_dependencies: BTreeMap<_, _> = manifest let current_dependencies: CurrentDependencies = CurrentDependencies(
.dependencies manifest
.0 .dependencies
.iter() .0
.filter_map(|(id, info)| { .iter()
if info.requirement.required() { .filter_map(|(id, info)| {
Some((id.clone(), CurrentDependencyInfo::default())) if info.requirement.required() {
} else { Some((id.clone(), CurrentDependencyInfo::default()))
None } else {
} None
}) }
.collect(); })
.collect(),
);
let current_dependents = { let current_dependents = {
let mut deps = BTreeMap::new(); let mut deps = BTreeMap::new();
for package in crate::db::DatabaseModel::new() for package in crate::db::DatabaseModel::new()
@@ -1139,7 +1264,7 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
deps.insert(package, dep); deps.insert(package, dep);
} }
} }
deps CurrentDependents(deps)
}; };
let mut pde = model let mut pde = model
.clone() .clone()
@@ -1183,6 +1308,8 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
}, },
); );
pde.save(&mut tx).await?; pde.save(&mut tx).await?;
let receipts = InstallS9Receipts::new(&mut tx).await?;
// UpdateDependencyReceipts
let mut dep_errs = model let mut dep_errs = model
.expect(&mut tx) .expect(&mut tx)
.await? .await?
@@ -1193,7 +1320,14 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
.dependency_errors() .dependency_errors()
.get_mut(&mut tx) .get_mut(&mut tx)
.await?; .await?;
*dep_errs = DependencyErrors::init(ctx, &mut tx, &manifest, &current_dependencies).await?; *dep_errs = DependencyErrors::init(
ctx,
&mut tx,
&manifest,
&current_dependencies,
&receipts.config.try_heal_receipts,
)
.await?;
dep_errs.save(&mut tx).await?; dep_errs.save(&mut tx).await?;
if let PackageDataEntry::Updating { if let PackageDataEntry::Updating {
@@ -1244,8 +1378,26 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
false, false,
&mut BTreeMap::new(), &mut BTreeMap::new(),
&mut BTreeMap::new(), &mut BTreeMap::new(),
&receipts.config,
) )
.await?; .await?;
} else {
remove_from_current_dependents_lists(
&mut tx,
pkg_id,
&prev.current_dependencies,
&receipts.config.current_dependents,
)
.await?; // remove previous
add_dependent_to_current_dependents_lists(
&mut tx,
pkg_id,
&current_dependencies,
&receipts.config.current_dependents,
)
.await?; // add new
}
if configured || manifest.config.is_none() {
let mut main_status = crate::db::DatabaseModel::new() let mut main_status = crate::db::DatabaseModel::new()
.package_data() .package_data()
.idx_model(pkg_id) .idx_model(pkg_id)
@@ -1261,17 +1413,16 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
*main_status = prev.status.main; *main_status = prev.status.main;
main_status.save(&mut tx).await?; main_status.save(&mut tx).await?;
} }
remove_from_current_dependents_lists(&mut tx, pkg_id, prev.current_dependencies.keys())
.await?; // remove previous
add_dependent_to_current_dependents_lists(&mut tx, pkg_id, &current_dependencies).await?; // add new
update_dependency_errors_of_dependents( update_dependency_errors_of_dependents(
ctx, ctx,
&mut tx, &mut tx,
pkg_id, pkg_id,
current_dependents &CurrentDependents({
.keys() let mut current_dependents = current_dependents.0.clone();
.chain(prev.current_dependents.keys()) current_dependents.append(&mut prev.current_dependents.0.clone());
.collect::<BTreeSet<_>>(), current_dependents
}),
&receipts.config.update_dependency_receipts,
) )
.await?; .await?;
if &prev.manifest.version != version { if &prev.manifest.version != version {
@@ -1290,39 +1441,84 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
&manifest.volumes, &manifest.volumes,
) )
.await?; .await?;
add_dependent_to_current_dependents_lists(&mut tx, pkg_id, &current_dependencies).await?; add_dependent_to_current_dependents_lists(
update_dependency_errors_of_dependents(ctx, &mut tx, pkg_id, current_dependents.keys()) &mut tx,
.await?; pkg_id,
&current_dependencies,
&receipts.config.current_dependents,
)
.await?;
update_dependency_errors_of_dependents(
ctx,
&mut tx,
pkg_id,
&current_dependents,
&receipts.config.update_dependency_receipts,
)
.await?;
} else if let Some(recovered) = { } else if let Some(recovered) = {
// solve taxonomy escalation receipts
crate::db::DatabaseModel::new() .recovered_packages
.recovered_packages() .get(&mut tx)
.lock(&mut tx, LockType::Write)
.await?;
crate::db::DatabaseModel::new()
.recovered_packages()
.idx_model(pkg_id)
.get(&mut tx, true)
.await? .await?
.into_owned() .remove(pkg_id)
} { } {
handle_recovered_package(recovered, manifest, ctx, pkg_id, version, &mut tx).await?; handle_recovered_package(
add_dependent_to_current_dependents_lists(&mut tx, pkg_id, &current_dependencies).await?; recovered,
update_dependency_errors_of_dependents(ctx, &mut tx, pkg_id, current_dependents.keys()) manifest,
.await?; ctx,
pkg_id,
version,
&mut tx,
&receipts.config,
)
.await?;
add_dependent_to_current_dependents_lists(
&mut tx,
pkg_id,
&current_dependencies,
&receipts.config.current_dependents,
)
.await?;
update_dependency_errors_of_dependents(
ctx,
&mut tx,
pkg_id,
&current_dependents,
&receipts.config.update_dependency_receipts,
)
.await?;
} else { } else {
add_dependent_to_current_dependents_lists(&mut tx, pkg_id, &current_dependencies).await?; add_dependent_to_current_dependents_lists(
update_dependency_errors_of_dependents(ctx, &mut tx, pkg_id, current_dependents.keys()) &mut tx,
.await?; pkg_id,
&current_dependencies,
&receipts.config.current_dependents,
)
.await?;
update_dependency_errors_of_dependents(
ctx,
&mut tx,
pkg_id,
&current_dependents,
&receipts.config.update_dependency_receipts,
)
.await?;
} }
crate::db::DatabaseModel::new() let recovered_packages = {
.recovered_packages() let mut r = receipts.recovered_packages.get(&mut tx).await?;
.remove(&mut tx, pkg_id) r.remove(pkg_id);
r
};
receipts
.recovered_packages
.set(&mut tx, recovered_packages)
.await?; .await?;
if let Some(installed) = pde.installed() { if let Some(installed) = pde.installed() {
reconfigure_dependents_with_live_pointers(ctx, &mut tx, installed).await?; reconfigure_dependents_with_live_pointers(ctx, &mut tx, &receipts.config, installed)
.await?;
} }
sql_tx.commit().await?; sql_tx.commit().await?;
@@ -1333,7 +1529,7 @@ pub async fn install_s9pk<R: AsyncRead + AsyncSeek + Unpin>(
Ok(()) Ok(())
} }
#[instrument(skip(ctx, tx))] #[instrument(skip(ctx, tx, receipts))]
async fn handle_recovered_package( async fn handle_recovered_package(
recovered: RecoveredPackageInfo, recovered: RecoveredPackageInfo,
manifest: Manifest, manifest: Manifest,
@@ -1341,6 +1537,7 @@ async fn handle_recovered_package(
pkg_id: &PackageId, pkg_id: &PackageId,
version: &Version, version: &Version,
tx: &mut patch_db::Transaction<&mut patch_db::PatchDbHandle>, tx: &mut patch_db::Transaction<&mut patch_db::PatchDbHandle>,
receipts: &ConfigReceipts,
) -> Result<(), Error> { ) -> Result<(), Error> {
let configured = if let Some(migration) = let configured = if let Some(migration) =
manifest manifest
@@ -1361,6 +1558,7 @@ async fn handle_recovered_package(
false, false,
&mut BTreeMap::new(), &mut BTreeMap::new(),
&mut BTreeMap::new(), &mut BTreeMap::new(),
&receipts,
) )
.await?; .await?;
} }

View File

@@ -44,10 +44,14 @@ impl InstallProgress {
mut db: Db, mut db: Db,
) -> Result<(), Error> { ) -> Result<(), Error> {
while !self.download_complete.load(Ordering::SeqCst) { while !self.download_complete.load(Ordering::SeqCst) {
model.put(&mut db, &self).await?; let mut tx = db.begin().await?;
model.put(&mut tx, &self).await?;
tx.save().await?;
tokio::time::sleep(Duration::from_secs(1)).await; tokio::time::sleep(Duration::from_secs(1)).await;
} }
model.put(&mut db, &self).await?; let mut tx = db.begin().await?;
model.put(&mut tx, &self).await?;
tx.save().await?;
Ok(()) Ok(())
} }
pub async fn track_download_during< pub async fn track_download_during<
@@ -74,10 +78,14 @@ impl InstallProgress {
complete: Arc<AtomicBool>, complete: Arc<AtomicBool>,
) -> Result<(), Error> { ) -> Result<(), Error> {
while !complete.load(Ordering::SeqCst) { while !complete.load(Ordering::SeqCst) {
model.put(&mut db, &self).await?; let mut tx = db.begin().await?;
model.put(&mut tx, &self).await?;
tx.save().await?;
tokio::time::sleep(Duration::from_secs(1)).await; tokio::time::sleep(Duration::from_secs(1)).await;
} }
model.put(&mut db, &self).await?; let mut tx = db.begin().await?;
model.put(&mut tx, &self).await?;
tx.save().await?;
Ok(()) Ok(())
} }
pub async fn track_read_during< pub async fn track_read_during<

View File

@@ -1,20 +1,66 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use patch_db::{DbHandle, LockType}; use patch_db::{DbHandle, LockReceipt, LockTargetId, LockType, Verifier};
use rpc_toolkit::command; use rpc_toolkit::command;
use tracing::instrument;
use crate::config::not_found;
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::dependencies::{break_transitive, BreakageRes, DependencyError}; use crate::db::model::CurrentDependents;
use crate::dependencies::{
break_transitive, BreakTransitiveReceipts, BreakageRes, DependencyError,
};
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::util::serde::display_serializable; use crate::util::serde::display_serializable;
use crate::util::Version; use crate::util::Version;
use crate::Error; use crate::Error;
pub struct UpdateReceipts {
break_receipts: BreakTransitiveReceipts,
current_dependents: LockReceipt<CurrentDependents, String>,
dependency: LockReceipt<crate::dependencies::DepInfo, (String, String)>,
}
impl UpdateReceipts {
pub async fn new<'a>(db: &'a mut impl DbHandle) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks);
Ok(setup(&db.lock_all(locks).await?)?)
}
pub fn setup(locks: &mut Vec<LockTargetId>) -> impl FnOnce(&Verifier) -> Result<Self, Error> {
let break_receipts = BreakTransitiveReceipts::setup(locks);
let current_dependents = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.current_dependents())
.make_locker(LockType::Write)
.add_to_keys(locks);
let dependency = crate::db::DatabaseModel::new()
.package_data()
.star()
.installed()
.map(|x| x.manifest().dependencies().star())
.make_locker(LockType::Write)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
break_receipts: break_receipts(skeleton_key)?,
current_dependents: current_dependents.verify(skeleton_key)?,
dependency: dependency.verify(skeleton_key)?,
})
}
}
}
#[command(subcommands(dry))] #[command(subcommands(dry))]
pub async fn update() -> Result<(), Error> { pub async fn update() -> Result<(), Error> {
Ok(()) Ok(())
} }
#[instrument(skip(ctx))]
#[command(display(display_serializable))] #[command(display(display_serializable))]
pub async fn dry( pub async fn dry(
#[context] ctx: RpcContext, #[context] ctx: RpcContext,
@@ -24,49 +70,34 @@ pub async fn dry(
let mut db = ctx.db.handle(); let mut db = ctx.db.handle();
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
let mut breakages = BTreeMap::new(); let mut breakages = BTreeMap::new();
crate::db::DatabaseModel::new() let receipts = UpdateReceipts::new(&mut tx).await?;
.package_data()
.lock(&mut tx, LockType::Read) for dependent in receipts
.await?; .current_dependents
for dependent in crate::db::DatabaseModel::new() .get(&mut tx, &id)
.package_data()
.idx_model(&id)
.and_then(|m| m.installed())
.expect(&mut tx)
.await?
.current_dependents()
.keys(&mut tx, true)
.await? .await?
.ok_or_else(not_found)?
.0
.keys()
.into_iter() .into_iter()
.filter(|dependent| &id != dependent) .filter(|dependent| &&id != dependent)
{ {
let version_req = crate::db::DatabaseModel::new() if let Some(dep_info) = receipts.dependency.get(&mut tx, (&dependent, &id)).await? {
.package_data() let version_req = dep_info.version;
.idx_model(&dependent) if !version.satisfies(&version_req) {
.and_then(|m| m.installed()) break_transitive(
.expect(&mut tx) &mut tx,
.await? &dependent,
.manifest() &id,
.dependencies() DependencyError::IncorrectVersion {
.idx_model(&id) expected: version_req,
.expect(&mut tx) received: version.clone(),
.await? },
.get(&mut tx, true) &mut breakages,
.await? &receipts.break_receipts,
.into_owned() )
.version; .await?;
if !version.satisfies(&version_req) { }
break_transitive(
&mut tx,
&dependent,
&id,
DependencyError::IncorrectVersion {
expected: version_req,
received: version.clone(),
},
&mut breakages,
)
.await?;
} }
} }
tx.abort().await?; tx.abort().await?;

View File

@@ -1,10 +1,13 @@
pub const CONFIG_PATH: &str = "/etc/embassy/config.yaml";
#[cfg(not(feature = "beta"))]
pub const DEFAULT_MARKETPLACE: &str = "https://marketplace.start9.com"; pub const DEFAULT_MARKETPLACE: &str = "https://marketplace.start9.com";
#[cfg(feature = "beta")]
pub const DEFAULT_MARKETPLACE: &str = "https://beta-registry-0-3.start9labs.com";
pub const BUFFER_SIZE: usize = 1024; pub const BUFFER_SIZE: usize = 1024;
pub const HOST_IP: [u8; 4] = [172, 18, 0, 1]; pub const HOST_IP: [u8; 4] = [172, 18, 0, 1];
pub const TARGET: &str = current_platform::CURRENT_PLATFORM;
lazy_static::lazy_static! {
pub static ref ARCH: &'static str = {
let (arch, _) = TARGET.split_once("-").unwrap();
arch
};
}
pub mod action; pub mod action;
pub mod auth; pub mod auth;
@@ -31,6 +34,7 @@ pub mod middleware;
pub mod migration; pub mod migration;
pub mod net; pub mod net;
pub mod notifications; pub mod notifications;
pub mod procedure;
pub mod properties; pub mod properties;
pub mod s9pk; pub mod s9pk;
pub mod setup; pub mod setup;
@@ -99,6 +103,7 @@ pub fn server() -> Result<(), RpcError> {
config::config, config::config,
control::start, control::start,
control::stop, control::stop,
control::restart,
logs::logs, logs::logs,
properties::properties, properties::properties,
dependencies::dependency, dependencies::dependency,

View File

@@ -12,8 +12,8 @@ use tokio::process::Command;
use tokio_stream::wrappers::LinesStream; use tokio_stream::wrappers::LinesStream;
use tracing::instrument; use tracing::instrument;
use crate::action::docker::DockerAction;
use crate::error::ResultExt; use crate::error::ResultExt;
use crate::procedure::docker::DockerProcedure;
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::util::serde::Reversible; use crate::util::serde::Reversible;
use crate::Error; use crate::Error;
@@ -111,7 +111,7 @@ pub enum LogSource {
Container(PackageId), Container(PackageId),
} }
pub fn display_logs(all: LogResponse, _: &ArgMatches<'_>) { pub fn display_logs(all: LogResponse, _: &ArgMatches) {
for entry in all.entries.iter() { for entry in all.entries.iter() {
println!("{}", entry); println!("{}", entry);
} }
@@ -158,7 +158,7 @@ pub async fn fetch_logs(
LogSource::Container(id) => { LogSource::Container(id) => {
cmd.arg(format!( cmd.arg(format!(
"CONTAINER_NAME={}", "CONTAINER_NAME={}",
DockerAction::container_name(&id, None) DockerProcedure::container_name(&id, None)
)); ));
} }
}; };

View File

@@ -1,16 +1,95 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use patch_db::{DbHandle, LockType}; use patch_db::{DbHandle, LockReceipt, LockType};
use tracing::instrument; use tracing::instrument;
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::db::model::CurrentDependents;
use crate::dependencies::{break_transitive, heal_transitive, DependencyError}; use crate::dependencies::{break_transitive, heal_transitive, DependencyError};
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::{Manifest, PackageId};
use crate::status::health_check::{HealthCheckId, HealthCheckResult}; use crate::status::health_check::{HealthCheckId, HealthCheckResult};
use crate::status::MainStatus; use crate::status::MainStatus;
use crate::Error; use crate::Error;
struct HealthCheckPreInformationReceipt {
status_model: LockReceipt<MainStatus, ()>,
manifest: LockReceipt<Manifest, ()>,
}
impl HealthCheckPreInformationReceipt {
pub async fn new(db: &'_ mut impl DbHandle, id: &PackageId) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks, id);
setup(&db.lock_all(locks).await?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
id: &PackageId,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
let status_model = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|x| x.installed())
.map(|x| x.status().main())
.make_locker(LockType::Read)
.add_to_keys(locks);
let manifest = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|x| x.installed())
.map(|x| x.manifest())
.make_locker(LockType::Read)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
status_model: status_model.verify(skeleton_key)?,
manifest: manifest.verify(skeleton_key)?,
})
}
}
}
struct HealthCheckStatusReceipt {
status: LockReceipt<MainStatus, ()>,
current_dependents: LockReceipt<CurrentDependents, ()>,
}
impl HealthCheckStatusReceipt {
pub async fn new(db: &'_ mut impl DbHandle, id: &PackageId) -> Result<Self, Error> {
let mut locks = Vec::new();
let setup = Self::setup(&mut locks, id);
setup(&db.lock_all(locks).await?)
}
pub fn setup(
locks: &mut Vec<patch_db::LockTargetId>,
id: &PackageId,
) -> impl FnOnce(&patch_db::Verifier) -> Result<Self, Error> {
let status = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|x| x.installed())
.map(|x| x.status().main())
.make_locker(LockType::Write)
.add_to_keys(locks);
let current_dependents = crate::db::DatabaseModel::new()
.package_data()
.idx_model(id)
.and_then(|x| x.installed())
.map(|x| x.current_dependents())
.make_locker(LockType::Read)
.add_to_keys(locks);
move |skeleton_key| {
Ok(Self {
status: status.verify(skeleton_key)?,
current_dependents: current_dependents.verify(skeleton_key)?,
})
}
}
}
#[instrument(skip(ctx, db))] #[instrument(skip(ctx, db))]
pub async fn check<Db: DbHandle>( pub async fn check<Db: DbHandle>(
ctx: &RpcContext, ctx: &RpcContext,
@@ -19,35 +98,17 @@ pub async fn check<Db: DbHandle>(
should_commit: &AtomicBool, should_commit: &AtomicBool,
) -> Result<(), Error> { ) -> Result<(), Error> {
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
let (manifest, started) = {
let mut checkpoint = tx.begin().await?;
let receipts = HealthCheckPreInformationReceipt::new(&mut checkpoint, id).await?;
let mut checkpoint = tx.begin().await?; let manifest = receipts.manifest.get(&mut checkpoint).await?;
let installed_model = crate::db::DatabaseModel::new() let started = receipts.status_model.get(&mut checkpoint).await?.started();
.package_data()
.idx_model(id)
.expect(&mut checkpoint)
.await?
.installed()
.expect(&mut checkpoint)
.await?;
let manifest = installed_model checkpoint.save().await?;
.clone() (manifest, started)
.manifest() };
.get(&mut checkpoint, true)
.await?
.into_owned();
let started = installed_model
.clone()
.status()
.main()
.started()
.get(&mut checkpoint, true)
.await?
.into_owned();
checkpoint.save().await?;
let health_results = if let Some(started) = started { let health_results = if let Some(started) = started {
manifest manifest
@@ -61,44 +122,38 @@ pub async fn check<Db: DbHandle>(
if !should_commit.load(Ordering::SeqCst) { if !should_commit.load(Ordering::SeqCst) {
return Ok(()); return Ok(());
} }
let current_dependents = {
let mut checkpoint = tx.begin().await?;
let receipts = HealthCheckStatusReceipt::new(&mut checkpoint, id).await?;
let mut checkpoint = tx.begin().await?; let status = receipts.status.get(&mut checkpoint).await?;
crate::db::DatabaseModel::new() match status {
.package_data() MainStatus::Running { health, started } => {
.lock(&mut checkpoint, LockType::Write) receipts
.await?; .status
.set(
let mut status = crate::db::DatabaseModel::new() &mut checkpoint,
.package_data() MainStatus::Running {
.idx_model(id) health: health_results.clone(),
.expect(&mut checkpoint) started,
.await? },
.installed() )
.expect(&mut checkpoint) .await?;
.await? }
.status() _ => (),
.main()
.get_mut(&mut checkpoint)
.await?;
match &mut *status {
MainStatus::Running { health, .. } => {
*health = health_results.clone();
} }
_ => (), let current_dependents = receipts.current_dependents.get(&mut checkpoint).await?;
}
status.save(&mut checkpoint).await?; checkpoint.save().await?;
current_dependents
};
let current_dependents = installed_model tracing::debug!("Checking health of {}", id);
.current_dependents() let receipts = crate::dependencies::BreakTransitiveReceipts::new(&mut tx).await?;
.get(&mut checkpoint, true) tracing::debug!("Got receipts {}", id);
.await?;
checkpoint.save().await?; for (dependent, info) in (current_dependents).0.iter() {
for (dependent, info) in &*current_dependents {
let failures: BTreeMap<HealthCheckId, HealthCheckResult> = health_results let failures: BTreeMap<HealthCheckId, HealthCheckResult> = health_results
.iter() .iter()
.filter(|(_, hc_res)| !matches!(hc_res, HealthCheckResult::Success { .. })) .filter(|(_, hc_res)| !matches!(hc_res, HealthCheckResult::Success { .. }))
@@ -113,10 +168,11 @@ pub async fn check<Db: DbHandle>(
id, id,
DependencyError::HealthChecksFailed { failures }, DependencyError::HealthChecksFailed { failures },
&mut BTreeMap::new(), &mut BTreeMap::new(),
&receipts,
) )
.await?; .await?;
} else { } else {
heal_transitive(ctx, &mut tx, &dependent, id).await?; heal_transitive(ctx, &mut tx, &dependent, id, &receipts.dependency_receipt).await?;
} }
} }

View File

@@ -19,13 +19,13 @@ use tokio::sync::{Notify, RwLock};
use torut::onion::TorSecretKeyV3; use torut::onion::TorSecretKeyV3;
use tracing::instrument; use tracing::instrument;
use crate::action::docker::DockerAction;
use crate::action::{ActionImplementation, NoOutput};
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::manager::sync::synchronizer; use crate::manager::sync::synchronizer;
use crate::net::interface::InterfaceId; use crate::net::interface::InterfaceId;
use crate::net::GeneratedCertificateMountPoint; use crate::net::GeneratedCertificateMountPoint;
use crate::notifications::NotificationLevel; use crate::notifications::NotificationLevel;
use crate::procedure::docker::DockerProcedure;
use crate::procedure::{NoOutput, PackageProcedure, ProcedureName};
use crate::s9pk::manifest::{Manifest, PackageId}; use crate::s9pk::manifest::{Manifest, PackageId};
use crate::status::MainStatus; use crate::status::MainStatus;
use crate::util::{Container, NonDetachingJoinHandle, Version}; use crate::util::{Container, NonDetachingJoinHandle, Version};
@@ -229,7 +229,10 @@ async fn run_main(
break; break;
} }
} }
Err(bollard::errors::Error::DockerResponseNotFoundError { .. }) => (), Err(bollard::errors::Error::DockerResponseServerError {
status_code: 404, // NOT FOUND
..
}) => (),
Err(e) => Err(e)?, Err(e) => Err(e)?,
} }
match futures::poll!(&mut runtime) { match futures::poll!(&mut runtime) {
@@ -293,6 +296,7 @@ async fn run_main(
.net_controller .net_controller
.remove( .remove(
&state.manifest.id, &state.manifest.id,
ip,
state.manifest.interfaces.0.keys().cloned(), state.manifest.interfaces.0.keys().cloned(),
) )
.await?; .await?;
@@ -312,7 +316,7 @@ async fn start_up_image(
&rt_state.ctx, &rt_state.ctx,
&rt_state.manifest.id, &rt_state.manifest.id,
&rt_state.manifest.version, &rt_state.manifest.version,
None, ProcedureName::Main,
&rt_state.manifest.volumes, &rt_state.manifest.volumes,
None, None,
false, false,
@@ -333,7 +337,7 @@ impl Manager {
ctx, ctx,
status: AtomicUsize::new(Status::Stopped as usize), status: AtomicUsize::new(Status::Stopped as usize),
on_stop, on_stop,
container_name: DockerAction::container_name(&manifest.id, None), container_name: DockerProcedure::container_name(&manifest.id, None),
manifest, manifest,
tor_keys, tor_keys,
synchronized: Notify::new(), synchronized: Notify::new(),
@@ -374,8 +378,13 @@ impl Manager {
.or_else(|e| { .or_else(|e| {
if matches!( if matches!(
e, e,
bollard::errors::Error::DockerResponseConflictError { .. } bollard::errors::Error::DockerResponseServerError {
| bollard::errors::Error::DockerResponseNotFoundError { .. } status_code: 409, // CONFLICT
..
} | bollard::errors::Error::DockerResponseServerError {
status_code: 404, // NOT FOUND
..
}
) { ) {
Ok(()) Ok(())
} else { } else {
@@ -391,6 +400,11 @@ impl Manager {
.commit_health_check_results .commit_health_check_results
.store(false, Ordering::SeqCst); .store(false, Ordering::SeqCst);
let _ = self.shared.on_stop.send(OnStop::Exit); let _ = self.shared.on_stop.send(OnStop::Exit);
let action = match &self.shared.manifest.main {
PackageProcedure::Docker(a) => a,
#[cfg(feature = "js_engine")]
PackageProcedure::Script(_) => return Ok(()),
};
match self match self
.shared .shared
.ctx .ctx
@@ -398,20 +412,27 @@ impl Manager {
.stop_container( .stop_container(
&self.shared.container_name, &self.shared.container_name,
Some(StopContainerOptions { Some(StopContainerOptions {
t: match &self.shared.manifest.main { t: action
ActionImplementation::Docker(a) => a, .sigterm_timeout
} .map(|a| *a)
.sigterm_timeout .unwrap_or(Duration::from_secs(30))
.map(|a| *a) .as_secs_f64() as i64,
.unwrap_or(Duration::from_secs(30))
.as_secs_f64() as i64,
}), }),
) )
.await .await
{ {
Err(bollard::errors::Error::DockerResponseNotFoundError { .. }) Err(bollard::errors::Error::DockerResponseServerError {
| Err(bollard::errors::Error::DockerResponseConflictError { .. }) status_code: 404, // NOT FOUND
| Err(bollard::errors::Error::DockerResponseNotModifiedError { .. }) => (), // Already stopped ..
})
| Err(bollard::errors::Error::DockerResponseServerError {
status_code: 409, // CONFLICT
..
})
| Err(bollard::errors::Error::DockerResponseServerError {
status_code: 304, // NOT MODIFIED
..
}) => (), // Already stopped
a => a?, a => a?,
}; };
self.shared.status.store( self.shared.status.store(
@@ -542,26 +563,38 @@ async fn stop(shared: &ManagerSharedState) -> Result<(), Error> {
) { ) {
resume(shared).await?; resume(shared).await?;
} }
let action = match &shared.manifest.main {
PackageProcedure::Docker(a) => a,
#[cfg(feature = "js_engine")]
PackageProcedure::Script(_) => return Ok(()),
};
match shared match shared
.ctx .ctx
.docker .docker
.stop_container( .stop_container(
&shared.container_name, &shared.container_name,
Some(StopContainerOptions { Some(StopContainerOptions {
t: match &shared.manifest.main { t: action
ActionImplementation::Docker(a) => a, .sigterm_timeout
} .map(|a| *a)
.sigterm_timeout .unwrap_or(Duration::from_secs(30))
.map(|a| *a) .as_secs_f64() as i64,
.unwrap_or(Duration::from_secs(30))
.as_secs_f64() as i64,
}), }),
) )
.await .await
{ {
Err(bollard::errors::Error::DockerResponseNotFoundError { .. }) Err(bollard::errors::Error::DockerResponseServerError {
| Err(bollard::errors::Error::DockerResponseConflictError { .. }) status_code: 404, // NOT FOUND
| Err(bollard::errors::Error::DockerResponseNotModifiedError { .. }) => (), // Already stopped ..
})
| Err(bollard::errors::Error::DockerResponseServerError {
status_code: 409, // CONFLICT
..
})
| Err(bollard::errors::Error::DockerResponseServerError {
status_code: 304, // NOT MODIFIED
..
}) => (), // Already stopped
a => a?, a => a?,
}; };
shared.status.store( shared.status.store(

View File

@@ -31,7 +31,10 @@ async fn synchronize_once(shared: &ManagerSharedState) -> Result<Status, Error>
MainStatus::Stopping => { MainStatus::Stopping => {
*status = MainStatus::Stopped; *status = MainStatus::Stopped;
} }
MainStatus::Starting => { MainStatus::Restarting => {
*status = MainStatus::Starting { restarting: true };
}
MainStatus::Starting { .. } => {
start(shared).await?; start(shared).await?;
} }
MainStatus::Running { started, .. } => { MainStatus::Running { started, .. } => {
@@ -41,19 +44,19 @@ async fn synchronize_once(shared: &ManagerSharedState) -> Result<Status, Error>
MainStatus::BackingUp { .. } => (), MainStatus::BackingUp { .. } => (),
}, },
Status::Starting => match *status { Status::Starting => match *status {
MainStatus::Stopped | MainStatus::Stopping => { MainStatus::Stopped | MainStatus::Stopping | MainStatus::Restarting => {
stop(shared).await?; stop(shared).await?;
} }
MainStatus::Starting | MainStatus::Running { .. } => (), MainStatus::Starting { .. } | MainStatus::Running { .. } => (),
MainStatus::BackingUp { .. } => { MainStatus::BackingUp { .. } => {
pause(shared).await?; pause(shared).await?;
} }
}, },
Status::Running => match *status { Status::Running => match *status {
MainStatus::Stopped | MainStatus::Stopping => { MainStatus::Stopped | MainStatus::Stopping | MainStatus::Restarting => {
stop(shared).await?; stop(shared).await?;
} }
MainStatus::Starting => { MainStatus::Starting { .. } => {
*status = MainStatus::Running { *status = MainStatus::Running {
started: Utc::now(), started: Utc::now(),
health: BTreeMap::new(), health: BTreeMap::new(),
@@ -65,10 +68,10 @@ async fn synchronize_once(shared: &ManagerSharedState) -> Result<Status, Error>
} }
}, },
Status::Paused => match *status { Status::Paused => match *status {
MainStatus::Stopped | MainStatus::Stopping => { MainStatus::Stopped | MainStatus::Stopping | MainStatus::Restarting => {
stop(shared).await?; stop(shared).await?;
} }
MainStatus::Starting | MainStatus::Running { .. } => { MainStatus::Starting { .. } | MainStatus::Running { .. } => {
resume(shared).await?; resume(shared).await?;
} }
MainStatus::BackingUp { .. } => (), MainStatus::BackingUp { .. } => (),

View File

@@ -34,33 +34,21 @@ impl HasLoggedOutSessions {
logged_out_sessions: impl IntoIterator<Item = impl AsLogoutSessionId>, logged_out_sessions: impl IntoIterator<Item = impl AsLogoutSessionId>,
ctx: &RpcContext, ctx: &RpcContext,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
let sessions = logged_out_sessions let mut open_authed_websockets = ctx.open_authed_websockets.lock().await;
.into_iter()
.by_ref()
.map(|x| x.as_logout_session_id())
.collect::<Vec<_>>();
let mut sqlx_conn = ctx.secret_store.acquire().await?; let mut sqlx_conn = ctx.secret_store.acquire().await?;
for session in &sessions { for session in logged_out_sessions {
let session = session.as_logout_session_id();
sqlx::query!( sqlx::query!(
"UPDATE session SET logged_out = CURRENT_TIMESTAMP WHERE id = ?", "UPDATE session SET logged_out = CURRENT_TIMESTAMP WHERE id = ?",
session session
) )
.execute(&mut sqlx_conn) .execute(&mut sqlx_conn)
.await?; .await?;
} for socket in open_authed_websockets.remove(&session).unwrap_or_default() {
drop(sqlx_conn);
for session in sessions {
for socket in ctx
.open_authed_websockets
.lock()
.await
.remove(&session)
.unwrap_or_default()
{
let _ = socket.send(()); let _ = socket.send(());
} }
} }
Ok(Self(())) Ok(HasLoggedOutSessions(()))
} }
} }

View File

@@ -8,9 +8,10 @@ use patch_db::HasModel;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::instrument; use tracing::instrument;
use crate::action::ActionImplementation;
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::id::ImageId; use crate::id::ImageId;
use crate::procedure::PackageProcedure;
use crate::procedure::ProcedureName;
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::util::Version; use crate::util::Version;
use crate::volume::Volumes; use crate::volume::Volumes;
@@ -19,27 +20,36 @@ use crate::{Error, ResultExt};
#[derive(Clone, Debug, Default, Deserialize, Serialize, HasModel)] #[derive(Clone, Debug, Default, Deserialize, Serialize, HasModel)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct Migrations { pub struct Migrations {
pub from: IndexMap<VersionRange, ActionImplementation>, pub from: IndexMap<VersionRange, PackageProcedure>,
pub to: IndexMap<VersionRange, ActionImplementation>, pub to: IndexMap<VersionRange, PackageProcedure>,
} }
impl Migrations { impl Migrations {
#[instrument] #[instrument]
pub fn validate(&self, volumes: &Volumes, image_ids: &BTreeSet<ImageId>) -> Result<(), Error> { pub fn validate(
&self,
eos_version: &Version,
volumes: &Volumes,
image_ids: &BTreeSet<ImageId>,
) -> Result<(), Error> {
for (version, migration) in &self.from { for (version, migration) in &self.from {
migration.validate(volumes, image_ids, true).with_ctx(|_| { migration
( .validate(eos_version, volumes, image_ids, true)
crate::ErrorKind::ValidateS9pk, .with_ctx(|_| {
format!("Migration from {}", version), (
) crate::ErrorKind::ValidateS9pk,
})?; format!("Migration from {}", version),
)
})?;
} }
for (version, migration) in &self.to { for (version, migration) in &self.to {
migration.validate(volumes, image_ids, true).with_ctx(|_| { migration
( .validate(eos_version, volumes, image_ids, true)
crate::ErrorKind::ValidateS9pk, .with_ctx(|_| {
format!("Migration to {}", version), (
) crate::ErrorKind::ValidateS9pk,
})?; format!("Migration to {}", version),
)
})?;
} }
Ok(()) Ok(())
} }
@@ -64,7 +74,7 @@ impl Migrations {
ctx, ctx,
pkg_id, pkg_id,
pkg_version, pkg_version,
Some("Migration"), // Migrations cannot be executed concurrently ProcedureName::Migration, // Migrations cannot be executed concurrently
volumes, volumes,
Some(version), Some(version),
false, false,
@@ -99,7 +109,7 @@ impl Migrations {
ctx, ctx,
pkg_id, pkg_id,
pkg_version, pkg_version,
Some("Migration"), ProcedureName::Migration,
volumes, volumes,
Some(version), Some(version),
false, false,

173
backend/src/net/dns.rs Normal file
View File

@@ -0,0 +1,173 @@
use std::borrow::Borrow;
use std::collections::{BTreeMap, BTreeSet};
use std::net::{Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;
use futures::TryFutureExt;
use helpers::NonDetachingJoinHandle;
use models::PackageId;
use tokio::net::{TcpListener, UdpSocket};
use tokio::sync::RwLock;
use trust_dns_server::authority::MessageResponseBuilder;
use trust_dns_server::client::op::{Header, ResponseCode};
use trust_dns_server::client::rr::{Name, Record, RecordType};
use trust_dns_server::server::{Request, RequestHandler, ResponseHandler, ResponseInfo};
use trust_dns_server::ServerFuture;
#[cfg(feature = "avahi")]
use crate::net::mdns::resolve_mdns;
use crate::{Error, ErrorKind, ResultExt};
pub struct DnsController {
services: Arc<RwLock<BTreeMap<PackageId, BTreeSet<Ipv4Addr>>>>,
#[allow(dead_code)]
dns_server: NonDetachingJoinHandle<Result<(), Error>>,
}
struct Resolver {
services: Arc<RwLock<BTreeMap<PackageId, BTreeSet<Ipv4Addr>>>>,
}
impl Resolver {
async fn resolve(&self, name: &Name) -> Option<Vec<Ipv4Addr>> {
match name.iter().next_back() {
#[cfg(feature = "avahi")]
Some(b"local") => match resolve_mdns(&format!(
"{}.local",
name.iter()
.rev()
.skip(1)
.next()
.and_then(|v| std::str::from_utf8(v).ok())
.unwrap_or_default()
))
.await
{
Ok(ip) => Some(vec![ip]),
Err(e) => {
tracing::error!("{}", e);
tracing::debug!("{:?}", e);
None
}
},
Some(b"embassy") => {
if let Some(pkg) = name.iter().rev().skip(1).next() {
if let Some(ip) = self
.services
.read()
.await
.get(std::str::from_utf8(pkg).unwrap_or_default())
{
Some(ip.iter().copied().collect())
} else {
None
}
} else {
None
}
}
_ => None,
}
}
}
#[async_trait::async_trait]
impl RequestHandler for Resolver {
async fn handle_request<R: ResponseHandler>(
&self,
request: &Request,
mut response_handle: R,
) -> ResponseInfo {
let query = request.request_info().query;
if let Some(ip) = self.resolve(query.name().borrow()).await {
if query.query_type() != RecordType::A {
tracing::warn!("Non A-Record requested for {}", query.name());
}
response_handle
.send_response(
MessageResponseBuilder::from_message_request(&*request).build(
Header::response_from_request(request.header()),
&ip.into_iter()
.map(|ip| {
Record::from_rdata(
request.request_info().query.name().to_owned().into(),
0,
trust_dns_server::client::rr::RData::A(ip),
)
})
.collect::<Vec<_>>(),
[],
[],
[],
),
)
.await
} else {
let mut res = Header::response_from_request(request.header());
res.set_response_code(ResponseCode::NXDomain);
response_handle
.send_response(
MessageResponseBuilder::from_message_request(&*request).build(
res.into(),
[],
[],
[],
[],
),
)
.await
}
.unwrap_or_else(|e| {
tracing::error!("{}", e);
tracing::debug!("{:?}", e);
let mut res = Header::response_from_request(request.header());
res.set_response_code(ResponseCode::ServFail);
res.into()
})
}
}
impl DnsController {
pub async fn init(bind: &[SocketAddr]) -> Result<Self, Error> {
let services = Arc::new(RwLock::new(BTreeMap::new()));
let mut server = ServerFuture::new(Resolver {
services: services.clone(),
});
server.register_listener(
TcpListener::bind(bind)
.await
.with_kind(ErrorKind::Network)?,
Duration::from_secs(30),
);
server.register_socket(UdpSocket::bind(bind).await.with_kind(ErrorKind::Network)?);
let dns_server = tokio::spawn(
server
.block_until_done()
.map_err(|e| Error::new(e, ErrorKind::Network)),
)
.into();
Ok(Self {
services,
dns_server,
})
}
pub async fn add(&self, pkg_id: &PackageId, ip: Ipv4Addr) {
let mut writable = self.services.write().await;
let mut ips = writable.remove(pkg_id).unwrap_or_default();
ips.insert(ip);
writable.insert(pkg_id.clone(), ips);
}
pub async fn remove(&self, pkg_id: &PackageId, ip: Ipv4Addr) {
let mut writable = self.services.write().await;
let mut ips = writable.remove(pkg_id).unwrap_or_default();
ips.remove(&ip);
if !ips.is_empty() {
writable.insert(pkg_id.clone(), ips);
}
}
}

View File

@@ -1,5 +1,4 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::path::Path;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use futures::TryStreamExt; use futures::TryStreamExt;
@@ -16,6 +15,8 @@ use crate::s9pk::manifest::PackageId;
use crate::util::serde::Port; use crate::util::serde::Port;
use crate::{Error, ResultExt}; use crate::{Error, ResultExt};
pub use models::InterfaceId;
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct Interfaces(pub BTreeMap<InterfaceId, Interface>); // TODO pub struct Interfaces(pub BTreeMap<InterfaceId, Interface>); // TODO
@@ -113,46 +114,6 @@ impl Interfaces {
} }
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct InterfaceId<S: AsRef<str> = String>(Id<S>);
impl<S: AsRef<str>> From<Id<S>> for InterfaceId<S> {
fn from(id: Id<S>) -> Self {
Self(id)
}
}
impl<S: AsRef<str>> std::fmt::Display for InterfaceId<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", &self.0)
}
}
impl<S: AsRef<str>> std::ops::Deref for InterfaceId<S> {
type Target = S;
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl<S: AsRef<str>> AsRef<str> for InterfaceId<S> {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl<'de, S> Deserialize<'de> for InterfaceId<S>
where
S: AsRef<str>,
Id<S>: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(InterfaceId(Deserialize::deserialize(deserializer)?))
}
}
impl<S: AsRef<str>> AsRef<Path> for InterfaceId<S> {
fn as_ref(&self) -> &Path {
self.0.as_ref().as_ref()
}
}
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]

View File

@@ -1,5 +1,5 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::net::IpAddr; use std::net::Ipv4Addr;
use avahi_sys::{ use avahi_sys::{
self, avahi_client_errno, avahi_entry_group_add_service, avahi_entry_group_commit, self, avahi_client_errno, avahi_entry_group_add_service, avahi_entry_group_commit,
@@ -17,7 +17,7 @@ use crate::s9pk::manifest::PackageId;
use crate::util::Invoke; use crate::util::Invoke;
use crate::Error; use crate::Error;
pub async fn resolve_mdns(hostname: &str) -> Result<IpAddr, Error> { pub async fn resolve_mdns(hostname: &str) -> Result<Ipv4Addr, Error> {
Ok(String::from_utf8( Ok(String::from_utf8(
Command::new("avahi-resolve-host-name") Command::new("avahi-resolve-host-name")
.arg("-4") .arg("-4")
@@ -94,12 +94,7 @@ impl MdnsControllerInner {
std::ptr::null::<libc::c_char>(), std::ptr::null::<libc::c_char>(),
); );
if res < avahi_sys::AVAHI_OK { if res < avahi_sys::AVAHI_OK {
let e_str = avahi_strerror(res); log_str_error("add service to Avahi entry group", res);
tracing::error!(
"Could not add service to Avahi entry group: {:?}",
std::ffi::CStr::from_ptr(e_str)
);
avahi_free(e_str as *mut c_void);
panic!("Failed to load Avahi services"); panic!("Failed to load Avahi services");
} }
tracing::info!( tracing::info!(
@@ -129,12 +124,7 @@ impl MdnsControllerInner {
self.hostname.len(), self.hostname.len(),
); );
if res < avahi_sys::AVAHI_OK { if res < avahi_sys::AVAHI_OK {
let e_str = avahi_strerror(res); log_str_error("add CNAME record to Avahi entry group", res);
tracing::error!(
"Could not add CNAME record to Avahi entry group: {:?}",
std::ffi::CStr::from_ptr(e_str)
);
avahi_free(e_str as *mut c_void);
panic!("Failed to load Avahi services"); panic!("Failed to load Avahi services");
} }
tracing::info!("Published {:?}", lan_address_ptr); tracing::info!("Published {:?}", lan_address_ptr);
@@ -156,12 +146,7 @@ impl MdnsControllerInner {
err_c, err_c,
); );
if avahi_client == std::ptr::null_mut::<AvahiClient>() { if avahi_client == std::ptr::null_mut::<AvahiClient>() {
let e_str = avahi_strerror(*box_err); log_str_error("create Avahi client", *box_err);
tracing::error!(
"Could not create avahi client: {:?}",
std::ffi::CStr::from_ptr(e_str)
);
avahi_free(e_str as *mut c_void);
panic!("Failed to create Avahi Client"); panic!("Failed to create Avahi Client");
} }
let group = avahi_sys::avahi_entry_group_new( let group = avahi_sys::avahi_entry_group_new(
@@ -170,12 +155,7 @@ impl MdnsControllerInner {
std::ptr::null_mut(), std::ptr::null_mut(),
); );
if group == std::ptr::null_mut() { if group == std::ptr::null_mut() {
let e_str = avahi_strerror(avahi_client_errno(avahi_client)); log_str_error("create Avahi entry group", avahi_client_errno(avahi_client));
tracing::error!(
"Could not create avahi entry group: {:?}",
std::ffi::CStr::from_ptr(e_str)
);
avahi_free(e_str as *mut c_void);
panic!("Failed to create Avahi Entry Group"); panic!("Failed to create Avahi Entry Group");
} }
let mut hostname_buf = vec![0]; let mut hostname_buf = vec![0];
@@ -199,12 +179,7 @@ impl MdnsControllerInner {
res.load_services(); res.load_services();
let commit_err = avahi_entry_group_commit(res.entry_group); let commit_err = avahi_entry_group_commit(res.entry_group);
if commit_err < avahi_sys::AVAHI_OK { if commit_err < avahi_sys::AVAHI_OK {
let e_str = avahi_strerror(commit_err); log_str_error("reset Avahi entry group", commit_err);
tracing::error!(
"Could not reset Avahi entry group: {:?}",
std::ffi::CStr::from_ptr(e_str)
);
avahi_free(e_str as *mut c_void);
panic!("Failed to load Avahi services: reset"); panic!("Failed to load Avahi services: reset");
} }
res res
@@ -215,23 +190,13 @@ impl MdnsControllerInner {
let mut res; let mut res;
res = avahi_entry_group_reset(self.entry_group); res = avahi_entry_group_reset(self.entry_group);
if res < avahi_sys::AVAHI_OK { if res < avahi_sys::AVAHI_OK {
let e_str = avahi_strerror(res); log_str_error("reset Avahi entry group", res);
tracing::error!(
"Could not reset Avahi entry group: {:?}",
std::ffi::CStr::from_ptr(e_str)
);
avahi_free(e_str as *mut c_void);
panic!("Failed to load Avahi services: reset"); panic!("Failed to load Avahi services: reset");
} }
self.load_services(); self.load_services();
res = avahi_entry_group_commit(self.entry_group); res = avahi_entry_group_commit(self.entry_group);
if res < avahi_sys::AVAHI_OK { if res < avahi_sys::AVAHI_OK {
let e_str = avahi_strerror(res); log_str_error("commit Avahi entry group", res);
tracing::error!(
"Could not commit Avahi entry group: {:?}",
std::ffi::CStr::from_ptr(e_str)
);
avahi_free(e_str as *mut c_void);
panic!("Failed to load Avahi services: commit"); panic!("Failed to load Avahi services: commit");
} }
} }
@@ -264,6 +229,18 @@ impl Drop for MdnsControllerInner {
} }
} }
fn log_str_error(action: &str, e: i32) {
unsafe {
let e_str = avahi_strerror(e);
tracing::error!(
"Could not {}: {:?}",
action,
std::ffi::CStr::from_ptr(e_str)
);
avahi_free(e_str as *mut c_void);
}
}
unsafe extern "C" fn entry_group_callback( unsafe extern "C" fn entry_group_callback(
_group: *mut avahi_sys::AvahiEntryGroup, _group: *mut avahi_sys::AvahiEntryGroup,
state: avahi_sys::AvahiEntryGroupState, state: avahi_sys::AvahiEntryGroupState,

View File

@@ -14,11 +14,13 @@ use self::mdns::MdnsController;
use self::nginx::NginxController; use self::nginx::NginxController;
use self::ssl::SslManager; use self::ssl::SslManager;
use self::tor::TorController; use self::tor::TorController;
use crate::net::dns::DnsController;
use crate::net::interface::TorConfig; use crate::net::interface::TorConfig;
use crate::net::nginx::InterfaceMetadata; use crate::net::nginx::InterfaceMetadata;
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::Error; use crate::Error;
pub mod dns;
pub mod interface; pub mod interface;
#[cfg(feature = "avahi")] #[cfg(feature = "avahi")]
pub mod mdns; pub mod mdns;
@@ -45,6 +47,7 @@ pub struct NetController {
pub mdns: MdnsController, pub mdns: MdnsController,
pub nginx: NginxController, pub nginx: NginxController,
pub ssl: SslManager, pub ssl: SslManager,
pub dns: DnsController,
} }
impl NetController { impl NetController {
#[instrument(skip(db))] #[instrument(skip(db))]
@@ -52,6 +55,7 @@ impl NetController {
embassyd_addr: SocketAddr, embassyd_addr: SocketAddr,
embassyd_tor_key: TorSecretKeyV3, embassyd_tor_key: TorSecretKeyV3,
tor_control: SocketAddr, tor_control: SocketAddr,
dns_bind: &[SocketAddr],
db: SqlitePool, db: SqlitePool,
import_root_ca: Option<(PKey<Private>, X509)>, import_root_ca: Option<(PKey<Private>, X509)>,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
@@ -65,10 +69,11 @@ impl NetController {
mdns: MdnsController::init(), mdns: MdnsController::init(),
nginx: NginxController::init(PathBuf::from("/etc/nginx"), &ssl).await?, nginx: NginxController::init(PathBuf::from("/etc/nginx"), &ssl).await?,
ssl, ssl,
dns: DnsController::init(dns_bind).await?,
}) })
} }
pub fn ssl_directory_for(&self, pkg_id: &PackageId) -> PathBuf { pub fn ssl_directory_for(pkg_id: &PackageId) -> PathBuf {
PathBuf::from(format!("{}/{}", PACKAGE_CERT_PATH, pkg_id)) PathBuf::from(format!("{}/{}", PACKAGE_CERT_PATH, pkg_id))
} }
@@ -92,7 +97,7 @@ impl NetController {
Some(cfg) => Some((i.0, cfg, i.2)), Some(cfg) => Some((i.0, cfg, i.2)),
}) })
.collect::<Vec<(InterfaceId, TorConfig, TorSecretKeyV3)>>(); .collect::<Vec<(InterfaceId, TorConfig, TorSecretKeyV3)>>();
let (tor_res, _, nginx_res) = tokio::join!( let (tor_res, _, nginx_res, _) = tokio::join!(
self.tor.add(pkg_id, ip, interfaces_tor), self.tor.add(pkg_id, ip, interfaces_tor),
{ {
#[cfg(feature = "avahi")] #[cfg(feature = "avahi")]
@@ -123,7 +128,8 @@ impl NetController {
)), )),
}); });
self.nginx.add(&self.ssl, pkg_id.clone(), ip, interfaces) self.nginx.add(&self.ssl, pkg_id.clone(), ip, interfaces)
} },
self.dns.add(pkg_id, ip),
); );
tor_res?; tor_res?;
nginx_res?; nginx_res?;
@@ -135,9 +141,10 @@ impl NetController {
pub async fn remove<I: IntoIterator<Item = InterfaceId> + Clone>( pub async fn remove<I: IntoIterator<Item = InterfaceId> + Clone>(
&self, &self,
pkg_id: &PackageId, pkg_id: &PackageId,
ip: Ipv4Addr,
interfaces: I, interfaces: I,
) -> Result<(), Error> { ) -> Result<(), Error> {
let (tor_res, _, nginx_res) = tokio::join!( let (tor_res, _, nginx_res, _) = tokio::join!(
self.tor.remove(pkg_id, interfaces.clone()), self.tor.remove(pkg_id, interfaces.clone()),
{ {
#[cfg(feature = "avahi")] #[cfg(feature = "avahi")]
@@ -146,7 +153,8 @@ impl NetController {
let mdns_fut = futures::future::ready(()); let mdns_fut = futures::future::ready(());
mdns_fut mdns_fut
}, },
self.nginx.remove(pkg_id) self.nginx.remove(pkg_id),
self.dns.remove(pkg_id, ip),
); );
tor_res?; tor_res?;
nginx_res?; nginx_res?;

View File

@@ -14,5 +14,6 @@ server {{
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade; proxy_set_header Connection $connection_upgrade;
{proxy_redirect_directive}
}} }}
}} }}

View File

@@ -91,7 +91,7 @@ impl NginxControllerInner {
for (id, meta) in interface_map.iter() { for (id, meta) in interface_map.iter() {
for (port, lan_port_config) in meta.lan_config.iter() { for (port, lan_port_config) in meta.lan_config.iter() {
// get ssl certificate chain // get ssl certificate chain
let (listen_args, ssl_certificate_line, ssl_certificate_key_line) = let (listen_args, ssl_certificate_line, ssl_certificate_key_line, proxy_redirect_directive) =
if lan_port_config.ssl { if lan_port_config.ssl {
// these have already been written by the net controller // these have already been written by the net controller
let package_path = nginx_root.join(format!("ssl/{}", package)); let package_path = nginx_root.join(format!("ssl/{}", package));
@@ -115,9 +115,10 @@ impl NginxControllerInner {
format!("{} ssl", port.0), format!("{} ssl", port.0),
format!("ssl_certificate {};", ssl_path_cert.to_str().unwrap()), format!("ssl_certificate {};", ssl_path_cert.to_str().unwrap()),
format!("ssl_certificate_key {};", ssl_path_key.to_str().unwrap()), format!("ssl_certificate_key {};", ssl_path_key.to_str().unwrap()),
format!("proxy_redirect http://$host/ https://$host/;"),
) )
} else { } else {
(format!("{}", port.0), String::from(""), String::from("")) (format!("{}", port.0), String::from(""), String::from(""), String::from(""))
}; };
// write nginx configs // write nginx configs
let nginx_conf_path = nginx_root.join(format!( let nginx_conf_path = nginx_root.join(format!(
@@ -135,6 +136,7 @@ impl NginxControllerInner {
ssl_certificate_key_line = ssl_certificate_key_line, ssl_certificate_key_line = ssl_certificate_key_line,
app_ip = ipv4, app_ip = ipv4,
internal_port = lan_port_config.internal, internal_port = lan_port_config.internal,
proxy_redirect_directive = proxy_redirect_directive,
), ),
) )
.await .await

View File

@@ -12,10 +12,12 @@ use openssl::pkey::{PKey, Private};
use openssl::x509::{X509Builder, X509Extension, X509NameBuilder, X509}; use openssl::x509::{X509Builder, X509Extension, X509NameBuilder, X509};
use openssl::*; use openssl::*;
use sqlx::SqlitePool; use sqlx::SqlitePool;
use tokio::process::Command;
use tokio::sync::Mutex; use tokio::sync::Mutex;
use tracing::instrument; use tracing::instrument;
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::util::Invoke;
use crate::{Error, ErrorKind, ResultExt}; use crate::{Error, ErrorKind, ResultExt};
static CERTIFICATE_VERSION: i32 = 2; // X509 version 3 is actually encoded as '2' in the cert because fuck you. static CERTIFICATE_VERSION: i32 = 2; // X509 version 3 is actually encoded as '2' in the cert because fuck you.
@@ -164,7 +166,8 @@ impl SslManager {
let (root_key, root_cert) = match store.load_root_certificate().await? { let (root_key, root_cert) = match store.load_root_certificate().await? {
None => { None => {
let root_key = generate_key()?; let root_key = generate_key()?;
let root_cert = make_root_cert(&root_key)?; let server_id = crate::hostname::get_id().await?;
let root_cert = make_root_cert(&root_key, &server_id)?;
store.save_root_certificate(&root_key, &root_cert).await?; store.save_root_certificate(&root_key, &root_cert).await?;
Ok::<_, Error>((root_key, root_cert)) Ok::<_, Error>((root_key, root_cert))
} }
@@ -179,6 +182,17 @@ impl SslManager {
) )
.await?; .await?;
tokio::fs::write(ROOT_CA_STATIC_PATH, root_cert.to_pem()?).await?; tokio::fs::write(ROOT_CA_STATIC_PATH, root_cert.to_pem()?).await?;
// write to ca cert store
tokio::fs::write(
"/usr/local/share/ca-certificates/embassy-root-ca.crt",
root_cert.to_pem()?,
)
.await?;
Command::new("update-ca-certificates")
.invoke(crate::ErrorKind::OpenSsl)
.await?;
let (int_key, int_cert) = match store.load_intermediate_certificate().await? { let (int_key, int_cert) = match store.load_intermediate_certificate().await? {
None => { None => {
let int_key = generate_key()?; let int_key = generate_key()?;
@@ -307,7 +321,7 @@ fn generate_key() -> Result<PKey<Private>, Error> {
Ok(key) Ok(key)
} }
#[instrument] #[instrument]
fn make_root_cert(root_key: &PKey<Private>) -> Result<X509, Error> { fn make_root_cert(root_key: &PKey<Private>, server_id: &str) -> Result<X509, Error> {
let mut builder = X509Builder::new()?; let mut builder = X509Builder::new()?;
builder.set_version(CERTIFICATE_VERSION)?; builder.set_version(CERTIFICATE_VERSION)?;
@@ -320,7 +334,8 @@ fn make_root_cert(root_key: &PKey<Private>) -> Result<X509, Error> {
builder.set_serial_number(&*rand_serial()?)?; builder.set_serial_number(&*rand_serial()?)?;
let mut subject_name_builder = X509NameBuilder::new()?; let mut subject_name_builder = X509NameBuilder::new()?;
subject_name_builder.append_entry_by_text("CN", "Embassy Local Root CA")?; subject_name_builder
.append_entry_by_text("CN", &format!("Embassy Local Root CA ({})", server_id))?;
subject_name_builder.append_entry_by_text("O", "Start9")?; subject_name_builder.append_entry_by_text("O", "Start9")?;
subject_name_builder.append_entry_by_text("OU", "Embassy")?; subject_name_builder.append_entry_by_text("OU", "Embassy")?;
let subject_name = subject_name_builder.build(); let subject_name = subject_name_builder.build();

View File

@@ -32,7 +32,7 @@ pub fn tor() -> Result<(), Error> {
Ok(()) Ok(())
} }
fn display_services(services: Vec<OnionAddressV3>, matches: &ArgMatches<'_>) { fn display_services(services: Vec<OnionAddressV3>, matches: &ArgMatches) {
use prettytable::*; use prettytable::*;
if matches.is_present("format") { if matches.is_present("format") {
@@ -351,7 +351,9 @@ impl TorControllerInner {
.get_info("onions/current") .get_info("onions/current")
.await? .await?
.lines() .lines()
.map(|l| l.trim().parse().with_kind(ErrorKind::Tor)) .map(|l| l.trim())
.filter(|l| !l.is_empty())
.map(|l| l.parse().with_kind(ErrorKind::Tor))
.collect() .collect()
} }
} }

View File

@@ -188,7 +188,7 @@ pub struct WifiListOut {
security: Vec<String>, security: Vec<String>,
} }
pub type WifiList = HashMap<Ssid, WifiListInfo>; pub type WifiList = HashMap<Ssid, WifiListInfo>;
fn display_wifi_info(info: WiFiInfo, matches: &ArgMatches<'_>) { fn display_wifi_info(info: WiFiInfo, matches: &ArgMatches) {
use prettytable::*; use prettytable::*;
if matches.is_present("format") { if matches.is_present("format") {
@@ -252,7 +252,7 @@ fn display_wifi_info(info: WiFiInfo, matches: &ArgMatches<'_>) {
table_global.print_tty(false); table_global.print_tty(false);
} }
fn display_wifi_list(info: Vec<WifiListOut>, matches: &ArgMatches<'_>) { fn display_wifi_list(info: Vec<WifiListOut>, matches: &ArgMatches) {
use prettytable::*; use prettytable::*;
if matches.is_present("format") { if matches.is_present("format") {
@@ -764,7 +764,7 @@ pub async fn interface_connected(interface: &str) -> Result<bool, Error> {
Ok(v.is_some()) Ok(v.is_some())
} }
pub fn country_code_parse(code: &str, _matches: &ArgMatches<'_>) -> Result<CountryCode, Error> { pub fn country_code_parse(code: &str, _matches: &ArgMatches) -> Result<CountryCode, Error> {
CountryCode::for_alpha2(code).map_err(|_| { CountryCode::for_alpha2(code).map_err(|_| {
Error::new( Error::new(
color_eyre::eyre::eyre!("Invalid Country Code: {}", code), color_eyre::eyre::eyre!("Invalid Country Code: {}", code),

View File

@@ -1,3 +1,9 @@
map $http_upgrade $connection_upgrade {
default upgrade;
'' $http_connection;
}
server { server {
listen 80 default_server; listen 80 default_server;
listen [::]:80 default_server; listen [::]:80 default_server;

View File

View File

@@ -0,0 +1,581 @@
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::ffi::{OsStr, OsString};
use std::net::Ipv4Addr;
use std::path::PathBuf;
use std::time::Duration;
use async_stream::stream;
use bollard::container::RemoveContainerOptions;
use color_eyre::eyre::eyre;
use color_eyre::Report;
use futures::future::Either as EitherFuture;
use futures::TryStreamExt;
use helpers::NonDetachingJoinHandle;
use nix::sys::signal;
use nix::unistd::Pid;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::io::{AsyncBufRead, AsyncBufReadExt, BufReader};
use tracing::instrument;
use super::ProcedureName;
use crate::context::RpcContext;
use crate::id::{Id, ImageId};
use crate::s9pk::manifest::{PackageId, SYSTEM_PACKAGE_ID};
use crate::util::serde::{Duration as SerdeDuration, IoFormat};
use crate::util::Version;
use crate::volume::{VolumeId, Volumes};
use crate::{Error, ResultExt, HOST_IP};
pub const NET_TLD: &str = "embassy";
lazy_static::lazy_static! {
pub static ref SYSTEM_IMAGES: BTreeSet<ImageId> = {
let mut set = BTreeSet::new();
set.insert("compat".parse().unwrap());
set.insert("utils".parse().unwrap());
set
};
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct DockerProcedure {
pub image: ImageId,
#[serde(default)]
pub system: bool,
pub entrypoint: String,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub mounts: BTreeMap<VolumeId, PathBuf>,
#[serde(default)]
pub io_format: Option<IoFormat>,
#[serde(default)]
pub inject: bool,
#[serde(default)]
pub shm_size_mb: Option<usize>, // TODO: use postfix sizing? like 1k vs 1m vs 1g
#[serde(default)]
pub sigterm_timeout: Option<SerdeDuration>,
}
impl DockerProcedure {
pub fn validate(
&self,
eos_version: &Version,
volumes: &Volumes,
image_ids: &BTreeSet<ImageId>,
expected_io: bool,
) -> Result<(), color_eyre::eyre::Report> {
for (volume, _) in &self.mounts {
if !volumes.contains_key(volume) && !matches!(&volume, &VolumeId::Backup) {
color_eyre::eyre::bail!("unknown volume: {}", volume);
}
}
if self.system {
if !SYSTEM_IMAGES.contains(&self.image) {
color_eyre::eyre::bail!("unknown system image: {}", self.image);
}
} else {
if !image_ids.contains(&self.image) {
color_eyre::eyre::bail!("image for {} not contained in package", self.image);
}
}
if expected_io && self.io_format.is_none() {
color_eyre::eyre::bail!("expected io-format");
}
if &**eos_version >= &emver::Version::new(0, 3, 1, 1)
&& self.inject
&& !self.mounts.is_empty()
{
color_eyre::eyre::bail!("mounts not allowed in inject actions");
}
Ok(())
}
#[instrument(skip(ctx, input))]
pub async fn execute<I: Serialize, O: for<'de> Deserialize<'de>>(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
name: ProcedureName,
volumes: &Volumes,
input: Option<I>,
allow_inject: bool,
timeout: Option<Duration>,
) -> Result<Result<O, (i32, String)>, Error> {
let name = name.docker_name();
let name: Option<&str> = name.as_ref().map(|x| &**x);
let mut cmd = tokio::process::Command::new("docker");
if self.inject && allow_inject {
cmd.arg("exec");
} else {
let container_name = Self::container_name(pkg_id, name);
cmd.arg("run")
.arg("--rm")
.arg("--network=start9")
.arg(format!("--add-host=embassy:{}", Ipv4Addr::from(HOST_IP)))
.arg("--name")
.arg(&container_name)
.arg(format!("--hostname={}", &container_name))
.arg("--no-healthcheck");
match ctx
.docker
.remove_container(
&container_name,
Some(RemoveContainerOptions {
v: false,
force: true,
link: false,
}),
)
.await
{
Ok(())
| Err(bollard::errors::Error::DockerResponseServerError {
status_code: 404, // NOT FOUND
..
}) => Ok(()),
Err(e) => Err(e),
}?;
}
cmd.args(
self.docker_args(ctx, pkg_id, pkg_version, volumes, allow_inject)
.await,
);
let input_buf = if let (Some(input), Some(format)) = (&input, &self.io_format) {
cmd.stdin(std::process::Stdio::piped());
Some(format.to_vec(input)?)
} else {
None
};
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
tracing::trace!(
"{}",
format!("{:?}", cmd)
.split(r#"" ""#)
.collect::<Vec<&str>>()
.join(" ")
);
let mut handle = cmd.spawn().with_kind(crate::ErrorKind::Docker)?;
let id = handle.id();
let timeout_fut = if let Some(timeout) = timeout {
EitherFuture::Right(async move {
tokio::time::sleep(timeout).await;
Ok(())
})
} else {
EitherFuture::Left(futures::future::pending::<Result<_, Error>>())
};
if let (Some(input), Some(mut stdin)) = (&input_buf, handle.stdin.take()) {
use tokio::io::AsyncWriteExt;
stdin
.write_all(input)
.await
.with_kind(crate::ErrorKind::Docker)?;
stdin.flush().await?;
stdin.shutdown().await?;
drop(stdin);
}
enum Race<T> {
Done(T),
TimedOut,
}
let io_format = self.io_format;
let mut output = BufReader::new(
handle
.stdout
.take()
.ok_or_else(|| eyre!("Can't takeout stout"))
.with_kind(crate::ErrorKind::Docker)?,
);
let output = NonDetachingJoinHandle::from(tokio::spawn(async move {
match async {
if let Some(format) = io_format {
return match max_by_lines(&mut output, None).await {
MaxByLines::Done(buffer) => {
Ok::<Value, Error>(
match format.from_slice(buffer.as_bytes()) {
Ok(a) => a,
Err(e) => {
tracing::trace!(
"Failed to deserialize stdout from {}: {}, falling back to UTF-8 string.",
format,
e
);
Value::String(buffer)
}
},
)
},
MaxByLines::Error(e) => Err(e),
MaxByLines::Overflow(buffer) => Ok(Value::String(buffer))
}
}
let lines = buf_reader_to_lines(&mut output, 1000).await?;
if lines.is_empty() {
return Ok(Value::Null);
}
let joined_output = lines.join("\n");
Ok(Value::String(joined_output))
}.await {
Ok(a) => Ok((a, output)),
Err(e) => Err((e, output))
}
}));
let err_output = BufReader::new(
handle
.stderr
.take()
.ok_or_else(|| eyre!("Can't takeout std err"))
.with_kind(crate::ErrorKind::Docker)?,
);
let err_output = NonDetachingJoinHandle::from(tokio::spawn(async move {
let lines = buf_reader_to_lines(err_output, 1000).await?;
let joined_output = lines.join("\n");
Ok::<_, Error>(joined_output)
}));
let res = tokio::select! {
res = handle.wait() => Race::Done(res.with_kind(crate::ErrorKind::Docker)?),
res = timeout_fut => {
res?;
Race::TimedOut
},
};
let exit_status = match res {
Race::Done(x) => x,
Race::TimedOut => {
if let Some(id) = id {
signal::kill(Pid::from_raw(id as i32), signal::SIGKILL)
.with_kind(crate::ErrorKind::Docker)?;
}
return Ok(Err((143, "Timed out. Retrying soon...".to_owned())));
}
};
Ok(
if exit_status.success() || exit_status.code() == Some(143) {
Ok(serde_json::from_value(
output
.await
.with_kind(crate::ErrorKind::Unknown)?
.map(|(v, _)| v)
.map_err(|(e, _)| tracing::warn!("{}", e))
.unwrap_or_default(),
)
.with_kind(crate::ErrorKind::Deserialization)?)
} else {
Err((
exit_status.code().unwrap_or_default(),
err_output.await.with_kind(crate::ErrorKind::Unknown)??,
))
},
)
}
#[instrument(skip(ctx, input))]
pub async fn sandboxed<I: Serialize, O: for<'de> Deserialize<'de>>(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
volumes: &Volumes,
input: Option<I>,
timeout: Option<Duration>,
) -> Result<Result<O, (i32, String)>, Error> {
let mut cmd = tokio::process::Command::new("docker");
cmd.arg("run").arg("--rm").arg("--network=none");
cmd.args(
self.docker_args(ctx, pkg_id, pkg_version, &volumes.to_readonly(), false)
.await,
);
let input_buf = if let (Some(input), Some(format)) = (&input, &self.io_format) {
cmd.stdin(std::process::Stdio::piped());
Some(format.to_vec(input)?)
} else {
None
};
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
let mut handle = cmd.spawn().with_kind(crate::ErrorKind::Docker)?;
if let (Some(input), Some(stdin)) = (&input_buf, &mut handle.stdin) {
use tokio::io::AsyncWriteExt;
stdin
.write_all(input)
.await
.with_kind(crate::ErrorKind::Docker)?;
}
let err_output = BufReader::new(
handle
.stderr
.take()
.ok_or_else(|| eyre!("Can't takeout std err"))
.with_kind(crate::ErrorKind::Docker)?,
);
let err_output = NonDetachingJoinHandle::from(tokio::spawn(async move {
let lines = buf_reader_to_lines(err_output, 1000).await?;
let joined_output = lines.join("\n");
Ok::<_, Error>(joined_output)
}));
let io_format = self.io_format;
let mut output = BufReader::new(
handle
.stdout
.take()
.ok_or_else(|| eyre!("Can't takeout stout"))
.with_kind(crate::ErrorKind::Docker)?,
);
let output = NonDetachingJoinHandle::from(tokio::spawn(async move {
match async {
if let Some(format) = io_format {
return match max_by_lines(&mut output, None).await {
MaxByLines::Done(buffer) => {
Ok::<Value, Error>(
match format.from_slice(buffer.as_bytes()) {
Ok(a) => a,
Err(e) => {
tracing::trace!(
"Failed to deserialize stdout from {}: {}, falling back to UTF-8 string.",
format,
e
);
Value::String(buffer)
}
},
)
},
MaxByLines::Error(e) => Err(e),
MaxByLines::Overflow(buffer) => Ok(Value::String(buffer))
}
}
let lines = buf_reader_to_lines(&mut output, 1000).await?;
if lines.is_empty() {
return Ok(Value::Null);
}
let joined_output = lines.join("\n");
Ok(Value::String(joined_output))
}.await {
Ok(a) => Ok((a, output)),
Err(e) => Err((e, output))
}
}));
let exit_status = handle.wait().await.with_kind(crate::ErrorKind::Docker)?;
Ok(
if exit_status.success() || exit_status.code() == Some(143) {
Ok(serde_json::from_value(
output
.await
.with_kind(crate::ErrorKind::Unknown)?
.map(|(v, _)| v)
.map_err(|(e, _)| tracing::warn!("{}", e))
.unwrap_or_default(),
)
.with_kind(crate::ErrorKind::Deserialization)?)
} else {
Err((
exit_status.code().unwrap_or_default(),
err_output.await.with_kind(crate::ErrorKind::Unknown)??,
))
},
)
}
pub fn container_name(pkg_id: &PackageId, name: Option<&str>) -> String {
if let Some(name) = name {
format!("{}_{}.{}", pkg_id, name, NET_TLD)
} else {
format!("{}.{}", pkg_id, NET_TLD)
}
}
pub fn uncontainer_name(name: &str) -> Option<(PackageId<&str>, Option<&str>)> {
let (pre_tld, _) = name.split_once('.')?;
if pre_tld.contains('_') {
let (pkg, name) = name.split_once('_')?;
Some((Id::try_from(pkg).ok()?.into(), Some(name)))
} else {
Some((Id::try_from(pre_tld).ok()?.into(), None))
}
}
async fn docker_args(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
volumes: &Volumes,
allow_inject: bool,
) -> Vec<Cow<'_, OsStr>> {
let mut res = Vec::with_capacity(
(2 * self.mounts.len()) // --mount <MOUNT_ARG>
+ (2 * self.shm_size_mb.is_some() as usize) // --shm-size <SHM_SIZE>
+ 5 // --interactive --log-driver=journald --entrypoint <ENTRYPOINT> <IMAGE>
+ self.args.len(), // [ARG...]
);
for (volume_id, dst) in &self.mounts {
let volume = if let Some(v) = volumes.get(volume_id) {
v
} else {
continue;
};
let src = volume.path_for(&ctx.datadir, pkg_id, pkg_version, volume_id);
if let Err(e) = tokio::fs::metadata(&src).await {
tracing::warn!("{} not mounted to container: {}", src.display(), e);
continue;
}
res.push(OsStr::new("--mount").into());
res.push(
OsString::from(format!(
"type=bind,src={},dst={}{}",
src.display(),
dst.display(),
if volume.readonly() { ",readonly" } else { "" }
))
.into(),
);
}
if let Some(shm_size_mb) = self.shm_size_mb {
res.push(OsStr::new("--shm-size").into());
res.push(OsString::from(format!("{}m", shm_size_mb)).into());
}
res.push(OsStr::new("--interactive").into());
if self.inject && allow_inject {
res.push(OsString::from(Self::container_name(pkg_id, None)).into());
res.push(OsStr::new(&self.entrypoint).into());
} else {
res.push(OsStr::new("--log-driver=journald").into());
res.push(OsStr::new("--entrypoint").into());
res.push(OsStr::new(&self.entrypoint).into());
if self.system {
res.push(OsString::from(self.image.for_package(SYSTEM_PACKAGE_ID, None)).into());
} else {
res.push(OsString::from(self.image.for_package(pkg_id, Some(pkg_version))).into());
}
}
res.extend(self.args.iter().map(|s| OsStr::new(s).into()));
res
}
}
struct RingVec<T> {
value: VecDeque<T>,
capacity: usize,
}
impl<T> RingVec<T> {
fn new(capacity: usize) -> Self {
RingVec {
value: VecDeque::with_capacity(capacity),
capacity,
}
}
fn push(&mut self, item: T) -> Option<T> {
let popped_item = if self.value.len() == self.capacity {
self.value.pop_front()
} else {
None
};
self.value.push_back(item);
popped_item
}
}
async fn buf_reader_to_lines(
reader: impl AsyncBufRead + Unpin,
limit: impl Into<Option<usize>>,
) -> Result<Vec<String>, Error> {
let lines = stream! {
let mut lines = reader.lines();
while let Some(line) = lines.next_line().await? {
yield Ok::<_, Report>(line);
}
};
let output: RingVec<String> = lines
.try_fold(
RingVec::new(limit.into().unwrap_or(1000)),
|mut acc, line| async move {
acc.push(line);
Ok(acc)
},
)
.await
.with_kind(crate::ErrorKind::Unknown)?;
let output: Vec<String> = output.value.into_iter().collect();
Ok(output)
}
enum MaxByLines {
Done(String),
Overflow(String),
Error(Error),
}
async fn max_by_lines(
reader: impl AsyncBufRead + Unpin,
max_items: impl Into<Option<usize>>,
) -> MaxByLines {
let mut answer = String::new();
let mut lines = reader.lines();
let mut has_over_blown = false;
let max_items = max_items.into().unwrap_or(10_000_000);
while let Some(line) = {
match lines.next_line().await {
Ok(a) => a,
Err(e) => return MaxByLines::Error(e.into()),
}
} {
if has_over_blown {
continue;
}
if !answer.is_empty() {
answer.push('\n');
}
answer.push_str(&line);
if answer.len() >= max_items {
has_over_blown = true;
tracing::warn!("Reading the buffer exceeding limits of {}", max_items);
}
}
if has_over_blown {
return MaxByLines::Overflow(answer);
}
MaxByLines::Done(answer)
}
#[cfg(test)]
mod tests {
use super::*;
/// Note, this size doesn't mean the vec will match. The vec will go to the next size, 0 -> 7 = 7 and so forth 7-15 = 15
/// Just how the vec with capacity works.
const CAPACITY_IN: usize = 7;
#[test]
fn default_capacity_is_set() {
let ring: RingVec<usize> = RingVec::new(CAPACITY_IN);
assert_eq!(CAPACITY_IN, ring.value.capacity());
assert_eq!(0, ring.value.len());
}
#[test]
fn capacity_can_not_be_exceeded() {
let mut ring = RingVec::new(CAPACITY_IN);
for i in 1..100usize {
ring.push(i);
}
assert_eq!(CAPACITY_IN, ring.value.capacity());
assert_eq!(CAPACITY_IN, ring.value.len());
}
}

View File

@@ -0,0 +1,379 @@
use std::{
path::{Path, PathBuf},
time::Duration,
};
use models::VolumeId;
use serde::{Deserialize, Serialize};
use tracing::instrument;
use crate::{
context::RpcContext, s9pk::manifest::PackageId, util::Version, volume::Volumes, Error,
};
use js_engine::{JsExecutionEnvironment, PathForVolumeId};
use super::ProcedureName;
pub use js_engine::JsError;
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "kebab-case")]
enum ErrorValue {
Error(String),
ErrorCode((i32, String)),
Result(serde_json::Value),
}
impl PathForVolumeId for Volumes {
fn path_for(
&self,
data_dir: &Path,
package_id: &PackageId,
version: &Version,
volume_id: &VolumeId,
) -> Option<PathBuf> {
let volume = self.get(volume_id)?;
Some(volume.path_for(data_dir, package_id, version, volume_id))
}
fn readonly(&self, volume_id: &VolumeId) -> bool {
self.get(volume_id).map(|x| x.readonly()).unwrap_or(false)
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct JsProcedure {
#[serde(default)]
args: Vec<serde_json::Value>,
}
impl JsProcedure {
pub fn validate(&self, _volumes: &Volumes) -> Result<(), color_eyre::eyre::Report> {
Ok(())
}
#[instrument(skip(directory, input))]
pub async fn execute<I: Serialize, O: for<'de> Deserialize<'de>>(
&self,
directory: &PathBuf,
pkg_id: &PackageId,
pkg_version: &Version,
name: ProcedureName,
volumes: &Volumes,
input: Option<I>,
timeout: Option<Duration>,
) -> Result<Result<O, (i32, String)>, Error> {
Ok(async move {
let running_action = JsExecutionEnvironment::load_from_package(
directory,
pkg_id,
pkg_version,
Box::new(volumes.clone()),
)
.await?
.run_action(name, input, self.args.clone());
let output: ErrorValue = match timeout {
Some(timeout_duration) => tokio::time::timeout(timeout_duration, running_action)
.await
.map_err(|_| (JsError::Timeout, "Timed out. Retrying soon...".to_owned()))??,
None => running_action.await?,
};
let output: O = unwrap_known_error(output)?;
Ok(output)
}
.await
.map_err(|(error, message)| (error.as_code_num(), message)))
}
#[instrument(skip(ctx, input))]
pub async fn sandboxed<I: Serialize, O: for<'de> Deserialize<'de>>(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
volumes: &Volumes,
input: Option<I>,
timeout: Option<Duration>,
name: ProcedureName,
) -> Result<Result<O, (i32, String)>, Error> {
Ok(async move {
let running_action = JsExecutionEnvironment::load_from_package(
&ctx.datadir,
pkg_id,
pkg_version,
Box::new(volumes.clone()),
)
.await?
.read_only_effects()
.run_action(name, input, self.args.clone());
let output: ErrorValue = match timeout {
Some(timeout_duration) => tokio::time::timeout(timeout_duration, running_action)
.await
.map_err(|_| (JsError::Timeout, "Timed out. Retrying soon...".to_owned()))??,
None => running_action.await?,
};
let output: O = unwrap_known_error(output)?;
Ok(output)
}
.await
.map_err(|(error, message)| (error.as_code_num(), message)))
}
}
fn unwrap_known_error<O: for<'de> Deserialize<'de>>(
error_value: ErrorValue,
) -> Result<O, (JsError, String)> {
match error_value {
ErrorValue::Error(error) => Err((JsError::Javascript, error)),
ErrorValue::ErrorCode((code, message)) => Err((JsError::Code(code), message)),
ErrorValue::Result(ref value) => match serde_json::from_value(value.clone()) {
Ok(a) => Ok(a),
Err(err) => {
tracing::error!("{}", err);
tracing::debug!("{:?}", err);
Err((
JsError::BoundryLayerSerDe,
format!(
"Couldn't convert output = {:#?} to the correct type",
serde_json::to_string_pretty(&error_value).unwrap_or_default()
),
))
}
},
}
}
#[tokio::test]
async fn js_action_execute() {
let js_action = JsProcedure { args: vec![] };
let path: PathBuf = "test/js_action_execute/"
.parse::<PathBuf>()
.unwrap()
.canonicalize()
.unwrap();
let package_id = "test-package".parse().unwrap();
let package_version: Version = "0.3.0.3".parse().unwrap();
let name = ProcedureName::GetConfig;
let volumes: Volumes = serde_json::from_value(serde_json::json!({
"main": {
"type": "data"
},
"compat": {
"type": "assets"
},
"filebrowser" :{
"package-id": "filebrowser",
"path": "data",
"readonly": true,
"type": "pointer",
"volume-id": "main",
}
}))
.unwrap();
let input: Option<serde_json::Value> = Some(serde_json::json!({"test":123}));
let timeout = Some(Duration::from_secs(10));
let _output: crate::config::action::ConfigRes = js_action
.execute(
&path,
&package_id,
&package_version,
name,
&volumes,
input,
timeout,
)
.await
.unwrap()
.unwrap();
assert_eq!(
&std::fs::read_to_string(
"test/js_action_execute/package-data/volumes/test-package/data/main/test.log"
)
.unwrap(),
"This is a test"
);
std::fs::remove_file(
"test/js_action_execute/package-data/volumes/test-package/data/main/test.log",
)
.unwrap();
}
#[tokio::test]
async fn js_action_execute_error() {
let js_action = JsProcedure { args: vec![] };
let path: PathBuf = "test/js_action_execute/"
.parse::<PathBuf>()
.unwrap()
.canonicalize()
.unwrap();
let package_id = "test-package".parse().unwrap();
let package_version: Version = "0.3.0.3".parse().unwrap();
let name = ProcedureName::SetConfig;
let volumes: Volumes = serde_json::from_value(serde_json::json!({
"main": {
"type": "data"
},
"compat": {
"type": "assets"
},
"filebrowser" :{
"package-id": "filebrowser",
"path": "data",
"readonly": true,
"type": "pointer",
"volume-id": "main",
}
}))
.unwrap();
let input: Option<serde_json::Value> = None;
let timeout = Some(Duration::from_secs(10));
let output: Result<serde_json::Value, _> = js_action
.execute(
&path,
&package_id,
&package_version,
name,
&volumes,
input,
timeout,
)
.await
.unwrap();
assert_eq!("Err((2, \"Not setup\"))", &format!("{:?}", output));
}
#[tokio::test]
async fn js_action_fetch() {
let js_action = JsProcedure { args: vec![] };
let path: PathBuf = "test/js_action_execute/"
.parse::<PathBuf>()
.unwrap()
.canonicalize()
.unwrap();
let package_id = "test-package".parse().unwrap();
let package_version: Version = "0.3.0.3".parse().unwrap();
let name = ProcedureName::Action("fetch".parse().unwrap());
let volumes: Volumes = serde_json::from_value(serde_json::json!({
"main": {
"type": "data"
},
"compat": {
"type": "assets"
},
"filebrowser" :{
"package-id": "filebrowser",
"path": "data",
"readonly": true,
"type": "pointer",
"volume-id": "main",
}
}))
.unwrap();
let input: Option<serde_json::Value> = None;
let timeout = Some(Duration::from_secs(10));
js_action
.execute::<serde_json::Value, serde_json::Value>(
&path,
&package_id,
&package_version,
name,
&volumes,
input,
timeout,
)
.await
.unwrap()
.unwrap();
}
#[tokio::test]
async fn js_action_var_arg() {
let js_action = JsProcedure {
args: vec![42.into()],
};
let path: PathBuf = "test/js_action_execute/"
.parse::<PathBuf>()
.unwrap()
.canonicalize()
.unwrap();
let package_id = "test-package".parse().unwrap();
let package_version: Version = "0.3.0.3".parse().unwrap();
let name = ProcedureName::Action("js-action-var-arg".parse().unwrap());
let volumes: Volumes = serde_json::from_value(serde_json::json!({
"main": {
"type": "data"
},
"compat": {
"type": "assets"
},
"filebrowser" :{
"package-id": "filebrowser",
"path": "data",
"readonly": true,
"type": "pointer",
"volume-id": "main",
}
}))
.unwrap();
let input: Option<serde_json::Value> = None;
let timeout = Some(Duration::from_secs(10));
js_action
.execute::<serde_json::Value, serde_json::Value>(
&path,
&package_id,
&package_version,
name,
&volumes,
input,
timeout,
)
.await
.unwrap()
.unwrap();
}
#[tokio::test]
async fn js_action_test_rename() {
let js_action = JsProcedure { args: vec![] };
let path: PathBuf = "test/js_action_execute/"
.parse::<PathBuf>()
.unwrap()
.canonicalize()
.unwrap();
let package_id = "test-package".parse().unwrap();
let package_version: Version = "0.3.0.3".parse().unwrap();
let name = ProcedureName::Action("test-rename".parse().unwrap());
let volumes: Volumes = serde_json::from_value(serde_json::json!({
"main": {
"type": "data"
},
"compat": {
"type": "assets"
},
"filebrowser" :{
"package-id": "filebrowser",
"path": "data",
"readonly": true,
"type": "pointer",
"volume-id": "main",
}
}))
.unwrap();
let input: Option<serde_json::Value> = None;
let timeout = Some(Duration::from_secs(10));
js_action
.execute::<serde_json::Value, serde_json::Value>(
&path,
&package_id,
&package_version,
name,
&volumes,
input,
timeout,
)
.await
.unwrap()
.unwrap();
}

View File

@@ -0,0 +1,149 @@
use std::collections::BTreeSet;
use std::time::Duration;
use patch_db::HasModel;
use serde::{Deserialize, Serialize};
use tracing::instrument;
use self::docker::DockerProcedure;
use crate::context::RpcContext;
use crate::id::ImageId;
use crate::s9pk::manifest::PackageId;
use crate::util::Version;
use crate::volume::Volumes;
use crate::Error;
pub mod docker;
#[cfg(feature = "js_engine")]
pub mod js_scripts;
pub use models::ProcedureName;
// TODO: create RPC endpoint that looks up the appropriate action and calls `execute`
#[derive(Clone, Debug, Deserialize, Serialize, HasModel)]
#[serde(rename_all = "kebab-case")]
#[serde(tag = "type")]
pub enum PackageProcedure {
Docker(DockerProcedure),
#[cfg(feature = "js_engine")]
Script(js_scripts::JsProcedure),
}
impl PackageProcedure {
pub fn is_script(&self) -> bool {
match self {
#[cfg(feature = "js_engine")]
Self::Script(_) => true,
_ => false,
}
}
#[instrument]
pub fn validate(
&self,
eos_version: &Version,
volumes: &Volumes,
image_ids: &BTreeSet<ImageId>,
expected_io: bool,
) -> Result<(), color_eyre::eyre::Report> {
match self {
PackageProcedure::Docker(action) => {
action.validate(eos_version, volumes, image_ids, expected_io)
}
#[cfg(feature = "js_engine")]
PackageProcedure::Script(action) => action.validate(volumes),
}
}
#[instrument(skip(ctx, input))]
pub async fn execute<I: Serialize, O: for<'de> Deserialize<'de>>(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
name: ProcedureName,
volumes: &Volumes,
input: Option<I>,
allow_inject: bool,
timeout: Option<Duration>,
) -> Result<Result<O, (i32, String)>, Error> {
tracing::trace!("Procedure execute {} {} - {:?}", self, pkg_id, name);
match self {
PackageProcedure::Docker(procedure) => {
procedure
.execute(
ctx,
pkg_id,
pkg_version,
name,
volumes,
input,
allow_inject,
timeout,
)
.await
}
#[cfg(feature = "js_engine")]
PackageProcedure::Script(procedure) => {
procedure
.execute(
&ctx.datadir,
pkg_id,
pkg_version,
name,
volumes,
input,
timeout,
)
.await
}
}
}
#[instrument(skip(ctx, input))]
pub async fn sandboxed<I: Serialize, O: for<'de> Deserialize<'de>>(
&self,
ctx: &RpcContext,
pkg_id: &PackageId,
pkg_version: &Version,
volumes: &Volumes,
input: Option<I>,
timeout: Option<Duration>,
name: ProcedureName,
) -> Result<Result<O, (i32, String)>, Error> {
tracing::trace!("Procedure sandboxed {} {} - {:?}", self, pkg_id, name);
match self {
PackageProcedure::Docker(procedure) => {
procedure
.sandboxed(ctx, pkg_id, pkg_version, volumes, input, timeout)
.await
}
#[cfg(feature = "js_engine")]
PackageProcedure::Script(procedure) => {
procedure
.sandboxed(ctx, pkg_id, pkg_version, volumes, input, timeout, name)
.await
}
}
}
}
impl std::fmt::Display for PackageProcedure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PackageProcedure::Docker(_) => write!(f, "Docker")?,
#[cfg(feature = "js_engine")]
PackageProcedure::Script(_) => write!(f, "JS")?,
}
Ok(())
}
}
#[derive(Debug)]
pub struct NoOutput;
impl<'de> Deserialize<'de> for NoOutput {
fn deserialize<D>(_: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(NoOutput)
}
}

View File

@@ -5,10 +5,11 @@ use serde_json::Value;
use tracing::instrument; use tracing::instrument;
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::procedure::ProcedureName;
use crate::s9pk::manifest::{Manifest, PackageId}; use crate::s9pk::manifest::{Manifest, PackageId};
use crate::{Error, ErrorKind}; use crate::{Error, ErrorKind};
pub fn display_properties(response: Value, _: &ArgMatches<'_>) { pub fn display_properties(response: Value, _: &ArgMatches) {
println!("{}", response); println!("{}", response);
} }
@@ -35,7 +36,7 @@ pub async fn fetch_properties(ctx: RpcContext, id: PackageId) -> Result<Value, E
&ctx, &ctx,
&manifest.id, &manifest.id,
&manifest.version, &manifest.version,
Some(&format!("Properties-{}", rand::random::<u64>())), ProcedureName::Properties,
&manifest.volumes, &manifest.volumes,
None, None,
false, false,

View File

@@ -1,25 +1,25 @@
use std::io::{Read, Seek, SeekFrom, Write}; use sha2_old::{Digest, Sha512};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt, SeekFrom};
use digest::Digest;
use sha2::Sha512;
use tracing::instrument; use tracing::instrument;
use typed_builder::TypedBuilder; use typed_builder::TypedBuilder;
use super::header::{FileSection, Header}; use super::header::{FileSection, Header};
use super::manifest::Manifest; use super::manifest::Manifest;
use super::SIG_CONTEXT; use super::SIG_CONTEXT;
use crate::util::io::to_cbor_async_writer;
use crate::util::HashWriter; use crate::util::HashWriter;
use crate::{Error, ResultExt}; use crate::{Error, ResultExt};
#[derive(TypedBuilder)] #[derive(TypedBuilder)]
pub struct S9pkPacker< pub struct S9pkPacker<
'a, 'a,
W: Write + Seek, W: AsyncWriteExt + AsyncSeekExt,
RLicense: Read, RLicense: AsyncReadExt + Unpin,
RInstructions: Read, RInstructions: AsyncReadExt + Unpin,
RIcon: Read, RIcon: AsyncReadExt + Unpin,
RDockerImages: Read, RDockerImages: AsyncReadExt + Unpin,
RAssets: Read, RAssets: AsyncReadExt + Unpin,
RScripts: AsyncReadExt + Unpin,
> { > {
writer: W, writer: W,
manifest: &'a Manifest, manifest: &'a Manifest,
@@ -28,102 +28,117 @@ pub struct S9pkPacker<
icon: RIcon, icon: RIcon,
docker_images: RDockerImages, docker_images: RDockerImages,
assets: RAssets, assets: RAssets,
scripts: Option<RScripts>,
} }
impl< impl<
'a, 'a,
W: Write + Seek, W: AsyncWriteExt + AsyncSeekExt + Unpin,
RLicense: Read, RLicense: AsyncReadExt + Unpin,
RInstructions: Read, RInstructions: AsyncReadExt + Unpin,
RIcon: Read, RIcon: AsyncReadExt + Unpin,
RDockerImages: Read, RDockerImages: AsyncReadExt + Unpin,
RAssets: Read, RAssets: AsyncReadExt + Unpin,
> S9pkPacker<'a, W, RLicense, RInstructions, RIcon, RDockerImages, RAssets> RScripts: AsyncReadExt + Unpin,
> S9pkPacker<'a, W, RLicense, RInstructions, RIcon, RDockerImages, RAssets, RScripts>
{ {
/// BLOCKING /// BLOCKING
#[instrument(skip(self))] #[instrument(skip(self))]
pub fn pack(mut self, key: &ed25519_dalek::Keypair) -> Result<(), Error> { pub async fn pack(mut self, key: &ed25519_dalek::Keypair) -> Result<(), Error> {
let header_pos = self.writer.stream_position()?; let header_pos = self.writer.stream_position().await?;
if header_pos != 0 { if header_pos != 0 {
tracing::warn!("Appending to non-empty file."); tracing::warn!("Appending to non-empty file.");
} }
let mut header = Header::placeholder(); let mut header = Header::placeholder();
header.serialize(&mut self.writer).with_ctx(|_| { header.serialize(&mut self.writer).await.with_ctx(|_| {
( (
crate::ErrorKind::Serialization, crate::ErrorKind::Serialization,
"Writing Placeholder Header", "Writing Placeholder Header",
) )
})?; })?;
let mut position = self.writer.stream_position()?; let mut position = self.writer.stream_position().await?;
let mut writer = HashWriter::new(Sha512::new(), &mut self.writer); let mut writer = HashWriter::new(Sha512::new(), &mut self.writer);
// manifest // manifest
serde_cbor::ser::into_writer(self.manifest, &mut writer).with_ctx(|_| { to_cbor_async_writer(&mut writer, self.manifest).await?;
( let new_pos = writer.inner_mut().stream_position().await?;
crate::ErrorKind::Serialization,
"Serializing Manifest (CBOR)",
)
})?;
let new_pos = writer.inner_mut().stream_position()?;
header.table_of_contents.manifest = FileSection { header.table_of_contents.manifest = FileSection {
position, position,
length: new_pos - position, length: new_pos - position,
}; };
position = new_pos; position = new_pos;
// license // license
std::io::copy(&mut self.license, &mut writer) tokio::io::copy(&mut self.license, &mut writer)
.await
.with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying License"))?; .with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying License"))?;
let new_pos = writer.inner_mut().stream_position()?; let new_pos = writer.inner_mut().stream_position().await?;
header.table_of_contents.license = FileSection { header.table_of_contents.license = FileSection {
position, position,
length: new_pos - position, length: new_pos - position,
}; };
position = new_pos; position = new_pos;
// instructions // instructions
std::io::copy(&mut self.instructions, &mut writer) tokio::io::copy(&mut self.instructions, &mut writer)
.await
.with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying Instructions"))?; .with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying Instructions"))?;
let new_pos = writer.inner_mut().stream_position()?; let new_pos = writer.inner_mut().stream_position().await?;
header.table_of_contents.instructions = FileSection { header.table_of_contents.instructions = FileSection {
position, position,
length: new_pos - position, length: new_pos - position,
}; };
position = new_pos; position = new_pos;
// icon // icon
std::io::copy(&mut self.icon, &mut writer) tokio::io::copy(&mut self.icon, &mut writer)
.await
.with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying Icon"))?; .with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying Icon"))?;
let new_pos = writer.inner_mut().stream_position()?; let new_pos = writer.inner_mut().stream_position().await?;
header.table_of_contents.icon = FileSection { header.table_of_contents.icon = FileSection {
position, position,
length: new_pos - position, length: new_pos - position,
}; };
position = new_pos; position = new_pos;
// docker_images // docker_images
std::io::copy(&mut self.docker_images, &mut writer) tokio::io::copy(&mut self.docker_images, &mut writer)
.await
.with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying Docker Images"))?; .with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying Docker Images"))?;
let new_pos = writer.inner_mut().stream_position()?; let new_pos = writer.inner_mut().stream_position().await?;
header.table_of_contents.docker_images = FileSection { header.table_of_contents.docker_images = FileSection {
position, position,
length: new_pos - position, length: new_pos - position,
}; };
position = new_pos; position = new_pos;
// assets // assets
std::io::copy(&mut self.assets, &mut writer) tokio::io::copy(&mut self.assets, &mut writer)
.await
.with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying Assets"))?; .with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying Assets"))?;
let new_pos = writer.inner_mut().stream_position()?; let new_pos = writer.inner_mut().stream_position().await?;
header.table_of_contents.assets = FileSection { header.table_of_contents.assets = FileSection {
position, position,
length: new_pos - position, length: new_pos - position,
}; };
position = new_pos; position = new_pos;
// scripts
if let Some(mut scripts) = self.scripts {
tokio::io::copy(&mut scripts, &mut writer)
.await
.with_ctx(|_| (crate::ErrorKind::Filesystem, "Copying Scripts"))?;
let new_pos = writer.inner_mut().stream_position().await?;
header.table_of_contents.scripts = Some(FileSection {
position,
length: new_pos - position,
});
position = new_pos;
}
// header // header
let (hash, _) = writer.finish(); let (hash, _) = writer.finish();
self.writer.seek(SeekFrom::Start(header_pos))?; self.writer.seek(SeekFrom::Start(header_pos)).await?;
header.pubkey = key.public.clone(); header.pubkey = key.public.clone();
header.signature = key.sign_prehashed(hash, Some(SIG_CONTEXT))?; header.signature = key.sign_prehashed(hash, Some(SIG_CONTEXT))?;
header header
.serialize(&mut self.writer) .serialize(&mut self.writer)
.await
.with_ctx(|_| (crate::ErrorKind::Serialization, "Writing Header"))?; .with_ctx(|_| (crate::ErrorKind::Serialization, "Writing Header"))?;
self.writer.seek(SeekFrom::Start(position))?; self.writer.seek(SeekFrom::Start(position)).await?;
Ok(()) Ok(())
} }

View File

@@ -1,9 +1,8 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::io::Write;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use ed25519_dalek::{PublicKey, Signature}; use ed25519_dalek::{PublicKey, Signature};
use tokio::io::{AsyncRead, AsyncReadExt}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
use crate::Error; use crate::Error;
@@ -20,17 +19,17 @@ impl Header {
pub fn placeholder() -> Self { pub fn placeholder() -> Self {
Header { Header {
pubkey: PublicKey::default(), pubkey: PublicKey::default(),
signature: Signature::new([0; 64]), signature: Signature::from_bytes(&[0; 64]).expect("Invalid ed25519 signature"),
table_of_contents: Default::default(), table_of_contents: Default::default(),
} }
} }
// MUST BE SAME SIZE REGARDLESS OF DATA // MUST BE SAME SIZE REGARDLESS OF DATA
pub fn serialize<W: Write>(&self, mut writer: W) -> std::io::Result<()> { pub async fn serialize<W: AsyncWriteExt + Unpin>(&self, mut writer: W) -> std::io::Result<()> {
writer.write_all(&MAGIC)?; writer.write_all(&MAGIC).await?;
writer.write_all(&[VERSION])?; writer.write_all(&[VERSION]).await?;
writer.write_all(self.pubkey.as_bytes())?; writer.write_all(self.pubkey.as_bytes()).await?;
writer.write_all(self.signature.as_ref())?; writer.write_all(self.signature.as_ref()).await?;
self.table_of_contents.serialize(writer)?; self.table_of_contents.serialize(writer).await?;
Ok(()) Ok(())
} }
pub async fn deserialize<R: AsyncRead + Unpin>(mut reader: R) -> Result<Self, Error> { pub async fn deserialize<R: AsyncRead + Unpin>(mut reader: R) -> Result<Self, Error> {
@@ -38,7 +37,7 @@ impl Header {
reader.read_exact(&mut magic).await?; reader.read_exact(&mut magic).await?;
if magic != MAGIC { if magic != MAGIC {
return Err(Error::new( return Err(Error::new(
eyre!("Incorrect Magic"), eyre!("Incorrect Magic: {:?}", magic),
crate::ErrorKind::ParseS9pk, crate::ErrorKind::ParseS9pk,
)); ));
} }
@@ -46,7 +45,7 @@ impl Header {
reader.read_exact(&mut version).await?; reader.read_exact(&mut version).await?;
if version[0] != VERSION { if version[0] != VERSION {
return Err(Error::new( return Err(Error::new(
eyre!("Unknown Version"), eyre!("Unknown Version: {}", version[0]),
crate::ErrorKind::ParseS9pk, crate::ErrorKind::ParseS9pk,
)); ));
} }
@@ -56,7 +55,7 @@ impl Header {
.map_err(|e| Error::new(e, crate::ErrorKind::ParseS9pk))?; .map_err(|e| Error::new(e, crate::ErrorKind::ParseS9pk))?;
let mut sig_bytes = [0; 64]; let mut sig_bytes = [0; 64];
reader.read_exact(&mut sig_bytes).await?; reader.read_exact(&mut sig_bytes).await?;
let signature = Signature::new(sig_bytes); let signature = Signature::from_bytes(&sig_bytes).expect("Invalid ed25519 signature");
let table_of_contents = TableOfContents::deserialize(reader).await?; let table_of_contents = TableOfContents::deserialize(reader).await?;
Ok(Header { Ok(Header {
@@ -75,24 +74,34 @@ pub struct TableOfContents {
pub icon: FileSection, pub icon: FileSection,
pub docker_images: FileSection, pub docker_images: FileSection,
pub assets: FileSection, pub assets: FileSection,
pub scripts: Option<FileSection>,
} }
impl TableOfContents { impl TableOfContents {
pub fn serialize<W: Write>(&self, mut writer: W) -> std::io::Result<()> { pub async fn serialize<W: AsyncWriteExt + Unpin>(&self, mut writer: W) -> std::io::Result<()> {
let len: u32 = ((1 + "manifest".len() + 16) let len: u32 = ((1 + "manifest".len() + 16)
+ (1 + "license".len() + 16) + (1 + "license".len() + 16)
+ (1 + "instructions".len() + 16) + (1 + "instructions".len() + 16)
+ (1 + "icon".len() + 16) + (1 + "icon".len() + 16)
+ (1 + "docker_images".len() + 16) + (1 + "docker_images".len() + 16)
+ (1 + "assets".len() + 16)) as u32; + (1 + "assets".len() + 16)
writer.write_all(&u32::to_be_bytes(len))?; + (1 + "scripts".len() + 16)) as u32;
self.manifest.serialize_entry("manifest", &mut writer)?; writer.write_all(&u32::to_be_bytes(len)).await?;
self.license.serialize_entry("license", &mut writer)?; self.manifest
.serialize_entry("manifest", &mut writer)
.await?;
self.license.serialize_entry("license", &mut writer).await?;
self.instructions self.instructions
.serialize_entry("instructions", &mut writer)?; .serialize_entry("instructions", &mut writer)
self.icon.serialize_entry("icon", &mut writer)?; .await?;
self.icon.serialize_entry("icon", &mut writer).await?;
self.docker_images self.docker_images
.serialize_entry("docker_images", &mut writer)?; .serialize_entry("docker_images", &mut writer)
self.assets.serialize_entry("assets", &mut writer)?; .await?;
self.assets.serialize_entry("assets", &mut writer).await?;
self.scripts
.unwrap_or_default()
.serialize_entry("scripts", &mut writer)
.await?;
Ok(()) Ok(())
} }
pub async fn deserialize<R: AsyncRead + Unpin>(mut reader: R) -> std::io::Result<Self> { pub async fn deserialize<R: AsyncRead + Unpin>(mut reader: R) -> std::io::Result<Self> {
@@ -131,6 +140,7 @@ impl TableOfContents {
icon: from_table(&table, "icon")?, icon: from_table(&table, "icon")?,
docker_images: from_table(&table, "docker_images")?, docker_images: from_table(&table, "docker_images")?,
assets: from_table(&table, "assets")?, assets: from_table(&table, "assets")?,
scripts: table.get("scripts".as_bytes()).cloned(),
}) })
} }
} }
@@ -141,11 +151,15 @@ pub struct FileSection {
pub length: u64, pub length: u64,
} }
impl FileSection { impl FileSection {
pub fn serialize_entry<W: Write>(self, label: &str, mut writer: W) -> std::io::Result<()> { pub async fn serialize_entry<W: AsyncWriteExt + Unpin>(
writer.write_all(&[label.len() as u8])?; self,
writer.write_all(label.as_bytes())?; label: &str,
writer.write_all(&u64::to_be_bytes(self.position))?; mut writer: W,
writer.write_all(&u64::to_be_bytes(self.length))?; ) -> std::io::Result<()> {
writer.write_all(&[label.len() as u8]).await?;
writer.write_all(label.as_bytes()).await?;
writer.write_all(&u64::to_be_bytes(self.position)).await?;
writer.write_all(&u64::to_be_bytes(self.length)).await?;
Ok(()) Ok(())
} }
pub async fn deserialize_entry<R: AsyncRead + Unpin>( pub async fn deserialize_entry<R: AsyncRead + Unpin>(

View File

@@ -1,104 +1,24 @@
use std::borrow::Borrow;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::str::FromStr;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use patch_db::HasModel; use patch_db::HasModel;
use serde::{Deserialize, Serialize, Serializer}; use serde::{Deserialize, Serialize};
use url::Url; use url::Url;
use crate::action::{ActionImplementation, Actions}; use crate::action::Actions;
use crate::backup::BackupActions; use crate::backup::BackupActions;
use crate::config::action::ConfigActions; use crate::config::action::ConfigActions;
use crate::dependencies::Dependencies; use crate::dependencies::Dependencies;
use crate::id::{Id, InvalidId, SYSTEM_ID};
use crate::migration::Migrations; use crate::migration::Migrations;
use crate::net::interface::Interfaces; use crate::net::interface::Interfaces;
use crate::procedure::PackageProcedure;
use crate::status::health_check::HealthChecks; use crate::status::health_check::HealthChecks;
use crate::util::Version; use crate::util::Version;
use crate::version::{Current, VersionT}; use crate::version::{Current, VersionT};
use crate::volume::Volumes; use crate::volume::Volumes;
use crate::Error; use crate::Error;
pub const SYSTEM_PACKAGE_ID: PackageId<&'static str> = PackageId(SYSTEM_ID); pub use models::{PackageId, SYSTEM_PACKAGE_ID};
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PackageId<S: AsRef<str> = String>(Id<S>);
impl<'a> PackageId<&'a str> {
pub fn owned(&self) -> PackageId {
PackageId(self.0.owned())
}
}
impl FromStr for PackageId {
type Err = InvalidId;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(PackageId(Id::try_from(s.to_owned())?))
}
}
impl From<PackageId> for String {
fn from(value: PackageId) -> Self {
value.0.into()
}
}
impl<S: AsRef<str>> From<Id<S>> for PackageId<S> {
fn from(id: Id<S>) -> Self {
PackageId(id)
}
}
impl<S: AsRef<str>> std::ops::Deref for PackageId<S> {
type Target = S;
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl<S: AsRef<str>> AsRef<PackageId<S>> for PackageId<S> {
fn as_ref(&self) -> &PackageId<S> {
self
}
}
impl<S: AsRef<str>> std::fmt::Display for PackageId<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", &self.0)
}
}
impl<S: AsRef<str>> AsRef<str> for PackageId<S> {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl<S: AsRef<str>> Borrow<str> for PackageId<S> {
fn borrow(&self) -> &str {
self.0.as_ref()
}
}
impl<S: AsRef<str>> AsRef<Path> for PackageId<S> {
fn as_ref(&self) -> &Path {
self.0.as_ref().as_ref()
}
}
impl<'de, S> Deserialize<'de> for PackageId<S>
where
S: AsRef<str>,
Id<S>: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
Ok(PackageId(Deserialize::deserialize(deserializer)?))
}
}
impl<S> Serialize for PackageId<S>
where
S: AsRef<str>,
{
fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
where
Ser: Serializer,
{
Serialize::serialize(&self.0, serializer)
}
}
fn current_version() -> Version { fn current_version() -> Version {
Current::new().semver().into() Current::new().semver().into()
@@ -128,12 +48,12 @@ pub struct Manifest {
#[serde(default)] #[serde(default)]
pub alerts: Alerts, pub alerts: Alerts,
#[model] #[model]
pub main: ActionImplementation, pub main: PackageProcedure,
pub health_checks: HealthChecks, pub health_checks: HealthChecks,
#[model] #[model]
pub config: Option<ConfigActions>, pub config: Option<ConfigActions>,
#[model] #[model]
pub properties: Option<ActionImplementation>, pub properties: Option<PackageProcedure>,
#[model] #[model]
pub volumes: Volumes, pub volumes: Volumes,
// #[serde(default)] // #[serde(default)]
@@ -153,6 +73,29 @@ pub struct Manifest {
pub dependencies: Dependencies, pub dependencies: Dependencies,
} }
impl Manifest {
pub fn package_procedures(&self) -> impl Iterator<Item = &PackageProcedure> {
use std::iter::once;
let main = once(&self.main);
let cfg_get = self.config.as_ref().map(|a| &a.get).into_iter();
let cfg_set = self.config.as_ref().map(|a| &a.set).into_iter();
let props = self.properties.iter();
let backups = vec![&self.backup.create, &self.backup.restore].into_iter();
let migrations = self
.migrations
.to
.values()
.chain(self.migrations.from.values());
let actions = self.actions.0.values().map(|a| &a.implementation);
main.chain(cfg_get)
.chain(cfg_set)
.chain(props)
.chain(backups)
.chain(migrations)
.chain(actions)
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)] #[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct Assets { pub struct Assets {
@@ -166,6 +109,8 @@ pub struct Assets {
pub docker_images: Option<PathBuf>, pub docker_images: Option<PathBuf>,
#[serde(default)] #[serde(default)]
pub assets: Option<PathBuf>, pub assets: Option<PathBuf>,
#[serde(default)]
pub scripts: Option<PathBuf>,
} }
impl Assets { impl Assets {
pub fn license_path(&self) -> &Path { pub fn license_path(&self) -> &Path {
@@ -205,6 +150,12 @@ impl Assets {
.map(|a| a.as_path()) .map(|a| a.as_path())
.unwrap_or(Path::new("assets")) .unwrap_or(Path::new("assets"))
} }
pub fn scripts_path(&self) -> &Path {
self.scripts
.as_ref()
.map(|a| a.as_path())
.unwrap_or(Path::new("scripts"))
}
} }
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]

View File

@@ -13,7 +13,7 @@ use crate::s9pk::reader::S9pkReader;
use crate::util::display_none; use crate::util::display_none;
use crate::util::serde::IoFormat; use crate::util::serde::IoFormat;
use crate::volume::Volume; use crate::volume::Volume;
use crate::{Error, ResultExt}; use crate::{Error, ErrorKind, ResultExt};
pub mod builder; pub mod builder;
pub mod header; pub mod header;
@@ -22,11 +22,10 @@ pub mod reader;
pub const SIG_CONTEXT: &'static [u8] = b"s9pk"; pub const SIG_CONTEXT: &'static [u8] = b"s9pk";
#[command(cli_only, display(display_none), blocking)] #[command(cli_only, display(display_none))]
#[instrument(skip(ctx))] #[instrument(skip(ctx))]
pub fn pack(#[context] ctx: SdkContext, #[arg] path: Option<PathBuf>) -> Result<(), Error> { pub async fn pack(#[context] ctx: SdkContext, #[arg] path: Option<PathBuf>) -> Result<(), Error> {
use std::fs::File; use tokio::fs::File;
use std::io::Read;
let path = if let Some(path) = path { let path = if let Some(path) = path {
path path
@@ -34,11 +33,17 @@ pub fn pack(#[context] ctx: SdkContext, #[arg] path: Option<PathBuf>) -> Result<
std::env::current_dir()? std::env::current_dir()?
}; };
let manifest_value: Value = if path.join("manifest.toml").exists() { let manifest_value: Value = if path.join("manifest.toml").exists() {
IoFormat::Toml.from_reader(File::open(path.join("manifest.toml"))?)? IoFormat::Toml
.from_async_reader(File::open(path.join("manifest.toml")).await?)
.await?
} else if path.join("manifest.yaml").exists() { } else if path.join("manifest.yaml").exists() {
IoFormat::Yaml.from_reader(File::open(path.join("manifest.yaml"))?)? IoFormat::Yaml
.from_async_reader(File::open(path.join("manifest.yaml")).await?)
.await?
} else if path.join("manifest.json").exists() { } else if path.join("manifest.json").exists() {
IoFormat::Json.from_reader(File::open(path.join("manifest.json"))?)? IoFormat::Json
.from_async_reader(File::open(path.join("manifest.json")).await?)
.await?
} else { } else {
return Err(Error::new( return Err(Error::new(
eyre!("manifest not found"), eyre!("manifest not found"),
@@ -54,61 +59,88 @@ pub fn pack(#[context] ctx: SdkContext, #[arg] path: Option<PathBuf>) -> Result<
} }
let outfile_path = path.join(format!("{}.s9pk", manifest.id)); let outfile_path = path.join(format!("{}.s9pk", manifest.id));
let mut outfile = File::create(outfile_path)?; let mut outfile = File::create(outfile_path).await?;
S9pkPacker::builder() S9pkPacker::builder()
.manifest(&manifest) .manifest(&manifest)
.writer(&mut outfile) .writer(&mut outfile)
.license( .license(
File::open(path.join(manifest.assets.license_path())).with_ctx(|_| { File::open(path.join(manifest.assets.license_path()))
( .await
crate::ErrorKind::Filesystem, .with_ctx(|_| {
manifest.assets.license_path().display().to_string(), (
) crate::ErrorKind::Filesystem,
})?, manifest.assets.license_path().display().to_string(),
)
})?,
) )
.icon( .icon(
File::open(path.join(manifest.assets.icon_path())).with_ctx(|_| { File::open(path.join(manifest.assets.icon_path()))
( .await
crate::ErrorKind::Filesystem, .with_ctx(|_| {
manifest.assets.icon_path().display().to_string(), (
) crate::ErrorKind::Filesystem,
})?, manifest.assets.icon_path().display().to_string(),
)
})?,
) )
.instructions( .instructions(
File::open(path.join(manifest.assets.instructions_path())).with_ctx(|_| { File::open(path.join(manifest.assets.instructions_path()))
( .await
crate::ErrorKind::Filesystem, .with_ctx(|_| {
manifest.assets.instructions_path().display().to_string(), (
) crate::ErrorKind::Filesystem,
})?, manifest.assets.instructions_path().display().to_string(),
)
})?,
) )
.docker_images( .docker_images(
File::open(path.join(manifest.assets.docker_images_path())).with_ctx(|_| { File::open(path.join(manifest.assets.docker_images_path()))
( .await
crate::ErrorKind::Filesystem, .with_ctx(|_| {
manifest.assets.docker_images_path().display().to_string(), (
) crate::ErrorKind::Filesystem,
})?, manifest.assets.docker_images_path().display().to_string(),
)
})?,
) )
.assets({ .assets({
let mut assets = tar::Builder::new(Vec::new()); // TODO: Ideally stream this? best not to buffer in memory let mut assets = tokio_tar::Builder::new(Vec::new()); // TODO: Ideally stream this? best not to buffer in memory
for (asset_volume, _) in manifest for (asset_volume, _) in manifest
.volumes .volumes
.iter() .iter()
.filter(|(_, v)| matches!(v, &&Volume::Assets {})) .filter(|(_, v)| matches!(v, &&Volume::Assets {}))
{ {
assets.append_dir_all( assets
asset_volume, .append_dir_all(
path.join(manifest.assets.assets_path()).join(asset_volume), asset_volume,
)?; path.join(manifest.assets.assets_path()).join(asset_volume),
)
.await?;
} }
std::io::Cursor::new(assets.into_inner()?) std::io::Cursor::new(assets.into_inner().await?)
})
.scripts({
let script_path = path.join(manifest.assets.scripts_path()).join("embassy.js");
let needs_script = manifest.package_procedures().any(|a| a.is_script());
let has_script = script_path.exists();
match (needs_script, has_script) {
(true, true) => Some(File::open(script_path).await?),
(true, false) => {
return Err(Error::new(eyre!("Script is declared in manifest, but no such script exists at ./scripts/embassy.js"), ErrorKind::Pack).into())
}
(false, true) => {
tracing::warn!("Manifest does not declare any actions that use scripts, but a script exists at ./scripts/embassy.js");
None
}
(false, false) => None
}
}) })
.build() .build()
.pack(&ctx.developer_key()?)?; .pack(&ctx.developer_key()?)
outfile.sync_all()?; .await?;
outfile.sync_all().await?;
Ok(()) Ok(())
} }

View File

@@ -6,10 +6,10 @@ use std::str::FromStr;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use digest::Output; use digest_old::Output;
use ed25519_dalek::PublicKey; use ed25519_dalek::PublicKey;
use futures::TryStreamExt; use futures::TryStreamExt;
use sha2::{Digest, Sha512}; use sha2_old::{Digest, Sha512};
use tokio::fs::File; use tokio::fs::File;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeek, AsyncSeekExt, ReadBuf, Take}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeek, AsyncSeekExt, ReadBuf, Take};
use tracing::instrument; use tracing::instrument;
@@ -153,23 +153,26 @@ impl<R: AsyncRead + AsyncSeek + Unpin> S9pkReader<R> {
man.actions man.actions
.0 .0
.iter() .iter()
.map(|(_, action)| action.validate(&man.volumes, &validated_image_ids)) .map(|(_, action)| {
action.validate(&man.eos_version, &man.volumes, &validated_image_ids)
})
.collect::<Result<(), Error>>()?; .collect::<Result<(), Error>>()?;
man.backup.validate(&man.volumes, &validated_image_ids)?; man.backup
.validate(&man.eos_version, &man.volumes, &validated_image_ids)?;
if let Some(cfg) = &man.config { if let Some(cfg) = &man.config {
cfg.validate(&man.volumes, &validated_image_ids)?; cfg.validate(&man.eos_version, &man.volumes, &validated_image_ids)?;
} }
man.health_checks man.health_checks
.validate(&man.volumes, &validated_image_ids)?; .validate(&man.eos_version, &man.volumes, &validated_image_ids)?;
man.interfaces.validate()?; man.interfaces.validate()?;
man.main man.main
.validate(&man.volumes, &validated_image_ids, false) .validate(&man.eos_version, &man.volumes, &validated_image_ids, false)
.with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Main"))?; .with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Main"))?;
man.migrations man.migrations
.validate(&man.volumes, &validated_image_ids)?; .validate(&man.eos_version, &man.volumes, &validated_image_ids)?;
if let Some(props) = &man.properties { if let Some(props) = &man.properties {
props props
.validate(&man.volumes, &validated_image_ids, true) .validate(&man.eos_version, &man.volumes, &validated_image_ids, true)
.with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Properties"))?; .with_ctx(|_| (crate::ErrorKind::ValidateS9pk, "Properties"))?;
} }
man.volumes.validate(&man.interfaces)?; man.volumes.validate(&man.interfaces)?;
@@ -305,4 +308,11 @@ impl<R: AsyncRead + AsyncSeek + Unpin> S9pkReader<R> {
pub async fn assets<'a>(&'a mut self) -> Result<ReadHandle<'a, R>, Error> { pub async fn assets<'a>(&'a mut self) -> Result<ReadHandle<'a, R>, Error> {
Ok(self.read_handle(self.toc.assets).await?) Ok(self.read_handle(self.toc.assets).await?)
} }
pub async fn scripts<'a>(&'a mut self) -> Result<Option<ReadHandle<'a, R>>, Error> {
Ok(match self.toc.scripts {
None => None,
Some(a) => Some(self.read_handle(a).await?),
})
}
} }

View File

@@ -7,16 +7,17 @@ use std::time::Duration;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use digest::generic_array::GenericArray; use digest::generic_array::GenericArray;
use digest::OutputSizeUser;
use futures::future::BoxFuture; use futures::future::BoxFuture;
use futures::{FutureExt, TryFutureExt, TryStreamExt}; use futures::{FutureExt, TryFutureExt, TryStreamExt};
use nix::unistd::{Gid, Uid}; use nix::unistd::{Gid, Uid};
use openssl::x509::X509; use openssl::x509::X509;
use patch_db::LockType; use patch_db::{DbHandle, LockType};
use rpc_toolkit::command; use rpc_toolkit::command;
use rpc_toolkit::yajrc::RpcError; use rpc_toolkit::yajrc::RpcError;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use sqlx::{Executor, Sqlite}; use sqlx::{Connection, Executor, Sqlite};
use tokio::fs::File; use tokio::fs::File;
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
use torut::onion::{OnionAddressV3, TorSecretKeyV3}; use torut::onion::{OnionAddressV3, TorSecretKeyV3};
@@ -35,6 +36,7 @@ use crate::disk::mount::filesystem::cifs::Cifs;
use crate::disk::mount::filesystem::ReadOnly; use crate::disk::mount::filesystem::ReadOnly;
use crate::disk::mount::guard::TmpMountGuard; use crate::disk::mount::guard::TmpMountGuard;
use crate::disk::util::{pvscan, recovery_info, DiskListResponse, EmbassyOsRecoveryInfo}; use crate::disk::util::{pvscan, recovery_info, DiskListResponse, EmbassyOsRecoveryInfo};
use crate::disk::REPAIR_DISK_PATH;
use crate::hostname::PRODUCT_KEY_PATH; use crate::hostname::PRODUCT_KEY_PATH;
use crate::id::Id; use crate::id::Id;
use crate::init::init; use crate::init::init;
@@ -75,9 +77,7 @@ pub struct StatusRes {
#[command(rpc_only, metadata(authenticated = false))] #[command(rpc_only, metadata(authenticated = false))]
pub async fn status(#[context] ctx: SetupContext) -> Result<StatusRes, Error> { pub async fn status(#[context] ctx: SetupContext) -> Result<StatusRes, Error> {
Ok(StatusRes { Ok(StatusRes {
product_key: tokio::fs::metadata("/embassy-os/product_key.txt") product_key: tokio::fs::metadata(PRODUCT_KEY_PATH).await.is_ok(),
.await
.is_ok(),
migrating: ctx.recovery_status.read().await.is_some(), migrating: ctx.recovery_status.read().await.is_some(),
}) })
} }
@@ -96,38 +96,87 @@ pub async fn list_disks() -> Result<DiskListResponse, Error> {
pub async fn attach( pub async fn attach(
#[context] ctx: SetupContext, #[context] ctx: SetupContext,
#[arg] guid: Arc<String>, #[arg] guid: Arc<String>,
#[arg(rename = "embassy-password")] password: Option<String>,
) -> Result<SetupResult, Error> { ) -> Result<SetupResult, Error> {
crate::disk::main::import( let requires_reboot = crate::disk::main::import(
&*guid, &*guid,
&ctx.datadir, &ctx.datadir,
RepairStrategy::Preen, if tokio::fs::metadata(REPAIR_DISK_PATH).await.is_ok() {
RepairStrategy::Aggressive
} else {
RepairStrategy::Preen
},
DEFAULT_PASSWORD, DEFAULT_PASSWORD,
) )
.await?; .await?;
if tokio::fs::metadata(REPAIR_DISK_PATH).await.is_ok() {
tokio::fs::remove_file(REPAIR_DISK_PATH)
.await
.with_ctx(|_| (ErrorKind::Filesystem, REPAIR_DISK_PATH))?;
}
if requires_reboot.0 {
crate::disk::main::export(&*guid, &ctx.datadir).await?;
return Err(Error::new(
eyre!(
"Errors were corrected with your disk, but the Embassy must be restarted in order to proceed"
),
ErrorKind::DiskManagement,
));
}
let product_key = ctx.product_key().await?;
let product_key_path = Path::new("/embassy-data/main/product_key.txt"); let product_key_path = Path::new("/embassy-data/main/product_key.txt");
if tokio::fs::metadata(product_key_path).await.is_ok() { if tokio::fs::metadata(product_key_path).await.is_ok() {
let pkey = tokio::fs::read_to_string(product_key_path).await?; let pkey = Arc::new(
if pkey.trim() != &*ctx.product_key().await? { tokio::fs::read_to_string(product_key_path)
.await?
.trim()
.to_owned(),
);
if pkey != product_key {
crate::disk::main::export(&*guid, &ctx.datadir).await?; crate::disk::main::export(&*guid, &ctx.datadir).await?;
return Err(Error::new( return Err(Error::new(
eyre!("The EmbassyOS product key does not match the supplied drive"), eyre!(
"The EmbassyOS product key does not match the supplied drive: {}",
pkey
),
ErrorKind::ProductKeyMismatch, ErrorKind::ProductKeyMismatch,
)); ));
} }
} }
init( init(
&RpcContextConfig::load(ctx.config_path.as_ref()).await?, &RpcContextConfig::load(ctx.config_path.as_ref()).await?,
&*ctx.product_key().await?, &*product_key,
) )
.await?; .await?;
let secrets = ctx.secret_store().await?; let secrets = ctx.secret_store().await?;
let tor_key = crate::net::tor::os_key(&mut secrets.acquire().await?).await?; let db = ctx.db(&secrets).await?;
let mut secrets_handle = secrets.acquire().await?;
let mut db_handle = db.handle();
let mut secrets_tx = secrets_handle.begin().await?;
let mut db_tx = db_handle.begin().await?;
if let Some(password) = password {
let set_password_receipt = crate::auth::SetPasswordReceipt::new(&mut db_tx).await?;
crate::auth::set_password(
&mut db_tx,
&set_password_receipt,
&mut secrets_tx,
&password,
)
.await?;
}
let tor_key = crate::net::tor::os_key(&mut secrets_tx).await?;
db_tx.commit(None).await?;
secrets_tx.commit().await?;
let (_, root_ca) = SslManager::init(secrets).await?.export_root_ca().await?; let (_, root_ca) = SslManager::init(secrets).await?.export_root_ca().await?;
let setup_result = SetupResult { let setup_result = SetupResult {
tor_address: format!("http://{}", tor_key.public().get_onion_address()), tor_address: format!("http://{}", tor_key.public().get_onion_address()),
lan_address: format!( lan_address: format!(
"https://embassy-{}.local", "https://embassy-{}.local",
crate::hostname::derive_id(&*ctx.product_key().await?) crate::hostname::derive_id(&*product_key)
), ),
root_ca: String::from_utf8(root_ca.to_pem()?)?, root_ca: String::from_utf8(root_ca.to_pem()?)?,
}; };
@@ -308,7 +357,7 @@ pub async fn execute_inner(
) )
.await?, .await?,
); );
crate::disk::main::import( let _ = crate::disk::main::import(
&*guid, &*guid,
&ctx.datadir, &ctx.datadir,
RepairStrategy::Preen, RepairStrategy::Preen,
@@ -352,7 +401,7 @@ pub async fn execute_inner(
}) })
.await .await
{ {
BEETHOVEN.play().await.unwrap_or_default(); // ignore error in playing the song (&BEETHOVEN).play().await.unwrap_or_default(); // ignore error in playing the song
tracing::error!("Error recovering drive!: {}", e); tracing::error!("Error recovering drive!: {}", e);
tracing::debug!("{:?}", e); tracing::debug!("{:?}", e);
*ctx.recovery_status.write().await = Some(Err(e.into())); *ctx.recovery_status.write().await = Some(Err(e.into()));
@@ -451,7 +500,7 @@ async fn recover(
async fn shasum( async fn shasum(
path: impl AsRef<Path>, path: impl AsRef<Path>,
) -> Result<GenericArray<u8, <Sha256 as Digest>::OutputSize>, Error> { ) -> Result<GenericArray<u8, <Sha256 as OutputSizeUser>::OutputSize>, Error> {
use tokio::io::AsyncReadExt; use tokio::io::AsyncReadExt;
let mut rdr = tokio::fs::File::open(path).await?; let mut rdr = tokio::fs::File::open(path).await?;

View File

@@ -6,10 +6,10 @@ use rpc_toolkit::command;
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::disk::main::export; use crate::disk::main::export;
use crate::init::SYSTEM_REBUILD_PATH; use crate::init::{STANDBY_MODE_PATH, SYSTEM_REBUILD_PATH};
use crate::sound::SHUTDOWN; use crate::sound::SHUTDOWN;
use crate::util::{display_none, Invoke}; use crate::util::{display_none, Invoke};
use crate::Error; use crate::{Error, ErrorKind};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Shutdown { pub struct Shutdown {
@@ -54,23 +54,24 @@ impl Shutdown {
tracing::debug!("{:?}", e); tracing::debug!("{:?}", e);
} }
} }
if let Err(e) = SHUTDOWN.play().await { if self.restart {
tracing::error!("Error Playing Shutdown Song: {}", e); if let Err(e) = SHUTDOWN.play().await {
tracing::debug!("{:?}", e); tracing::error!("Error Playing Shutdown Song: {}", e);
tracing::debug!("{:?}", e);
}
} else {
tokio::fs::write(STANDBY_MODE_PATH, "").await.unwrap();
Command::new("sync")
.invoke(ErrorKind::Filesystem)
.await
.unwrap();
} }
}); });
drop(rt); drop(rt);
if self.restart { if !self.restart {
Command::new("reboot").spawn().unwrap().wait().unwrap(); std::fs::write(STANDBY_MODE_PATH, "").unwrap();
} else {
Command::new("shutdown")
.arg("-h")
.arg("now")
.spawn()
.unwrap()
.wait()
.unwrap();
} }
Command::new("reboot").spawn().unwrap().wait().unwrap();
} }
} }

View File

@@ -112,19 +112,23 @@ pub struct Song<Notes> {
tempo_qpm: u16, tempo_qpm: u16,
note_sequence: Notes, note_sequence: Notes,
} }
impl<'a, T: 'a> Song<T> impl<'a, T> Song<T>
where where
&'a T: IntoIterator<Item = &'a (Option<Note>, TimeSlice)>, T: IntoIterator<Item = (Option<Note>, TimeSlice)> + Clone,
{ {
#[instrument(skip(self))] #[instrument(skip(self))]
pub async fn play(&'a self) -> Result<(), Error> { pub async fn play(&self) -> Result<(), Error> {
#[cfg(feature = "sound")] #[cfg(feature = "sound")]
{ {
let mut sound = SoundInterface::lease().await?; let mut sound = SoundInterface::lease().await?;
for (note, slice) in &self.note_sequence { for (note, slice) in self.note_sequence.clone() {
match note { match note {
None => tokio::time::sleep(slice.to_duration(self.tempo_qpm)).await, None => tokio::time::sleep(slice.to_duration(self.tempo_qpm)).await,
Some(n) => sound.play_for_time_slice(self.tempo_qpm, n, slice).await?, Some(n) => {
sound
.play_for_time_slice(self.tempo_qpm, &n, &slice)
.await?
}
}; };
} }
sound.close().await?; sound.close().await?;
@@ -285,6 +289,7 @@ pub fn circle_of_fourths(note: &Note) -> impl Iterator<Item = Note> {
iterate(|n| interval(&FOURTH, n), note) iterate(|n| interval(&FOURTH, n), note)
} }
#[derive(Clone, Debug)]
pub struct CircleOf<'a> { pub struct CircleOf<'a> {
current: Note, current: Note,
duration: TimeSlice, duration: TimeSlice,

View File

@@ -12,7 +12,7 @@ use crate::util::display_none;
use crate::util::serde::{display_serializable, IoFormat}; use crate::util::serde::{display_serializable, IoFormat};
use crate::{Error, ErrorKind}; use crate::{Error, ErrorKind};
static SSH_AUTHORIZED_KEYS_FILE: &str = "/root/.ssh/authorized_keys"; static SSH_AUTHORIZED_KEYS_FILE: &str = "/home/start9/.ssh/authorized_keys";
#[derive(Debug, serde::Deserialize, serde::Serialize)] #[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct PubKey( pub struct PubKey(
@@ -114,7 +114,7 @@ pub async fn delete(#[context] ctx: RpcContext, #[arg] fingerprint: String) -> R
} }
} }
fn display_all_ssh_keys(all: Vec<SshKeyResponse>, matches: &ArgMatches<'_>) { fn display_all_ssh_keys(all: Vec<SshKeyResponse>, matches: &ArgMatches) {
use prettytable::*; use prettytable::*;
if matches.is_present("format") { if matches.is_present("format") {

View File

@@ -1,58 +1,34 @@
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer, Serialize}; use serde::{Deserialize, Serialize};
use tracing::instrument; use tracing::instrument;
use crate::action::{ActionImplementation, NoOutput};
use crate::context::RpcContext; use crate::context::RpcContext;
use crate::id::{Id, ImageId}; use crate::id::ImageId;
use crate::procedure::{NoOutput, PackageProcedure, ProcedureName};
use crate::s9pk::manifest::PackageId; use crate::s9pk::manifest::PackageId;
use crate::util::serde::Duration; use crate::util::serde::Duration;
use crate::util::Version; use crate::util::Version;
use crate::volume::Volumes; use crate::volume::Volumes;
use crate::{Error, ResultExt}; use crate::{Error, ResultExt};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] pub use models::HealthCheckId;
pub struct HealthCheckId<S: AsRef<str> = String>(Id<S>);
impl<S: AsRef<str>> std::fmt::Display for HealthCheckId<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", &self.0)
}
}
impl<S: AsRef<str>> AsRef<str> for HealthCheckId<S> {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl<'de, S> Deserialize<'de> for HealthCheckId<S>
where
S: AsRef<str>,
Id<S>: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(HealthCheckId(Deserialize::deserialize(deserializer)?))
}
}
impl<S: AsRef<str>> AsRef<Path> for HealthCheckId<S> {
fn as_ref(&self) -> &Path {
self.0.as_ref().as_ref()
}
}
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct HealthChecks(pub BTreeMap<HealthCheckId, HealthCheck>); pub struct HealthChecks(pub BTreeMap<HealthCheckId, HealthCheck>);
impl HealthChecks { impl HealthChecks {
#[instrument] #[instrument]
pub fn validate(&self, volumes: &Volumes, image_ids: &BTreeSet<ImageId>) -> Result<(), Error> { pub fn validate(
&self,
eos_version: &Version,
volumes: &Volumes,
image_ids: &BTreeSet<ImageId>,
) -> Result<(), Error> {
for (_, check) in &self.0 { for (_, check) in &self.0 {
check check
.implementation .implementation
.validate(&volumes, image_ids, false) .validate(eos_version, &volumes, image_ids, false)
.with_ctx(|_| { .with_ctx(|_| {
( (
crate::ErrorKind::ValidateS9pk, crate::ErrorKind::ValidateS9pk,
@@ -89,7 +65,7 @@ pub struct HealthCheck {
pub name: String, pub name: String,
pub success_message: Option<String>, pub success_message: Option<String>,
#[serde(flatten)] #[serde(flatten)]
implementation: ActionImplementation, implementation: PackageProcedure,
pub timeout: Option<Duration>, pub timeout: Option<Duration>,
} }
impl HealthCheck { impl HealthCheck {
@@ -109,7 +85,7 @@ impl HealthCheck {
ctx, ctx,
pkg_id, pkg_id,
pkg_version, pkg_version,
Some(&format!("{}Health", id)), ProcedureName::Health(id.clone()),
volumes, volumes,
Some(Utc::now().signed_duration_since(started).num_milliseconds()), Some(Utc::now().signed_duration_since(started).num_milliseconds()),
true, true,

View File

@@ -24,8 +24,11 @@ pub struct Status {
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum MainStatus { pub enum MainStatus {
Stopped, Stopped,
Restarting,
Stopping, Stopping,
Starting, Starting {
restarting: bool,
},
Running { Running {
started: DateTime<Utc>, started: DateTime<Utc>,
health: BTreeMap<HealthCheckId, HealthCheckResult>, health: BTreeMap<HealthCheckId, HealthCheckResult>,
@@ -38,25 +41,36 @@ pub enum MainStatus {
impl MainStatus { impl MainStatus {
pub fn running(&self) -> bool { pub fn running(&self) -> bool {
match self { match self {
MainStatus::Starting MainStatus::Starting { .. }
| MainStatus::Running { .. } | MainStatus::Running { .. }
| MainStatus::BackingUp { | MainStatus::BackingUp {
started: Some(_), .. started: Some(_), ..
} => true, } => true,
MainStatus::Stopped MainStatus::Stopped
| MainStatus::Stopping | MainStatus::Stopping
| MainStatus::Restarting
| MainStatus::BackingUp { started: None, .. } => false, | MainStatus::BackingUp { started: None, .. } => false,
} }
} }
pub fn stop(&mut self) { pub fn stop(&mut self) {
match self { match self {
MainStatus::Starting | MainStatus::Running { .. } => { MainStatus::Starting { .. } | MainStatus::Running { .. } => {
*self = MainStatus::Stopping; *self = MainStatus::Stopping;
} }
MainStatus::BackingUp { started, .. } => { MainStatus::BackingUp { started, .. } => {
*started = None; *started = None;
} }
MainStatus::Stopped | MainStatus::Stopping => (), MainStatus::Stopped | MainStatus::Stopping | MainStatus::Restarting => (),
}
}
pub fn started(&self) -> Option<DateTime<Utc>> {
match self {
MainStatus::Running { started, .. } => Some(*started),
MainStatus::BackingUp { started, .. } => *started,
MainStatus::Stopped => None,
MainStatus::Restarting => None,
MainStatus::Stopping => None,
MainStatus::Starting { .. } => None,
} }
} }
} }

View File

@@ -30,7 +30,9 @@ use crate::disk::mount::filesystem::{FileSystem, ReadWrite};
use crate::disk::mount::guard::TmpMountGuard; use crate::disk::mount::guard::TmpMountGuard;
use crate::disk::BOOT_RW_PATH; use crate::disk::BOOT_RW_PATH;
use crate::notifications::NotificationLevel; use crate::notifications::NotificationLevel;
use crate::sound::{BEP, UPDATE_FAILED_1, UPDATE_FAILED_2, UPDATE_FAILED_3, UPDATE_FAILED_4}; use crate::sound::{
CIRCLE_OF_5THS_SHORT, UPDATE_FAILED_1, UPDATE_FAILED_2, UPDATE_FAILED_3, UPDATE_FAILED_4,
};
use crate::update::latest_information::LatestInformation; use crate::update::latest_information::LatestInformation;
use crate::util::Invoke; use crate::util::Invoke;
use crate::version::{Current, VersionT}; use crate::version::{Current, VersionT};
@@ -74,7 +76,7 @@ pub enum UpdateResult {
Updating, Updating,
} }
fn display_update_result(status: WithRevision<UpdateResult>, _: &ArgMatches<'_>) { fn display_update_result(status: WithRevision<UpdateResult>, _: &ArgMatches) {
match status.response { match status.response {
UpdateResult::Updating => { UpdateResult::Updating => {
println!("Updating..."); println!("Updating...");
@@ -137,7 +139,7 @@ async fn maybe_do_update(
"{}/eos/v0/latest?eos-version={}&arch={}", "{}/eos/v0/latest?eos-version={}&arch={}",
marketplace_url, marketplace_url,
Current::new().semver(), Current::new().semver(),
platforms::TARGET_ARCH, &*crate::ARCH,
)) ))
.await .await
.with_kind(ErrorKind::Network)? .with_kind(ErrorKind::Network)?
@@ -154,7 +156,7 @@ async fn maybe_do_update(
.version() .version()
.get_mut(&mut db) .get_mut(&mut db)
.await?; .await?;
if &latest_version <= &current_version { if &latest_version < &current_version {
return Ok(None); return Ok(None);
} }
let mut tx = db.begin().await?; let mut tx = db.begin().await?;
@@ -204,9 +206,10 @@ async fn maybe_do_update(
Ok(()) => { Ok(()) => {
status.updated = true; status.updated = true;
status.save(&mut db).await.expect("could not save status"); status.save(&mut db).await.expect("could not save status");
BEP.play().await.expect("could not bep"); CIRCLE_OF_5THS_SHORT
BEP.play().await.expect("could not bep"); .play()
BEP.play().await.expect("could not bep"); .await
.expect("could not play sound");
} }
Err(e) => { Err(e) => {
status.save(&mut db).await.expect("could not save status"); status.save(&mut db).await.expect("could not save status");
@@ -301,7 +304,7 @@ impl std::fmt::Display for EosUrl {
self.base, self.base,
self.version, self.version,
Current::new().semver(), Current::new().semver(),
platforms::TARGET_ARCH, &*crate::ARCH,
) )
} }
} }
@@ -353,7 +356,12 @@ async fn write_stream_to_label<Db: DbHandle>(
pin!(stream_download); pin!(stream_download);
let mut downloaded = 0; let mut downloaded = 0;
let mut last_progress_update = Instant::now(); let mut last_progress_update = Instant::now();
while let Some(Ok(item)) = stream_download.next().await { while let Some(item) = stream_download
.next()
.await
.transpose()
.with_kind(ErrorKind::Network)?
{
file.write_all(&item) file.write_all(&item)
.await .await
.with_kind(ErrorKind::Filesystem)?; .with_kind(ErrorKind::Filesystem)?;
@@ -371,6 +379,7 @@ async fn write_stream_to_label<Db: DbHandle>(
} }
file.flush().await.with_kind(ErrorKind::Filesystem)?; file.flush().await.with_kind(ErrorKind::Filesystem)?;
file.shutdown().await.with_kind(ErrorKind::Filesystem)?; file.shutdown().await.with_kind(ErrorKind::Filesystem)?;
file.sync_all().await.with_kind(ErrorKind::Filesystem)?;
drop(file); drop(file);
Ok(hasher.finalize().to_vec()) Ok(hasher.finalize().to_vec())
} }

View File

@@ -0,0 +1,56 @@
use std::fs::File;
use std::path::{Path, PathBuf};
use serde::Deserialize;
use serde_json::Value;
use crate::util::serde::IoFormat;
use crate::{Config, Error, ResultExt};
pub const CONFIG_PATH: &str = "/etc/embassy/config.yaml";
pub const CONFIG_PATH_LOCAL: &str = ".embassy/config.yaml";
pub fn local_config_path() -> Option<PathBuf> {
if let Ok(home) = std::env::var("HOME") {
Some(Path::new(&home).join(CONFIG_PATH_LOCAL))
} else {
None
}
}
/// BLOCKING
pub fn load_config_from_paths<'a, T: for<'de> Deserialize<'de>>(
paths: impl IntoIterator<Item = impl AsRef<Path>>,
) -> Result<T, Error> {
let mut config = Default::default();
for path in paths {
if path.as_ref().exists() {
let format: IoFormat = path
.as_ref()
.extension()
.and_then(|s| s.to_str())
.map(|f| f.parse())
.transpose()?
.unwrap_or_default();
let new = format.from_reader(File::open(path)?)?;
config = merge_configs(config, new);
}
}
serde_json::from_value(Value::Object(config)).with_kind(crate::ErrorKind::Deserialization)
}
pub fn merge_configs(mut first: Config, second: Config) -> Config {
for (k, v) in second.into_iter() {
let new = match first.remove(&k) {
None => v,
Some(old) => match (old, v) {
(Value::Object(first), Value::Object(second)) => {
Value::Object(merge_configs(first, second))
}
(first, _) => first,
},
};
first.insert(k, new);
}
first
}

View File

@@ -153,6 +153,17 @@ where
.map_err(color_eyre::eyre::Error::from) .map_err(color_eyre::eyre::Error::from)
.with_kind(crate::ErrorKind::Deserialization) .with_kind(crate::ErrorKind::Deserialization)
} }
pub async fn to_cbor_async_writer<T, W>(mut writer: W, value: &T) -> Result<(), crate::Error>
where
T: serde::Serialize,
W: AsyncWrite + Unpin,
{
let mut buffer = Vec::new();
serde_cbor::ser::into_writer(value, &mut buffer).with_kind(crate::ErrorKind::Serialization)?;
buffer.extend_from_slice(b"\n");
writer.write_all(&buffer).await?;
Ok(())
}
pub async fn from_json_async_reader<T, R>(mut reader: R) -> Result<T, crate::Error> pub async fn from_json_async_reader<T, R>(mut reader: R) -> Result<T, crate::Error>
where where

View File

@@ -1,4 +1,3 @@
use tracing::metadata::LevelFilter;
use tracing::Subscriber; use tracing::Subscriber;
use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::util::SubscriberInitExt;

Some files were not shown because too many files have changed in this diff Show More