Deployr 0.1.0: cross-platform application deployment CLI
Replaces Ninite for endpoint software: one catalog, one command line, and the same behaviour on Windows, macOS and Linux. Single static binary, no server and no agent, driven from an RMM script runner or by hand. - catalog of ~50 apps compiled into the binary, extendable with YAML overlays in catalog.d or via --catalog, no rebuild required - providers: winget, choco, brew, cask, apt, dnf/yum, zypper, pacman, flatpak, snap, plus direct vendor downloads (msi/exe/msu/dmg/pkg/deb/rpm/zip/tar.gz/ AppImage) - sources are tried in order and fall through, so one catalog entry covers winget on Windows, a cask on macOS and the vendor .deb on Debian - provider-independent detection (registry, paths, commands) makes runs idempotent even for software installed by hand - unattended by construction: stdin closed, silent flags, per-command timeouts - handles the traps that break naive wrappers: winget missing under SYSTEM, Homebrew refusing root, 1641/3010 reboot exits, "already installed" reported as failure - --json summary on stdout with progress on stderr, and RMM-friendly exit codes (0 ok, 1 failed, 2 usage, 3 privileges) Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
commit
4909edee2d
40 files changed
+6714
No files matched your search
@@ -0,0 +1,9 @@
|
|||||||
|
# The shell scripts and the catalog are consumed on Linux and macOS: they must
|
||||||
|
# keep LF endings no matter what a Windows checkout does.
|
||||||
|
* text=auto eol=lf
|
||||||
|
|
||||||
|
*.ps1 text eol=crlf
|
||||||
|
*.bat text eol=crlf
|
||||||
|
*.cmd text eol=crlf
|
||||||
|
|
||||||
|
go.sum linguist-generated
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/dist/
|
||||||
|
/build/
|
||||||
|
*.exe
|
||||||
|
*.syso
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
*.log
|
||||||
|
/.idea/
|
||||||
|
/.vscode/
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
VERSION ?= dev
|
||||||
|
PKG := git.starwarslab.us/ATOM_IT/Deployr/internal/version
|
||||||
|
COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
|
||||||
|
DATE := $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||||
|
LDFLAGS := -s -w -X $(PKG).Version=$(VERSION) -X $(PKG).Commit=$(COMMIT) -X $(PKG).Date=$(DATE)
|
||||||
|
|
||||||
|
.PHONY: all build test vet fmt check dist clean install
|
||||||
|
|
||||||
|
all: check build
|
||||||
|
|
||||||
|
## build: compile for the host platform into ./deployr
|
||||||
|
build:
|
||||||
|
CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o deployr ./cmd/deployr
|
||||||
|
|
||||||
|
## test: run the unit tests
|
||||||
|
test:
|
||||||
|
go test ./...
|
||||||
|
|
||||||
|
## vet: static analysis for every supported platform
|
||||||
|
vet:
|
||||||
|
go vet ./...
|
||||||
|
GOOS=windows GOARCH=amd64 go vet ./...
|
||||||
|
GOOS=darwin GOARCH=arm64 go vet ./...
|
||||||
|
GOOS=linux GOARCH=amd64 go vet ./...
|
||||||
|
|
||||||
|
fmt:
|
||||||
|
gofmt -l -w .
|
||||||
|
|
||||||
|
## check: fmt verification, vet and tests -- run this before pushing
|
||||||
|
check: vet test
|
||||||
|
@test -z "$$(gofmt -l . )" || (echo "gofmt needed:"; gofmt -l .; exit 1)
|
||||||
|
|
||||||
|
## dist: cross-compile release binaries into dist/
|
||||||
|
dist:
|
||||||
|
VERSION=$(VERSION) ./scripts/build.sh
|
||||||
|
|
||||||
|
## install: install to /usr/local/bin (Unix)
|
||||||
|
install: build
|
||||||
|
install -m 0755 deployr /usr/local/bin/deployr
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -rf dist deployr deployr.exe
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
# Deployr
|
||||||
|
|
||||||
|
Cross-platform application deployment and patching from a single binary.
|
||||||
|
|
||||||
|
Deployr replaces Ninite for endpoint software: one catalog of applications, one
|
||||||
|
command line, and the same behaviour on **Windows, macOS and Linux**. It prefers
|
||||||
|
the machine's native package manager and falls back to the vendor's own
|
||||||
|
installer when that route is missing or unreliable.
|
||||||
|
|
||||||
|
There is no server and no agent. Deployr is a single static executable you drop
|
||||||
|
on a machine — by hand, or through your RMM's script runner — and it exits with
|
||||||
|
a status code your automation can branch on.
|
||||||
|
|
||||||
|
```
|
||||||
|
deployr install chrome 7zip vlc
|
||||||
|
deployr install @standard --json
|
||||||
|
deployr update --all
|
||||||
|
deployr status
|
||||||
|
```
|
||||||
|
|
||||||
|
## Why not just call winget / brew / apt directly?
|
||||||
|
|
||||||
|
Because the interesting part is everything around the package manager:
|
||||||
|
|
||||||
|
- **winget does not exist under SYSTEM.** The `winget` on PATH is an app
|
||||||
|
execution alias that only resolves inside a user session — exactly what an RMM
|
||||||
|
script does not have. Deployr finds the real payload under `WindowsApps`.
|
||||||
|
- **Homebrew refuses to run as root**, which is the context an MDM or RMM gives
|
||||||
|
you. Deployr drops to the account that owns the Homebrew prefix.
|
||||||
|
- **Package managers lie with exit codes.** "Already installed" and "no
|
||||||
|
applicable upgrade" are failures to winget and successes to you.
|
||||||
|
- **Not every app is in every repo.** A source list per platform means Chrome
|
||||||
|
comes from winget on Windows, a cask on macOS and Google's own `.deb` on
|
||||||
|
Debian, and it is one catalog entry.
|
||||||
|
- **Unattended means unattended.** Every command runs with stdin closed, silent
|
||||||
|
flags applied and a timeout, so nothing ever waits on a prompt nobody will see.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Download the binary for the machine from `dist/` (see [Building](#building)) and
|
||||||
|
put it somewhere on PATH.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# Windows (elevated)
|
||||||
|
Copy-Item deployr_windows_amd64.exe C:\ProgramData\Deployr\deployr.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# macOS / Linux
|
||||||
|
sudo install -m 0755 deployr_linux_amd64 /usr/local/bin/deployr
|
||||||
|
```
|
||||||
|
|
||||||
|
Verify the machine is ready:
|
||||||
|
|
||||||
|
```
|
||||||
|
deployr doctor
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
| Command | What it does |
|
||||||
|
| --- | --- |
|
||||||
|
| `deployr install <app...>` | Install applications that are not already present |
|
||||||
|
| `deployr update <app...>` | Update installed applications (`--all` for everything present) |
|
||||||
|
| `deployr uninstall <app...>` | Remove applications |
|
||||||
|
| `deployr list` | Show the catalog, filtered to this platform |
|
||||||
|
| `deployr status` | Report what is installed and at which version |
|
||||||
|
| `deployr info <app>` | Show one app's install recipe and current state |
|
||||||
|
| `deployr profiles` | List the bundles defined in the catalog |
|
||||||
|
| `deployr doctor` | Platform, privileges, directories and available providers |
|
||||||
|
| `deployr catalog validate` | Check a catalog overlay before you ship it |
|
||||||
|
|
||||||
|
Anything prefixed with `@` is a profile — a named bundle of apps:
|
||||||
|
|
||||||
|
```
|
||||||
|
deployr install @standard @security
|
||||||
|
```
|
||||||
|
|
||||||
|
### Useful flags
|
||||||
|
|
||||||
|
```
|
||||||
|
--json machine-readable summary on stdout (progress goes to stderr)
|
||||||
|
--dry-run plan the run without touching the machine
|
||||||
|
--verbose log every command that gets executed
|
||||||
|
--force act even when the app is already in the desired state
|
||||||
|
--strict fail instead of falling through to the next source
|
||||||
|
--provider winget restrict every app to a single provider
|
||||||
|
--catalog PATH load an extra catalog file or directory (repeatable)
|
||||||
|
--timeout 45m per-installer timeout (default 30m)
|
||||||
|
--require-checksum refuse vendor downloads with no sha256 pinned in the catalog
|
||||||
|
```
|
||||||
|
|
||||||
|
### Exit codes
|
||||||
|
|
||||||
|
| Code | Meaning |
|
||||||
|
| --- | --- |
|
||||||
|
| `0` | Everything ended in the requested state |
|
||||||
|
| `1` | At least one app failed |
|
||||||
|
| `2` | Usage or catalog error |
|
||||||
|
| `3` | Insufficient privileges — nothing was attempted |
|
||||||
|
|
||||||
|
## Deploying through an RMM
|
||||||
|
|
||||||
|
Deployr is designed to be the payload of a script policy. See
|
||||||
|
[docs/RMM.md](docs/RMM.md) for ready-made Level.io and NinjaOne snippets.
|
||||||
|
|
||||||
|
The short version:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# Windows script policy
|
||||||
|
& "C:\ProgramData\Deployr\deployr.exe" install @standard --json
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# macOS / Linux script policy
|
||||||
|
/usr/local/bin/deployr install @standard --json
|
||||||
|
```
|
||||||
|
|
||||||
|
Progress lines go to stderr and the JSON summary to stdout, so an RMM that
|
||||||
|
captures both gets a readable transcript *and* a parseable result:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"action": "install",
|
||||||
|
"host": "WS-014",
|
||||||
|
"os": "windows",
|
||||||
|
"arch": "amd64",
|
||||||
|
"total": 6,
|
||||||
|
"changed": 2,
|
||||||
|
"skipped": 4,
|
||||||
|
"failed": 0,
|
||||||
|
"reboot_required": false,
|
||||||
|
"results": [
|
||||||
|
{ "app": "chrome", "status": "skip", "version": "129.0.6668.90", "message": "already installed" },
|
||||||
|
{ "app": "vlc", "status": "ok", "provider": "winget", "version": "3.0.21" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## The catalog
|
||||||
|
|
||||||
|
The catalog is compiled into the binary, so a bare executable on a fresh machine
|
||||||
|
already knows how to install ~45 common applications. Every entry lists its
|
||||||
|
sources in preference order:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- id: chrome
|
||||||
|
name: Google Chrome
|
||||||
|
categories: [browser]
|
||||||
|
windows:
|
||||||
|
sources:
|
||||||
|
- provider: winget
|
||||||
|
id: Google.Chrome
|
||||||
|
- provider: choco
|
||||||
|
id: googlechrome
|
||||||
|
- provider: direct
|
||||||
|
url: https://dl.google.com/tag/s/dl/chrome/install/googlechromestandaloneenterprise64.msi
|
||||||
|
kind: msi
|
||||||
|
detect:
|
||||||
|
registry: ["Google Chrome"]
|
||||||
|
```
|
||||||
|
|
||||||
|
Add your own apps without rebuilding by dropping a YAML file in the overlay
|
||||||
|
directory (`C:\ProgramData\Deployr\catalog.d` or `/etc/deployr/catalog.d`), or by
|
||||||
|
passing `--catalog`. Overlays can also override a shipped entry — same `id`
|
||||||
|
replaces it wholesale.
|
||||||
|
|
||||||
|
Full format reference and worked examples: [docs/CATALOG.md](docs/CATALOG.md).
|
||||||
|
|
||||||
|
### Providers
|
||||||
|
|
||||||
|
| Provider | Platform | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `winget` | Windows | Resolved under SYSTEM; prefers machine scope, falls back to user scope |
|
||||||
|
| `choco` | Windows | Chocolatey 1.x and 2.x |
|
||||||
|
| `brew` | macOS, Linux | Formulae; drops from root to the Homebrew owner |
|
||||||
|
| `cask` | macOS | Casks; `--greedy` on upgrade so self-updating apps still get patched |
|
||||||
|
| `apt` | Linux | Refreshes the index once per run; `noninteractive` throughout |
|
||||||
|
| `dnf` | Linux | Also drives `dnf5` and `yum` |
|
||||||
|
| `zypper` | Linux | |
|
||||||
|
| `pacman` | Linux | |
|
||||||
|
| `flatpak` | Linux | System-wide as root, per-user otherwise |
|
||||||
|
| `snap` | Linux | |
|
||||||
|
| `direct` | all | Vendor download: msi, exe, msu, dmg, pkg, deb, rpm, zip, tar.gz, AppImage |
|
||||||
|
|
||||||
|
## Building
|
||||||
|
|
||||||
|
Requires Go 1.24 or newer. No cgo, no external build tools.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make build # host binary
|
||||||
|
make dist VERSION=0.1.0 # all six platforms into dist/
|
||||||
|
make check # vet on every platform + tests + gofmt
|
||||||
|
```
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\scripts\build.ps1 -Version 0.1.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Output is one static binary per platform (~7 MB), with SHA256SUMS alongside.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
```
|
||||||
|
cmd/deployr entry point
|
||||||
|
internal/catalog catalog types, embedded data, overlay merging
|
||||||
|
internal/provider winget, choco, brew/cask, apt, dnf, zypper, pacman, flatpak, snap, direct
|
||||||
|
internal/engine decides what needs doing and walks the source list
|
||||||
|
internal/detect is it already installed (registry, paths, commands)
|
||||||
|
internal/download vendor downloads with retries and checksum pinning
|
||||||
|
internal/platform OS, arch, elevation, well-known directories
|
||||||
|
internal/run non-interactive command execution with timeouts
|
||||||
|
internal/cli command line parsing and output rendering
|
||||||
|
```
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Working: catalog, all providers, install/update/uninstall/status/list/info/
|
||||||
|
doctor, JSON output, overlays, RMM exit codes.
|
||||||
|
|
||||||
|
Not built yet: a central dashboard (deliberately — this is the standalone CLI),
|
||||||
|
scheduled self-updates, and per-app version pinning.
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// Command deployr installs, updates and removes applications on Windows, macOS
|
||||||
|
// and Linux from a single catalog, preferring the machine's native package
|
||||||
|
// manager and falling back to the vendor's own installer.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
os.Exit(cli.Main(os.Args[1:]))
|
||||||
|
}
|
||||||
+162
@@ -0,0 +1,162 @@
|
|||||||
|
# Catalog format
|
||||||
|
|
||||||
|
The catalog says what deployr can install and how. One copy is compiled into the
|
||||||
|
binary (`internal/catalog/data/apps.yaml`); overlays let you add or override
|
||||||
|
entries on a machine without rebuilding.
|
||||||
|
|
||||||
|
## Where overlays are loaded from
|
||||||
|
|
||||||
|
In increasing order of precedence:
|
||||||
|
|
||||||
|
1. `C:\ProgramData\Deployr\catalog.d\*.yaml` (Windows)
|
||||||
|
`/var/lib/deployr/catalog.d/*.yaml` and `/etc/deployr/catalog.d/*.yaml` (Unix)
|
||||||
|
2. The per-user cache directory's `catalog.d` (used automatically when the
|
||||||
|
machine-wide path is not writable)
|
||||||
|
3. Anything passed with `--catalog FILE_OR_DIR` (repeatable)
|
||||||
|
|
||||||
|
An overlay app whose `id` matches a shipped app **replaces it entirely** — no
|
||||||
|
deep merge — so what you read in the file is exactly what will run. Profiles are
|
||||||
|
replaced by name the same way.
|
||||||
|
|
||||||
|
Check an overlay before you ship it:
|
||||||
|
|
||||||
|
```
|
||||||
|
deployr catalog validate ./my-apps.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Document shape
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
apps:
|
||||||
|
- id: my-app # required, unique, lowercase
|
||||||
|
name: My Application # required, human name
|
||||||
|
description: ...
|
||||||
|
homepage: https://...
|
||||||
|
categories: [line-of-business]
|
||||||
|
aliases: [myapp] # alternative names accepted on the command line
|
||||||
|
|
||||||
|
windows: # one or more of windows / darwin / linux
|
||||||
|
sources: [...] # required, tried in order
|
||||||
|
detect: {...} # how to tell it is already installed
|
||||||
|
notes: ... # shown by `deployr info`
|
||||||
|
|
||||||
|
profiles:
|
||||||
|
onboarding: [my-app, chrome, 7zip]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Sources
|
||||||
|
|
||||||
|
Sources are tried top to bottom. The first provider that **exists on the
|
||||||
|
machine** is used; if it fails, deployr moves to the next one (unless
|
||||||
|
`--strict`). Put the route you trust most first.
|
||||||
|
|
||||||
|
### Package manager sources
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
sources:
|
||||||
|
- provider: winget # winget|choco|brew|cask|apt|dnf|zypper|pacman|flatpak|snap
|
||||||
|
id: Google.Chrome # the provider's own package identifier
|
||||||
|
args: ["--locale", "en-US"] # optional extra arguments
|
||||||
|
arch: [amd64] # optional: restrict to these GOARCH values
|
||||||
|
repo: flathub # optional: flatpak remote
|
||||||
|
```
|
||||||
|
|
||||||
|
### Direct vendor downloads
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
sources:
|
||||||
|
- provider: direct
|
||||||
|
url: https://vendor.example/app-setup.msi
|
||||||
|
urls: # or per-architecture, overriding url
|
||||||
|
amd64: https://vendor.example/app-x64.msi
|
||||||
|
arm64: https://vendor.example/app-arm64.msi
|
||||||
|
kind: msi # msi|exe|msu|dmg|pkg|deb|rpm|zip|tar.gz|appimage
|
||||||
|
# inferred from the URL when omitted
|
||||||
|
silent_args: ["/S"] # REQUIRED for kind: exe
|
||||||
|
sha256: 9f2c... # optional; enforced when set, required by --require-checksum
|
||||||
|
app_name: MyApp.app # dmg/zip on macOS: the bundle to copy to /Applications
|
||||||
|
dest: "%ProgramFiles%/MyApp" # zip/tar.gz: extraction target
|
||||||
|
uninstall_id: my-app # Linux: package name to remove; Windows: registry DisplayName
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes that matter in practice:
|
||||||
|
|
||||||
|
- **`kind: exe` without `silent_args` is rejected.** A bare vendor `.exe` opens a
|
||||||
|
wizard on someone's screen and then hangs until the timeout — refusing is the
|
||||||
|
correct behaviour, not a limitation.
|
||||||
|
- **Evergreen URLs cannot be checksum-pinned.** A vendor "latest" link changes
|
||||||
|
content on every release. Pin `sha256` only for versioned URLs, and use
|
||||||
|
`--require-checksum` on sites where an unpinned download is unacceptable.
|
||||||
|
- **`.dmg` handling**: a `.pkg` inside the image wins; otherwise the `.app` named
|
||||||
|
by `app_name` (or the only one present) is copied to `/Applications` with
|
||||||
|
`ditto`, replacing any existing bundle.
|
||||||
|
- **`.deb` installs go through `apt-get install ./file`**, so dependencies
|
||||||
|
resolve instead of leaving a half-configured dpkg state.
|
||||||
|
|
||||||
|
## Detection
|
||||||
|
|
||||||
|
Detection is how deployr decides an app is *already installed*, no matter who
|
||||||
|
installed it. It runs before any provider is touched, which is why
|
||||||
|
`deployr install chrome` is fast and idempotent on a machine that already has
|
||||||
|
Chrome from an image.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
detect:
|
||||||
|
registry: ["Google Chrome"] # Windows uninstall entries, case-insensitive substring
|
||||||
|
paths: # files or directories; env vars and globs allowed
|
||||||
|
- "%ProgramFiles%/Google/Chrome/Application/chrome.exe"
|
||||||
|
- "/Applications/Google Chrome.app"
|
||||||
|
commands: [google-chrome-stable] # executables that must resolve on PATH
|
||||||
|
```
|
||||||
|
|
||||||
|
Evaluation order is registry, then paths, then commands — first hit wins. The
|
||||||
|
registry scan covers 64-bit, 32-bit and per-user uninstall keys; missing one of
|
||||||
|
those is the classic reason a "not installed" check is wrong.
|
||||||
|
|
||||||
|
Version reporting comes from, in order: the provider's own query, the registry's
|
||||||
|
`DisplayVersion`, or a macOS bundle's `CFBundleShortVersionString`. An app with
|
||||||
|
no version available still reports correctly as installed.
|
||||||
|
|
||||||
|
If `detect` is omitted entirely, deployr cannot skip work it does not need to
|
||||||
|
do, and `update` / `uninstall` will always run the provider. Always write one.
|
||||||
|
|
||||||
|
## A complete overlay example
|
||||||
|
|
||||||
|
`C:\ProgramData\Deployr\catalog.d\atomit.yaml`
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
apps:
|
||||||
|
- id: linemgr
|
||||||
|
name: LineManager Client
|
||||||
|
description: Line-of-business client for the accounting team
|
||||||
|
categories: [line-of-business]
|
||||||
|
windows:
|
||||||
|
sources:
|
||||||
|
- provider: direct
|
||||||
|
url: https://files.example.com/linemgr/LineManagerSetup-4.8.2.msi
|
||||||
|
kind: msi
|
||||||
|
sha256: 5f0d9a3c1e...
|
||||||
|
silent_args: ["SERVER=lm01.corp.example.com"]
|
||||||
|
detect:
|
||||||
|
registry: ["LineManager Client"]
|
||||||
|
|
||||||
|
# Override a shipped app: force Chrome through Chocolatey only.
|
||||||
|
- id: chrome
|
||||||
|
name: Google Chrome
|
||||||
|
categories: [browser]
|
||||||
|
windows:
|
||||||
|
sources:
|
||||||
|
- provider: choco
|
||||||
|
id: googlechrome
|
||||||
|
detect:
|
||||||
|
registry: ["Google Chrome"]
|
||||||
|
|
||||||
|
profiles:
|
||||||
|
accounting: [linemgr, chrome, adobereader, 7zip]
|
||||||
|
```
|
||||||
|
|
||||||
|
Then:
|
||||||
|
|
||||||
|
```
|
||||||
|
deployr install @accounting --json
|
||||||
|
```
|
||||||
+187
@@ -0,0 +1,187 @@
|
|||||||
|
# Running deployr from an RMM
|
||||||
|
|
||||||
|
Deployr is a single binary with meaningful exit codes, so any script runner can
|
||||||
|
drive it. The pattern is always the same: make sure the binary is on the
|
||||||
|
machine, run it, return its exit code.
|
||||||
|
|
||||||
|
| Code | Meaning | Suggested RMM handling |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `0` | Everything is in the requested state | Success |
|
||||||
|
| `1` | At least one app failed | Alert, read the JSON `results` |
|
||||||
|
| `2` | Usage or catalog error | Alert — the script or overlay is wrong |
|
||||||
|
| `3` | Insufficient privileges | Fix the policy's run-as context |
|
||||||
|
|
||||||
|
Progress goes to **stderr**, the `--json` summary to **stdout**. An RMM that
|
||||||
|
captures both gets a readable transcript and a parseable result from one run.
|
||||||
|
|
||||||
|
## Getting the binary onto the machine
|
||||||
|
|
||||||
|
Deployr has no self-update, on purpose: the RMM already does software
|
||||||
|
distribution, and one authority beating another is how endpoints drift. Ship it
|
||||||
|
the way you ship any other tool.
|
||||||
|
|
||||||
|
### Windows
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$dir = "C:\ProgramData\Deployr"
|
||||||
|
$exe = "$dir\deployr.exe"
|
||||||
|
$src = "https://files.example.com/deployr/deployr_windows_amd64.exe"
|
||||||
|
$expected = "PUT_THE_SHA256_HERE"
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
||||||
|
|
||||||
|
$need = $true
|
||||||
|
if (Test-Path $exe) {
|
||||||
|
$need = (Get-FileHash $exe -Algorithm SHA256).Hash -ne $expected
|
||||||
|
}
|
||||||
|
if ($need) {
|
||||||
|
Invoke-WebRequest -Uri $src -OutFile "$exe.new" -UseBasicParsing
|
||||||
|
if ((Get-FileHash "$exe.new" -Algorithm SHA256).Hash -ne $expected) {
|
||||||
|
Remove-Item "$exe.new"; throw "deployr checksum mismatch"
|
||||||
|
}
|
||||||
|
Move-Item "$exe.new" $exe -Force
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### macOS / Linux
|
||||||
|
|
||||||
|
```sh
|
||||||
|
BIN=/usr/local/bin/deployr
|
||||||
|
SRC=https://files.example.com/deployr/deployr_linux_amd64
|
||||||
|
EXPECTED=PUT_THE_SHA256_HERE
|
||||||
|
|
||||||
|
if [ ! -x "$BIN" ] || [ "$(shasum -a 256 "$BIN" | cut -d' ' -f1)" != "$EXPECTED" ]; then
|
||||||
|
curl -fsSL "$SRC" -o /tmp/deployr.new
|
||||||
|
echo "$EXPECTED /tmp/deployr.new" | shasum -a 256 -c - || exit 1
|
||||||
|
install -m 0755 /tmp/deployr.new "$BIN"
|
||||||
|
rm -f /tmp/deployr.new
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
|
||||||
|
## Level.io
|
||||||
|
|
||||||
|
Level runs scripts as SYSTEM on Windows and root on macOS/Linux, which is what
|
||||||
|
deployr wants. Create one script per intent and attach it to a policy.
|
||||||
|
|
||||||
|
**Windows — install the standard bundle**
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$exe = "C:\ProgramData\Deployr\deployr.exe"
|
||||||
|
& $exe install @standard --json
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
```
|
||||||
|
|
||||||
|
**macOS / Linux — patch everything present, weekly**
|
||||||
|
|
||||||
|
```sh
|
||||||
|
#!/bin/sh
|
||||||
|
/usr/local/bin/deployr update --all --json
|
||||||
|
```
|
||||||
|
|
||||||
|
Level surfaces a non-zero exit as a failed script run, so no extra wiring is
|
||||||
|
needed for alerting.
|
||||||
|
|
||||||
|
## NinjaOne
|
||||||
|
|
||||||
|
Ninja's script results branch on exit code the same way. Add deployr as a script
|
||||||
|
with **Run As: System**, then either:
|
||||||
|
|
||||||
|
- **Scheduled patching** — `deployr update --all --json` on a weekly policy.
|
||||||
|
- **Onboarding** — `deployr install @standard --json` as a task on new devices.
|
||||||
|
- **On-demand** — take the app list as a script parameter:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
param([string]$Apps = "@standard")
|
||||||
|
$exe = "C:\ProgramData\Deployr\deployr.exe"
|
||||||
|
& $exe install @($Apps -split '\s+') --json
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
```
|
||||||
|
|
||||||
|
## Site-specific app lists
|
||||||
|
|
||||||
|
Rather than editing scripts per client, ship a catalog overlay with the binary
|
||||||
|
and reference profiles by name:
|
||||||
|
|
||||||
|
```
|
||||||
|
C:\ProgramData\Deployr\catalog.d\client.yaml -> profiles: { standard: [...] }
|
||||||
|
```
|
||||||
|
|
||||||
|
The script stays `deployr install @standard` everywhere, and what `@standard`
|
||||||
|
means is a per-site file your RMM already knows how to distribute. See
|
||||||
|
[CATALOG.md](CATALOG.md).
|
||||||
|
|
||||||
|
## Scheduling without an RMM
|
||||||
|
|
||||||
|
**Windows — weekly patch run at 03:00**
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$action = New-ScheduledTaskAction -Execute "C:\ProgramData\Deployr\deployr.exe" -Argument "update --all"
|
||||||
|
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 3am
|
||||||
|
Register-ScheduledTask -TaskName "Deployr patching" -Action $action -Trigger $trigger `
|
||||||
|
-User "SYSTEM" -RunLevel Highest
|
||||||
|
```
|
||||||
|
|
||||||
|
**Linux — systemd timer**
|
||||||
|
|
||||||
|
```ini
|
||||||
|
# /etc/systemd/system/deployr.service
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=/usr/local/bin/deployr update --all
|
||||||
|
|
||||||
|
# /etc/systemd/system/deployr.timer
|
||||||
|
[Timer]
|
||||||
|
OnCalendar=Sun 03:00
|
||||||
|
Persistent=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
|
```
|
||||||
|
|
||||||
|
**macOS — a LaunchDaemon** running the same `update --all` on a
|
||||||
|
`StartCalendarInterval` works identically. Keep it a daemon, not an agent:
|
||||||
|
deployr needs root, and it drops to the console user itself when Homebrew is
|
||||||
|
involved.
|
||||||
|
|
||||||
|
## Reading the results
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"action": "update",
|
||||||
|
"host": "WS-014",
|
||||||
|
"os": "windows",
|
||||||
|
"total": 12,
|
||||||
|
"changed": 3,
|
||||||
|
"skipped": 9,
|
||||||
|
"failed": 0,
|
||||||
|
"reboot_required": true,
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"app": "vlc",
|
||||||
|
"status": "ok",
|
||||||
|
"provider": "winget",
|
||||||
|
"version": "3.0.21",
|
||||||
|
"duration_ms": 18422
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"app": "linemgr",
|
||||||
|
"status": "fail",
|
||||||
|
"error": "winget: not available on this machine; direct: HTTP 404",
|
||||||
|
"attempts": [
|
||||||
|
{ "provider": "winget", "error": "not available on this machine" },
|
||||||
|
{ "provider": "direct", "error": "HTTP 404" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`attempts` is the useful field when something fails: it lists every route that
|
||||||
|
was tried and why each one did not work, which is usually enough to fix the
|
||||||
|
catalog entry without logging into the machine.
|
||||||
|
|
||||||
|
Every run also appends to a log file:
|
||||||
|
|
||||||
|
- Windows: `C:\ProgramData\Deployr\logs\deployr.log`
|
||||||
|
- macOS: `/Library/Logs/Deployr/deployr.log`
|
||||||
|
- Linux: `/var/log/deployr/deployr.log`
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
module git.starwarslab.us/ATOM_IT/Deployr
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
golang.org/x/sys v0.47.0
|
||||||
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
|
)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||||
|
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestEmbeddedCatalogLoads(t *testing.T) {
|
||||||
|
cat, err := Embedded()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("embedded catalog does not parse: %v", err)
|
||||||
|
}
|
||||||
|
if len(cat.Apps) == 0 {
|
||||||
|
t.Fatal("embedded catalog is empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEveryTargetHasDetection guards the property the engine relies on to be
|
||||||
|
// idempotent: without detect rules it cannot tell an app is already installed.
|
||||||
|
func TestEveryTargetHasDetection(t *testing.T) {
|
||||||
|
cat, err := Embedded()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, app := range cat.Apps {
|
||||||
|
for _, goos := range app.Platforms() {
|
||||||
|
if app.TargetFor(goos).Detect.Empty() {
|
||||||
|
t.Errorf("%s/%s has no detect rules", app.ID, goos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProfilesReferenceRealApps(t *testing.T) {
|
||||||
|
cat, err := Embedded()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for name, members := range cat.Profiles {
|
||||||
|
if len(members) == 0 {
|
||||||
|
t.Errorf("profile %q is empty", name)
|
||||||
|
}
|
||||||
|
for _, id := range members {
|
||||||
|
if _, ok := cat.Get(id); !ok {
|
||||||
|
t.Errorf("profile %q references unknown app %q", name, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveExpandsProfilesAndDeduplicates(t *testing.T) {
|
||||||
|
cat, err := Embedded()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
apps, unknown := cat.Resolve([]string{"@standard", "chrome", "chrome"})
|
||||||
|
if len(unknown) != 0 {
|
||||||
|
t.Fatalf("unexpected unknown names: %v", unknown)
|
||||||
|
}
|
||||||
|
|
||||||
|
seen := map[string]int{}
|
||||||
|
for _, a := range apps {
|
||||||
|
seen[a.ID]++
|
||||||
|
}
|
||||||
|
if seen["chrome"] != 1 {
|
||||||
|
t.Errorf("chrome resolved %d times, want 1", seen["chrome"])
|
||||||
|
}
|
||||||
|
if len(apps) < len(cat.Profiles["standard"]) {
|
||||||
|
t.Errorf("resolved %d apps, expected at least the %d in @standard", len(apps), len(cat.Profiles["standard"]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveReportsUnknownNames(t *testing.T) {
|
||||||
|
cat, err := Embedded()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, unknown := cat.Resolve([]string{"chrome", "definitely-not-an-app", "@nope"})
|
||||||
|
if len(unknown) != 2 {
|
||||||
|
t.Fatalf("got unknown=%v, want 2 entries", unknown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAliasesResolve(t *testing.T) {
|
||||||
|
cat, err := Embedded()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app, ok := cat.Get("notepad++")
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("alias notepad++ did not resolve")
|
||||||
|
}
|
||||||
|
if app.ID != "notepadplusplus" {
|
||||||
|
t.Errorf("alias resolved to %q", app.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOverlayReplacesAppAndAddsProfile(t *testing.T) {
|
||||||
|
base, err := Embedded()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
overlay, err := Parse([]byte(`
|
||||||
|
apps:
|
||||||
|
- id: chrome
|
||||||
|
name: Google Chrome
|
||||||
|
windows:
|
||||||
|
sources:
|
||||||
|
- provider: choco
|
||||||
|
id: googlechrome
|
||||||
|
detect:
|
||||||
|
registry: ["Google Chrome"]
|
||||||
|
profiles:
|
||||||
|
onboarding: [chrome]
|
||||||
|
`), "test overlay")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
base.merge(overlay)
|
||||||
|
base.reindex()
|
||||||
|
|
||||||
|
app, ok := base.Get("chrome")
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("chrome missing after merge")
|
||||||
|
}
|
||||||
|
sources := app.Windows.Sources
|
||||||
|
if len(sources) != 1 || sources[0].Provider != "choco" {
|
||||||
|
t.Errorf("overlay did not replace the shipped entry: %+v", sources)
|
||||||
|
}
|
||||||
|
if app.Darwin != nil {
|
||||||
|
t.Error("overlay replace should be wholesale, not a deep merge")
|
||||||
|
}
|
||||||
|
if _, ok := base.Profiles["onboarding"]; !ok {
|
||||||
|
t.Error("overlay profile was not added")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateRejectsBadEntries(t *testing.T) {
|
||||||
|
cases := map[string]string{
|
||||||
|
"missing id": "apps:\n - name: No ID\n windows:\n sources:\n - provider: winget\n id: X\n",
|
||||||
|
"no platforms": "apps:\n - id: x\n name: X\n",
|
||||||
|
"no sources": "apps:\n - id: x\n name: X\n windows:\n sources: []\n",
|
||||||
|
"direct wthout url": "apps:\n - id: x\n name: X\n windows:\n sources:\n - provider: direct\n kind: msi\n",
|
||||||
|
"provider no id": "apps:\n - id: x\n name: X\n windows:\n sources:\n - provider: winget\n",
|
||||||
|
}
|
||||||
|
for name, doc := range cases {
|
||||||
|
if _, err := Parse([]byte(doc), "test"); err == nil {
|
||||||
|
t.Errorf("%s: expected a validation error", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseRejectsUnknownFields(t *testing.T) {
|
||||||
|
// A typo in a catalog key must fail loudly rather than be ignored.
|
||||||
|
_, err := Parse([]byte("apps:\n - id: x\n name: X\n windowz:\n sources: []\n"), "test")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected an error for an unknown field")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSourceURLForArch(t *testing.T) {
|
||||||
|
src := Source{
|
||||||
|
URL: "https://example.test/default.msi",
|
||||||
|
URLs: map[string]string{"arm64": "https://example.test/arm.msi"},
|
||||||
|
}
|
||||||
|
if got := src.URLFor("arm64"); got != "https://example.test/arm.msi" {
|
||||||
|
t.Errorf("arm64 URL = %q", got)
|
||||||
|
}
|
||||||
|
if got := src.URLFor("amd64"); got != "https://example.test/default.msi" {
|
||||||
|
t.Errorf("amd64 fallback URL = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSourceSupportsArch(t *testing.T) {
|
||||||
|
unrestricted := Source{}
|
||||||
|
if !unrestricted.SupportsArch("riscv64") {
|
||||||
|
t.Error("a source with no arch list should support every arch")
|
||||||
|
}
|
||||||
|
restricted := Source{Arch: []string{"amd64"}}
|
||||||
|
if restricted.SupportsArch("arm64") {
|
||||||
|
t.Error("arm64 should not match an amd64-only source")
|
||||||
|
}
|
||||||
|
if !restricted.SupportsArch("amd64") {
|
||||||
|
t.Error("amd64 should match an amd64-only source")
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,245 @@
|
|||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "embed"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed data/apps.yaml
|
||||||
|
var embeddedYAML []byte
|
||||||
|
|
||||||
|
// Parse reads a catalog document.
|
||||||
|
func Parse(data []byte, origin string) (*Catalog, error) {
|
||||||
|
var c Catalog
|
||||||
|
dec := yaml.NewDecoder(strings.NewReader(string(data)))
|
||||||
|
dec.KnownFields(true)
|
||||||
|
if err := dec.Decode(&c); err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", origin, err)
|
||||||
|
}
|
||||||
|
if err := c.validate(origin); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Embedded returns the catalog compiled into the binary.
|
||||||
|
func Embedded() (*Catalog, error) {
|
||||||
|
c, err := Parse(embeddedYAML, "embedded catalog")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c.reindex()
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load returns the embedded catalog with overlays merged over it. Overlays are
|
||||||
|
// read from the well-known catalog.d directories and then from extra (files or
|
||||||
|
// directories), so an operator can add or override apps without rebuilding.
|
||||||
|
func Load(extra []string) (*Catalog, error) {
|
||||||
|
base, err := Embedded()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var files []string
|
||||||
|
for _, dir := range platform.CatalogDirs() {
|
||||||
|
files = append(files, yamlFilesIn(dir)...)
|
||||||
|
}
|
||||||
|
for _, p := range extra {
|
||||||
|
p = platform.ExpandPath(p)
|
||||||
|
info, err := os.Stat(p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("catalog %q: %w", p, err)
|
||||||
|
}
|
||||||
|
if info.IsDir() {
|
||||||
|
files = append(files, yamlFilesIn(p)...)
|
||||||
|
} else {
|
||||||
|
files = append(files, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, f := range files {
|
||||||
|
data, err := os.ReadFile(f)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("catalog %q: %w", f, err)
|
||||||
|
}
|
||||||
|
overlay, err := Parse(data, f)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
base.merge(overlay)
|
||||||
|
}
|
||||||
|
|
||||||
|
base.reindex()
|
||||||
|
return base, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func yamlFilesIn(dir string) []string {
|
||||||
|
var out []string
|
||||||
|
for _, pattern := range []string{"*.yaml", "*.yml"} {
|
||||||
|
matches, err := filepath.Glob(filepath.Join(dir, pattern))
|
||||||
|
if err == nil {
|
||||||
|
out = append(out, matches...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// merge applies an overlay: apps are replaced whole by ID, profiles by name.
|
||||||
|
// Replacing rather than deep-merging keeps overrides predictable — what you
|
||||||
|
// read in the overlay file is exactly what will run.
|
||||||
|
func (c *Catalog) merge(overlay *Catalog) {
|
||||||
|
for _, app := range overlay.Apps {
|
||||||
|
replaced := false
|
||||||
|
for i, existing := range c.Apps {
|
||||||
|
if strings.EqualFold(existing.ID, app.ID) {
|
||||||
|
c.Apps[i] = app
|
||||||
|
replaced = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !replaced {
|
||||||
|
c.Apps = append(c.Apps, app)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(overlay.Profiles) > 0 && c.Profiles == nil {
|
||||||
|
c.Profiles = map[string][]string{}
|
||||||
|
}
|
||||||
|
for name, apps := range overlay.Profiles {
|
||||||
|
c.Profiles[name] = apps
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Catalog) validate(origin string) error {
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, app := range c.Apps {
|
||||||
|
switch {
|
||||||
|
case app.ID == "":
|
||||||
|
return fmt.Errorf("%s: an app entry is missing an id", origin)
|
||||||
|
case seen[strings.ToLower(app.ID)]:
|
||||||
|
return fmt.Errorf("%s: duplicate app id %q", origin, app.ID)
|
||||||
|
case app.Name == "":
|
||||||
|
return fmt.Errorf("%s: app %q is missing a name", origin, app.ID)
|
||||||
|
case len(app.Platforms()) == 0:
|
||||||
|
return fmt.Errorf("%s: app %q defines no platform targets", origin, app.ID)
|
||||||
|
}
|
||||||
|
seen[strings.ToLower(app.ID)] = true
|
||||||
|
|
||||||
|
for _, goos := range app.Platforms() {
|
||||||
|
t := app.TargetFor(goos)
|
||||||
|
if len(t.Sources) == 0 {
|
||||||
|
return fmt.Errorf("%s: app %q has no %s sources", origin, app.ID, goos)
|
||||||
|
}
|
||||||
|
for i, s := range t.Sources {
|
||||||
|
if s.Provider == "" {
|
||||||
|
return fmt.Errorf("%s: app %q %s source %d has no provider", origin, app.ID, goos, i+1)
|
||||||
|
}
|
||||||
|
if s.Provider == "direct" && s.URL == "" && len(s.URLs) == 0 {
|
||||||
|
return fmt.Errorf("%s: app %q %s direct source has no url", origin, app.ID, goos)
|
||||||
|
}
|
||||||
|
if s.Provider != "direct" && s.ID == "" {
|
||||||
|
return fmt.Errorf("%s: app %q %s %s source has no id", origin, app.ID, goos, s.Provider)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Catalog) reindex() {
|
||||||
|
c.index = make(map[string]*App, len(c.Apps)*2)
|
||||||
|
for _, app := range c.Apps {
|
||||||
|
c.index[strings.ToLower(app.ID)] = app
|
||||||
|
for _, alias := range app.Aliases {
|
||||||
|
c.index[strings.ToLower(alias)] = app
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(c.Apps, func(i, j int) bool {
|
||||||
|
return strings.ToLower(c.Apps[i].ID) < strings.ToLower(c.Apps[j].ID)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get looks up an app by ID or alias.
|
||||||
|
func (c *Catalog) Get(name string) (*App, bool) {
|
||||||
|
app, ok := c.index[strings.ToLower(strings.TrimSpace(name))]
|
||||||
|
return app, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve expands a list of command-line names into apps. A name prefixed with
|
||||||
|
// "@" refers to a profile. Unknown names are returned separately so the caller
|
||||||
|
// can report all of them at once rather than dying on the first.
|
||||||
|
func (c *Catalog) Resolve(names []string) (apps []*App, unknown []string) {
|
||||||
|
seen := map[string]bool{}
|
||||||
|
add := func(app *App) {
|
||||||
|
if !seen[app.ID] {
|
||||||
|
seen[app.ID] = true
|
||||||
|
apps = append(apps, app)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, raw := range names {
|
||||||
|
name := strings.TrimSpace(raw)
|
||||||
|
if name == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(name, "@") {
|
||||||
|
members, ok := c.Profiles[strings.TrimPrefix(name, "@")]
|
||||||
|
if !ok {
|
||||||
|
unknown = append(unknown, name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, m := range members {
|
||||||
|
if app, ok := c.Get(m); ok {
|
||||||
|
add(app)
|
||||||
|
} else {
|
||||||
|
unknown = append(unknown, m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if app, ok := c.Get(name); ok {
|
||||||
|
add(app)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
unknown = append(unknown, name)
|
||||||
|
}
|
||||||
|
return apps, unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
// ForPlatform returns every app installable on the given GOOS.
|
||||||
|
func (c *Catalog) ForPlatform(goos string) []*App {
|
||||||
|
var out []*App
|
||||||
|
for _, app := range c.Apps {
|
||||||
|
if app.TargetFor(goos) != nil {
|
||||||
|
out = append(out, app)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Suggest returns catalog IDs similar to name, for "did you mean" output.
|
||||||
|
func (c *Catalog) Suggest(name string) []string {
|
||||||
|
name = strings.ToLower(strings.TrimPrefix(name, "@"))
|
||||||
|
var out []string
|
||||||
|
for _, app := range c.Apps {
|
||||||
|
id := strings.ToLower(app.ID)
|
||||||
|
if strings.Contains(id, name) || strings.Contains(name, id) ||
|
||||||
|
strings.Contains(strings.ToLower(app.Name), name) {
|
||||||
|
out = append(out, app.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
if len(out) > 5 {
|
||||||
|
out = out[:5]
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
// This test needs internal/provider, which imports internal/catalog, so it
|
||||||
|
// lives in the external test package to avoid an import cycle.
|
||||||
|
package catalog_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSourcesUseKnownProviders catches a typo in a catalog source before it
|
||||||
|
// turns into a runtime "unknown provider" on someone's endpoint.
|
||||||
|
func TestSourcesUseKnownProviders(t *testing.T) {
|
||||||
|
cat, err := catalog.Embedded()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, app := range cat.Apps {
|
||||||
|
for _, goos := range app.Platforms() {
|
||||||
|
for _, src := range app.TargetFor(goos).Sources {
|
||||||
|
p, ok := provider.Get(src.Provider)
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("%s/%s: unknown provider %q", app.ID, goos, src.Provider)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
supported := false
|
||||||
|
for _, os := range p.OSes() {
|
||||||
|
if os == goos {
|
||||||
|
supported = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !supported {
|
||||||
|
t.Errorf("%s: provider %q cannot run on %s", app.ID, src.Provider, goos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDirectSourcesAreInstallable checks the two rules the direct provider
|
||||||
|
// enforces at runtime: an exe needs silent switches, and a zip needs somewhere
|
||||||
|
// to go. Catching these here beats catching them on an endpoint.
|
||||||
|
func TestDirectSourcesAreInstallable(t *testing.T) {
|
||||||
|
cat, err := catalog.Embedded()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, app := range cat.Apps {
|
||||||
|
for _, goos := range app.Platforms() {
|
||||||
|
for _, src := range app.TargetFor(goos).Sources {
|
||||||
|
if src.Provider != "direct" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
kind := src.Kind
|
||||||
|
if kind == "" {
|
||||||
|
kind = provider.InferKind(src.URLFor("amd64"))
|
||||||
|
}
|
||||||
|
switch kind {
|
||||||
|
case "":
|
||||||
|
t.Errorf("%s/%s: cannot infer installer kind from %q; set kind", app.ID, goos, src.URL)
|
||||||
|
case "exe":
|
||||||
|
if len(src.SilentArgs) == 0 {
|
||||||
|
t.Errorf("%s/%s: exe source has no silent_args", app.ID, goos)
|
||||||
|
}
|
||||||
|
case "zip":
|
||||||
|
if src.Dest == "" && goos != "darwin" {
|
||||||
|
t.Errorf("%s/%s: zip source has no dest", app.ID, goos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
// Package catalog defines the application catalog: what deployr knows how to
|
||||||
|
// install, and by which route on each operating system.
|
||||||
|
package catalog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Catalog is a merged view of the embedded catalog plus any overlays.
|
||||||
|
type Catalog struct {
|
||||||
|
Apps []*App `yaml:"apps"`
|
||||||
|
Profiles map[string][]string `yaml:"profiles,omitempty"`
|
||||||
|
|
||||||
|
index map[string]*App
|
||||||
|
}
|
||||||
|
|
||||||
|
// App is one installable product.
|
||||||
|
type App struct {
|
||||||
|
ID string `yaml:"id"`
|
||||||
|
Name string `yaml:"name"`
|
||||||
|
Description string `yaml:"description,omitempty"`
|
||||||
|
Homepage string `yaml:"homepage,omitempty"`
|
||||||
|
Categories []string `yaml:"categories,omitempty"`
|
||||||
|
// Aliases are alternative names accepted on the command line.
|
||||||
|
Aliases []string `yaml:"aliases,omitempty"`
|
||||||
|
|
||||||
|
Windows *Target `yaml:"windows,omitempty"`
|
||||||
|
Darwin *Target `yaml:"darwin,omitempty"`
|
||||||
|
Linux *Target `yaml:"linux,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Target is the per-OS install recipe.
|
||||||
|
type Target struct {
|
||||||
|
// Sources are tried in order; the first one whose provider is present on
|
||||||
|
// the machine wins, and a failure falls through to the next unless the
|
||||||
|
// caller asked for strict mode.
|
||||||
|
Sources []Source `yaml:"sources"`
|
||||||
|
// Detect is how we decide the app is already present, independent of
|
||||||
|
// which route installed it.
|
||||||
|
Detect Detect `yaml:"detect,omitempty"`
|
||||||
|
// Notes surface caveats to the operator (licensing, reboot, etc).
|
||||||
|
Notes string `yaml:"notes,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Source is a single install route.
|
||||||
|
type Source struct {
|
||||||
|
// Provider is winget, choco, brew, cask, apt, dnf, pacman, zypper,
|
||||||
|
// flatpak, snap or direct.
|
||||||
|
Provider string `yaml:"provider"`
|
||||||
|
// ID is the package identifier for the provider.
|
||||||
|
ID string `yaml:"id,omitempty"`
|
||||||
|
// Args are extra arguments appended to the install command.
|
||||||
|
Args []string `yaml:"args,omitempty"`
|
||||||
|
// Arch restricts this source to specific GOARCH values.
|
||||||
|
Arch []string `yaml:"arch,omitempty"`
|
||||||
|
// Repo is an optional remote name (flatpak) or tap (brew).
|
||||||
|
Repo string `yaml:"repo,omitempty"`
|
||||||
|
|
||||||
|
// The fields below apply to the "direct" provider: a vendor download.
|
||||||
|
URL string `yaml:"url,omitempty"`
|
||||||
|
// URLs maps GOARCH to a download URL when the vendor ships per-arch builds.
|
||||||
|
URLs map[string]string `yaml:"urls,omitempty"`
|
||||||
|
// Kind is msi, exe, msu, dmg, pkg, deb, rpm or zip. Inferred from the URL
|
||||||
|
// when empty.
|
||||||
|
Kind string `yaml:"kind,omitempty"`
|
||||||
|
// SilentArgs are the vendor's unattended-install switches (exe installers).
|
||||||
|
SilentArgs []string `yaml:"silent_args,omitempty"`
|
||||||
|
// SHA256 pins the download. Evergreen "latest" URLs cannot be pinned, so
|
||||||
|
// this is optional unless --require-checksum is passed.
|
||||||
|
SHA256 string `yaml:"sha256,omitempty"`
|
||||||
|
// AppName is the bundle to copy out of a dmg/zip, e.g. "Firefox.app".
|
||||||
|
AppName string `yaml:"app_name,omitempty"`
|
||||||
|
// Dest is the extraction target for zip payloads.
|
||||||
|
Dest string `yaml:"dest,omitempty"`
|
||||||
|
// UninstallID lets uninstall fall back to a different identifier, e.g. the
|
||||||
|
// registry DisplayName for something installed from a vendor MSI.
|
||||||
|
UninstallID string `yaml:"uninstall_id,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// URLFor returns the download URL for a GOARCH.
|
||||||
|
func (s Source) URLFor(arch string) string {
|
||||||
|
if u, ok := s.URLs[arch]; ok && u != "" {
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
if u, ok := s.URLs["default"]; ok && u != "" {
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
return s.URL
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportsArch reports whether this source applies to the given GOARCH.
|
||||||
|
func (s Source) SupportsArch(arch string) bool {
|
||||||
|
if len(s.Arch) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, a := range s.Arch {
|
||||||
|
if strings.EqualFold(a, arch) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect describes presence checks that do not depend on a package manager.
|
||||||
|
type Detect struct {
|
||||||
|
// Commands are executables that must resolve on PATH.
|
||||||
|
Commands []string `yaml:"commands,omitempty"`
|
||||||
|
// Paths are files or directories (globs allowed, env vars expanded).
|
||||||
|
Paths []string `yaml:"paths,omitempty"`
|
||||||
|
// Registry are Windows uninstall-entry DisplayName prefixes.
|
||||||
|
Registry []string `yaml:"registry,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty reports whether there is nothing to check.
|
||||||
|
func (d Detect) Empty() bool {
|
||||||
|
return len(d.Commands) == 0 && len(d.Paths) == 0 && len(d.Registry) == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// TargetFor returns the recipe for a GOOS, or nil when unsupported.
|
||||||
|
func (a *App) TargetFor(goos string) *Target {
|
||||||
|
switch goos {
|
||||||
|
case "windows":
|
||||||
|
return a.Windows
|
||||||
|
case "darwin":
|
||||||
|
return a.Darwin
|
||||||
|
case "linux":
|
||||||
|
return a.Linux
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Platforms lists the operating systems this app supports, sorted.
|
||||||
|
func (a *App) Platforms() []string {
|
||||||
|
var out []string
|
||||||
|
for _, goos := range []string{"windows", "darwin", "linux"} {
|
||||||
|
if a.TargetFor(goos) != nil {
|
||||||
|
out = append(out, goos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasCategory reports category membership, case-insensitively.
|
||||||
|
func (a *App) HasCategory(c string) bool {
|
||||||
|
for _, have := range a.Categories {
|
||||||
|
if strings.EqualFold(have, c) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Categories returns every category in the catalog, sorted and deduplicated.
|
||||||
|
func (c *Catalog) Categories() []string {
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var out []string
|
||||||
|
for _, a := range c.Apps {
|
||||||
|
for _, cat := range a.Categories {
|
||||||
|
if !seen[cat] {
|
||||||
|
seen[cat] = true
|
||||||
|
out = append(out, cat)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProfileNames returns profile names, sorted.
|
||||||
|
func (c *Catalog) ProfileNames() []string {
|
||||||
|
out := make([]string, 0, len(c.Profiles))
|
||||||
|
for name := range c.Profiles {
|
||||||
|
out = append(out, name)
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
// Package cli parses the command line and wires the catalog, providers and
|
||||||
|
// engine together.
|
||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/logx"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/version"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exit codes. These are the contract with whatever script calls deployr.
|
||||||
|
const (
|
||||||
|
// ExitOK means every requested app ended in the desired state.
|
||||||
|
ExitOK = 0
|
||||||
|
// ExitFailure means at least one app could not be handled.
|
||||||
|
ExitFailure = 1
|
||||||
|
// ExitUsage means the command line or catalog was wrong.
|
||||||
|
ExitUsage = 2
|
||||||
|
// ExitPrivilege means deployr does not have the rights to install software.
|
||||||
|
ExitPrivilege = 3
|
||||||
|
)
|
||||||
|
|
||||||
|
// globals are the flags every action-taking command accepts.
|
||||||
|
type globals struct {
|
||||||
|
json bool
|
||||||
|
dryRun bool
|
||||||
|
verbose bool
|
||||||
|
quiet bool
|
||||||
|
force bool
|
||||||
|
strict bool
|
||||||
|
requireChecksum bool
|
||||||
|
keepDownloads bool
|
||||||
|
allowUnelevated bool
|
||||||
|
only string
|
||||||
|
logFile string
|
||||||
|
noLog bool
|
||||||
|
timeout time.Duration
|
||||||
|
catalogs multiFlag
|
||||||
|
}
|
||||||
|
|
||||||
|
type multiFlag []string
|
||||||
|
|
||||||
|
func (m *multiFlag) String() string { return strings.Join(*m, ",") }
|
||||||
|
func (m *multiFlag) Set(v string) error {
|
||||||
|
*m = append(*m, v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *globals) register(fs *flag.FlagSet) {
|
||||||
|
fs.BoolVar(&g.json, "json", false, "emit a machine-readable summary on stdout")
|
||||||
|
fs.BoolVar(&g.dryRun, "dry-run", false, "show what would happen without changing anything")
|
||||||
|
fs.BoolVar(&g.verbose, "verbose", false, "log every command that is run")
|
||||||
|
fs.BoolVar(&g.quiet, "quiet", false, "only report failures")
|
||||||
|
fs.Var(&g.catalogs, "catalog", "extra catalog file or directory (repeatable)")
|
||||||
|
fs.DurationVar(&g.timeout, "timeout", 30*time.Minute, "per-installer timeout")
|
||||||
|
fs.StringVar(&g.logFile, "log-file", "", "write the run log here (default: the deployr log directory)")
|
||||||
|
fs.BoolVar(&g.noLog, "no-log", false, "do not write a log file")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *globals) registerAction(fs *flag.FlagSet) {
|
||||||
|
g.register(fs)
|
||||||
|
fs.BoolVar(&g.force, "force", false, "act even when the app is already in the desired state")
|
||||||
|
fs.BoolVar(&g.strict, "strict", false, "fail instead of falling through to the next source")
|
||||||
|
fs.BoolVar(&g.requireChecksum, "require-checksum", false, "refuse vendor downloads that have no sha256 in the catalog")
|
||||||
|
fs.BoolVar(&g.keepDownloads, "keep-downloads", false, "keep downloaded installers in the cache directory")
|
||||||
|
fs.BoolVar(&g.allowUnelevated, "allow-unelevated", false, "continue without administrator/root rights")
|
||||||
|
fs.StringVar(&g.only, "provider", "", "restrict every app to a single provider (e.g. winget, direct)")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *globals) level() logx.Level {
|
||||||
|
switch {
|
||||||
|
case g.verbose:
|
||||||
|
return logx.LevelDebug
|
||||||
|
case g.quiet:
|
||||||
|
return logx.LevelError
|
||||||
|
default:
|
||||||
|
return logx.LevelInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// newLogger sends progress to stdout normally, and to stderr in --json mode so
|
||||||
|
// stdout carries nothing but the JSON document.
|
||||||
|
func (g *globals) newLogger() *logx.Logger {
|
||||||
|
var console io.Writer = os.Stdout
|
||||||
|
if g.json {
|
||||||
|
console = os.Stderr
|
||||||
|
}
|
||||||
|
log := logx.New(console, g.level())
|
||||||
|
|
||||||
|
if !g.noLog {
|
||||||
|
path := g.logFile
|
||||||
|
if path == "" {
|
||||||
|
path = filepath.Join(platform.LogDir(), "deployr.log")
|
||||||
|
}
|
||||||
|
if err := log.AttachFile(path); err != nil {
|
||||||
|
log.Debugf("log file unavailable (%v); continuing without one", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return log
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main runs the CLI and returns the process exit code.
|
||||||
|
func Main(args []string) int {
|
||||||
|
if len(args) == 0 {
|
||||||
|
usage(os.Stdout)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
cmd := args[0]
|
||||||
|
rest := args[1:]
|
||||||
|
|
||||||
|
switch cmd {
|
||||||
|
case "install", "i":
|
||||||
|
return actionCommand(ctx, "install", rest)
|
||||||
|
case "update", "upgrade":
|
||||||
|
return actionCommand(ctx, "update", rest)
|
||||||
|
case "uninstall", "remove":
|
||||||
|
return actionCommand(ctx, "uninstall", rest)
|
||||||
|
case "list", "ls":
|
||||||
|
return listCommand(ctx, rest)
|
||||||
|
case "status":
|
||||||
|
return statusCommand(ctx, rest)
|
||||||
|
case "info", "show":
|
||||||
|
return infoCommand(rest)
|
||||||
|
case "profiles":
|
||||||
|
return profilesCommand(rest)
|
||||||
|
case "doctor":
|
||||||
|
return doctorCommand(ctx, rest)
|
||||||
|
case "catalog":
|
||||||
|
return catalogCommand(rest)
|
||||||
|
case "version", "--version", "-v":
|
||||||
|
fmt.Println(version.String())
|
||||||
|
return ExitOK
|
||||||
|
case "help", "--help", "-h":
|
||||||
|
usage(os.Stdout)
|
||||||
|
return ExitOK
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(os.Stderr, "deployr: unknown command %q\n\n", cmd)
|
||||||
|
usage(os.Stderr)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseFlags parses args and returns the non-flag operands. The standard flag
|
||||||
|
// package stops at the first operand, which would make `deployr install chrome
|
||||||
|
// --json` silently treat --json as an app name. Repeatedly parsing what is left
|
||||||
|
// after each operand gives the flags-anywhere behaviour every other CLI has.
|
||||||
|
func parseFlags(fs *flag.FlagSet, args []string) ([]string, error) {
|
||||||
|
var operands []string
|
||||||
|
for {
|
||||||
|
if err := fs.Parse(args); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rest := fs.Args()
|
||||||
|
if len(rest) == 0 {
|
||||||
|
return operands, nil
|
||||||
|
}
|
||||||
|
operands = append(operands, rest[0])
|
||||||
|
args = rest[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadCatalog reads the embedded catalog plus overlays, reporting a usage error
|
||||||
|
// rather than a stack trace when an overlay is malformed.
|
||||||
|
func loadCatalog(paths []string) (*catalog.Catalog, error) {
|
||||||
|
cat, err := catalog.Load(paths)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("catalog: %w", err)
|
||||||
|
}
|
||||||
|
return cat, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveApps maps command-line names onto catalog entries, printing a
|
||||||
|
// "did you mean" hint for anything unrecognised.
|
||||||
|
func resolveApps(cat *catalog.Catalog, names []string) ([]*catalog.App, error) {
|
||||||
|
apps, unknown := cat.Resolve(names)
|
||||||
|
if len(unknown) > 0 {
|
||||||
|
var msg strings.Builder
|
||||||
|
fmt.Fprintf(&msg, "unknown app or profile: %s", strings.Join(unknown, ", "))
|
||||||
|
if suggestions := cat.Suggest(unknown[0]); len(suggestions) > 0 {
|
||||||
|
fmt.Fprintf(&msg, "\n did you mean: %s", strings.Join(suggestions, ", "))
|
||||||
|
}
|
||||||
|
msg.WriteString("\n run `deployr list` to see the catalog")
|
||||||
|
return nil, errors.New(msg.String())
|
||||||
|
}
|
||||||
|
if len(apps) == 0 {
|
||||||
|
return nil, errors.New("no apps given")
|
||||||
|
}
|
||||||
|
return apps, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func usage(w io.Writer) {
|
||||||
|
fmt.Fprint(w, `deployr - cross-platform application deployment for Windows, macOS and Linux
|
||||||
|
|
||||||
|
USAGE
|
||||||
|
deployr <command> [flags] [apps...]
|
||||||
|
|
||||||
|
COMMANDS
|
||||||
|
install <app|@profile>... install applications
|
||||||
|
update <app|@profile>... update installed applications (--all for everything present)
|
||||||
|
uninstall <app|@profile>... remove applications
|
||||||
|
list show the catalog
|
||||||
|
status [app...] report what is installed
|
||||||
|
info <app> show one app's install recipe
|
||||||
|
profiles list the bundles defined in the catalog
|
||||||
|
doctor report platform, privileges and available providers
|
||||||
|
catalog validate [path] check a catalog overlay for errors
|
||||||
|
version print the build version
|
||||||
|
|
||||||
|
COMMON FLAGS
|
||||||
|
--json machine-readable output on stdout
|
||||||
|
--dry-run plan without changing the machine
|
||||||
|
--verbose log every command executed
|
||||||
|
--catalog PATH extra catalog file or directory (repeatable)
|
||||||
|
--timeout 30m per-installer timeout
|
||||||
|
|
||||||
|
EXAMPLES
|
||||||
|
deployr install chrome 7zip vlc
|
||||||
|
deployr install @standard --json
|
||||||
|
deployr update --all
|
||||||
|
deployr status --json
|
||||||
|
deployr list --category browser
|
||||||
|
|
||||||
|
EXIT CODES
|
||||||
|
0 success 1 one or more apps failed 2 usage error 3 insufficient privileges
|
||||||
|
`)
|
||||||
|
}
|
||||||
@@ -0,0 +1,594 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"text/tabwriter"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/detect"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/engine"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/logx"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/provider"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/run"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/version"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ------------------------------------------------- install/update/remove ---
|
||||||
|
|
||||||
|
func actionCommand(ctx context.Context, action string, args []string) int {
|
||||||
|
var g globals
|
||||||
|
fs := flag.NewFlagSet("deployr "+action, flag.ContinueOnError)
|
||||||
|
g.registerAction(fs)
|
||||||
|
all := fs.Bool("all", false, "apply to every catalog app that is installed on this machine")
|
||||||
|
names, err := parseFlags(fs, args)
|
||||||
|
if err != nil {
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
if !platform.Supported() {
|
||||||
|
fmt.Fprintf(os.Stderr, "deployr: %s is not a supported platform\n", runtime.GOOS)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
cat, err := loadCatalog(g.catalogs)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
var apps []*catalog.App
|
||||||
|
switch {
|
||||||
|
case *all && len(names) == 0:
|
||||||
|
apps = installedApps(cat)
|
||||||
|
if len(apps) == 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr: nothing from the catalog is installed on this machine")
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
case *all:
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr: --all takes no app arguments")
|
||||||
|
return ExitUsage
|
||||||
|
default:
|
||||||
|
apps, err = resolveApps(cat, names)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log := g.newLogger()
|
||||||
|
defer log.Close()
|
||||||
|
|
||||||
|
if code := checkPrivileges(&g, log); code != ExitOK {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Infof("%s: %s on %s (%s/%s)%s", version.String(), action, platform.Hostname(),
|
||||||
|
runtime.GOOS, runtime.GOARCH, dryRunNote(g.dryRun))
|
||||||
|
|
||||||
|
summary := engine.Run(ctx, apps, engine.Config{
|
||||||
|
Action: engine.Action(action),
|
||||||
|
DryRun: g.dryRun,
|
||||||
|
Force: g.force,
|
||||||
|
Strict: g.strict,
|
||||||
|
Timeout: g.timeout,
|
||||||
|
CacheDir: platform.CacheDir(),
|
||||||
|
RequireChecksum: g.requireChecksum,
|
||||||
|
KeepDownloads: g.keepDownloads,
|
||||||
|
OnlyProvider: g.only,
|
||||||
|
Log: log,
|
||||||
|
})
|
||||||
|
|
||||||
|
if g.json {
|
||||||
|
if err := writeJSON(summary); err != nil {
|
||||||
|
log.Errorf("%v", err)
|
||||||
|
return ExitFailure
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Infof("%s", summaryLine(summary))
|
||||||
|
if summary.RebootRequired {
|
||||||
|
log.Infof("a reboot is required to finish")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return summary.ExitCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
func dryRunNote(dry bool) string {
|
||||||
|
if dry {
|
||||||
|
return " [dry run]"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func summaryLine(s engine.Summary) string {
|
||||||
|
return fmt.Sprintf("%d changed, %d skipped, %d failed, %d unsupported in %s",
|
||||||
|
s.Changed, s.Skipped, s.Failed, s.Unsupported,
|
||||||
|
(time.Duration(s.DurationMS) * time.Millisecond).Round(time.Second))
|
||||||
|
}
|
||||||
|
|
||||||
|
// installedApps returns the catalog apps present on this machine, which is what
|
||||||
|
// `--all` means for an update run.
|
||||||
|
func installedApps(cat *catalog.Catalog) []*catalog.App {
|
||||||
|
var out []*catalog.App
|
||||||
|
for _, app := range cat.ForPlatform(runtime.GOOS) {
|
||||||
|
target := app.TargetFor(runtime.GOOS)
|
||||||
|
if ok, _ := detect.Installed(target.Detect); ok {
|
||||||
|
out = append(out, app)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkPrivileges refuses to start a run that cannot possibly succeed. Windows
|
||||||
|
// needs a real elevated token; Unix accepts either root or passwordless sudo.
|
||||||
|
func checkPrivileges(g *globals, log *logx.Logger) int {
|
||||||
|
if platform.IsElevated() {
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
if runtime.GOOS != "windows" && run.CanEscalate() {
|
||||||
|
log.Debugf("not root; escalating individual commands with sudo -n")
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
if g.allowUnelevated || g.dryRun {
|
||||||
|
log.Warnf("running without administrator/root rights; most installs will fail")
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
log.Errorf("administrator/root rights are required: %s", platform.PrivilegeHint())
|
||||||
|
log.Errorf("pass --allow-unelevated to try anyway")
|
||||||
|
return ExitPrivilege
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ list ---
|
||||||
|
|
||||||
|
type listRow struct {
|
||||||
|
App string `json:"app"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Platforms []string `json:"platforms"`
|
||||||
|
Categories []string `json:"categories,omitempty"`
|
||||||
|
Installed *bool `json:"installed,omitempty"`
|
||||||
|
Version string `json:"version,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func listCommand(_ context.Context, args []string) int {
|
||||||
|
var g globals
|
||||||
|
fs := flag.NewFlagSet("deployr list", flag.ContinueOnError)
|
||||||
|
g.register(fs)
|
||||||
|
category := fs.String("category", "", "only show apps in this category")
|
||||||
|
everywhere := fs.Bool("all-platforms", false, "include apps with no recipe for this platform")
|
||||||
|
onlyInstalled := fs.Bool("installed", false, "only show apps present on this machine")
|
||||||
|
names, err := parseFlags(fs, args)
|
||||||
|
if err != nil {
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
if len(names) > 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr: list takes no arguments; did you mean `deployr status`?")
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
cat, err := loadCatalog(g.catalogs)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
apps := cat.Apps
|
||||||
|
if !*everywhere {
|
||||||
|
apps = cat.ForPlatform(runtime.GOOS)
|
||||||
|
}
|
||||||
|
|
||||||
|
rows := make([]listRow, 0, len(apps))
|
||||||
|
for _, app := range apps {
|
||||||
|
if *category != "" && !app.HasCategory(*category) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
row := listRow{App: app.ID, Name: app.Name, Platforms: app.Platforms(), Categories: app.Categories}
|
||||||
|
if target := app.TargetFor(runtime.GOOS); target != nil {
|
||||||
|
present, ver := detect.Installed(target.Detect)
|
||||||
|
row.Installed = &present
|
||||||
|
row.Version = ver
|
||||||
|
}
|
||||||
|
if *onlyInstalled && (row.Installed == nil || !*row.Installed) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rows = append(rows, row)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.json {
|
||||||
|
if err := writeJSON(rows); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitFailure
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||||
|
fmt.Fprintln(w, "APP\tNAME\tPLATFORMS\tCATEGORIES\tINSTALLED")
|
||||||
|
for _, r := range rows {
|
||||||
|
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", r.App, r.Name,
|
||||||
|
strings.Join(shortPlatforms(r.Platforms), ","),
|
||||||
|
strings.Join(r.Categories, ","), installedCell(r))
|
||||||
|
}
|
||||||
|
w.Flush()
|
||||||
|
fmt.Printf("\n%d apps\n", len(rows))
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func installedCell(r listRow) string {
|
||||||
|
switch {
|
||||||
|
case r.Installed == nil:
|
||||||
|
return "-"
|
||||||
|
case !*r.Installed:
|
||||||
|
return "no"
|
||||||
|
case r.Version != "":
|
||||||
|
return "yes " + r.Version
|
||||||
|
default:
|
||||||
|
return "yes"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func shortPlatforms(p []string) []string {
|
||||||
|
out := make([]string, 0, len(p))
|
||||||
|
for _, os := range p {
|
||||||
|
switch os {
|
||||||
|
case "windows":
|
||||||
|
out = append(out, "win")
|
||||||
|
case "darwin":
|
||||||
|
out = append(out, "mac")
|
||||||
|
default:
|
||||||
|
out = append(out, os)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- status ---
|
||||||
|
|
||||||
|
type statusRow struct {
|
||||||
|
App string `json:"app"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Installed bool `json:"installed"`
|
||||||
|
Version string `json:"version,omitempty"`
|
||||||
|
Supported bool `json:"supported"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func statusCommand(_ context.Context, args []string) int {
|
||||||
|
var g globals
|
||||||
|
fs := flag.NewFlagSet("deployr status", flag.ContinueOnError)
|
||||||
|
g.register(fs)
|
||||||
|
names, err := parseFlags(fs, args)
|
||||||
|
if err != nil {
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
cat, err := loadCatalog(g.catalogs)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
apps := cat.ForPlatform(runtime.GOOS)
|
||||||
|
if len(names) > 0 {
|
||||||
|
apps, err = resolveApps(cat, names)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rows := make([]statusRow, 0, len(apps))
|
||||||
|
for _, app := range apps {
|
||||||
|
row := statusRow{App: app.ID, Name: app.Name}
|
||||||
|
if target := app.TargetFor(runtime.GOOS); target != nil {
|
||||||
|
row.Supported = true
|
||||||
|
row.Installed, row.Version = detect.Installed(target.Detect)
|
||||||
|
}
|
||||||
|
rows = append(rows, row)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.json {
|
||||||
|
if err := writeJSON(rows); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitFailure
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||||
|
fmt.Fprintln(w, "APP\tNAME\tSTATE\tVERSION")
|
||||||
|
installed := 0
|
||||||
|
for _, r := range rows {
|
||||||
|
state := "not installed"
|
||||||
|
switch {
|
||||||
|
case !r.Supported:
|
||||||
|
state = "unsupported"
|
||||||
|
case r.Installed:
|
||||||
|
state = "installed"
|
||||||
|
installed++
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", r.App, r.Name, state, r.Version)
|
||||||
|
}
|
||||||
|
w.Flush()
|
||||||
|
fmt.Printf("\n%d of %d installed\n", installed, len(rows))
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ info ---
|
||||||
|
|
||||||
|
func infoCommand(args []string) int {
|
||||||
|
var g globals
|
||||||
|
fs := flag.NewFlagSet("deployr info", flag.ContinueOnError)
|
||||||
|
g.register(fs)
|
||||||
|
names, err := parseFlags(fs, args)
|
||||||
|
if err != nil {
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
if len(names) != 1 {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr: info takes exactly one app")
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
cat, err := loadCatalog(g.catalogs)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
app, ok := cat.Get(names[0])
|
||||||
|
if !ok {
|
||||||
|
fmt.Fprintf(os.Stderr, "deployr: unknown app %q\n", names[0])
|
||||||
|
if s := cat.Suggest(names[0]); len(s) > 0 {
|
||||||
|
fmt.Fprintf(os.Stderr, " did you mean: %s\n", strings.Join(s, ", "))
|
||||||
|
}
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.json {
|
||||||
|
if err := writeJSON(app); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitFailure
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("%s (%s)\n", app.Name, app.ID)
|
||||||
|
if app.Description != "" {
|
||||||
|
fmt.Printf(" %s\n", app.Description)
|
||||||
|
}
|
||||||
|
if app.Homepage != "" {
|
||||||
|
fmt.Printf(" homepage: %s\n", app.Homepage)
|
||||||
|
}
|
||||||
|
if len(app.Categories) > 0 {
|
||||||
|
fmt.Printf(" categories: %s\n", strings.Join(app.Categories, ", "))
|
||||||
|
}
|
||||||
|
if len(app.Aliases) > 0 {
|
||||||
|
fmt.Printf(" aliases: %s\n", strings.Join(app.Aliases, ", "))
|
||||||
|
}
|
||||||
|
for _, goos := range app.Platforms() {
|
||||||
|
target := app.TargetFor(goos)
|
||||||
|
fmt.Printf("\n %s\n", goos)
|
||||||
|
for i, src := range target.Sources {
|
||||||
|
id := src.ID
|
||||||
|
if src.Provider == "direct" {
|
||||||
|
id = src.URLFor(runtime.GOARCH)
|
||||||
|
if id == "" {
|
||||||
|
id = src.URL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Printf(" %d. %-8s %s\n", i+1, src.Provider, id)
|
||||||
|
}
|
||||||
|
if !target.Detect.Empty() {
|
||||||
|
fmt.Printf(" detect: %s\n", describeDetect(target.Detect))
|
||||||
|
}
|
||||||
|
if target.Notes != "" {
|
||||||
|
fmt.Printf(" note: %s\n", target.Notes)
|
||||||
|
}
|
||||||
|
if goos == runtime.GOOS {
|
||||||
|
present, ver := detect.Installed(target.Detect)
|
||||||
|
state := "not installed"
|
||||||
|
if present {
|
||||||
|
state = "installed"
|
||||||
|
if ver != "" {
|
||||||
|
state += " " + ver
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Printf(" state: %s\n", state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func describeDetect(d catalog.Detect) string {
|
||||||
|
var parts []string
|
||||||
|
if len(d.Registry) > 0 {
|
||||||
|
parts = append(parts, "registry "+strings.Join(d.Registry, " | "))
|
||||||
|
}
|
||||||
|
if len(d.Paths) > 0 {
|
||||||
|
parts = append(parts, "paths "+strings.Join(d.Paths, " | "))
|
||||||
|
}
|
||||||
|
if len(d.Commands) > 0 {
|
||||||
|
parts = append(parts, "commands "+strings.Join(d.Commands, " | "))
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "; ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------- profiles ---
|
||||||
|
|
||||||
|
func profilesCommand(args []string) int {
|
||||||
|
var g globals
|
||||||
|
fs := flag.NewFlagSet("deployr profiles", flag.ContinueOnError)
|
||||||
|
g.register(fs)
|
||||||
|
names, err := parseFlags(fs, args)
|
||||||
|
if err != nil {
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
if len(names) > 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr: profiles takes no arguments")
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
cat, err := loadCatalog(g.catalogs)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.json {
|
||||||
|
if err := writeJSON(cat.Profiles); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitFailure
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
profileNames := cat.ProfileNames()
|
||||||
|
if len(profileNames) == 0 {
|
||||||
|
fmt.Println("no profiles defined")
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
for _, name := range profileNames {
|
||||||
|
members := append([]string(nil), cat.Profiles[name]...)
|
||||||
|
sort.Strings(members)
|
||||||
|
fmt.Printf("@%s (%d apps)\n %s\n\n", name, len(members), strings.Join(members, " "))
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- doctor ---
|
||||||
|
|
||||||
|
type doctorReport struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
Host string `json:"host"`
|
||||||
|
OS string `json:"os"`
|
||||||
|
Arch string `json:"arch"`
|
||||||
|
Elevated bool `json:"elevated"`
|
||||||
|
CanSudo bool `json:"can_escalate"`
|
||||||
|
Dirs map[string]string `json:"dirs"`
|
||||||
|
CatalogApp int `json:"catalog_apps"`
|
||||||
|
ForThisOS int `json:"catalog_apps_this_os"`
|
||||||
|
Profiles int `json:"profiles"`
|
||||||
|
Providers map[string]bool `json:"providers"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func doctorCommand(ctx context.Context, args []string) int {
|
||||||
|
var g globals
|
||||||
|
fs := flag.NewFlagSet("deployr doctor", flag.ContinueOnError)
|
||||||
|
g.register(fs)
|
||||||
|
names, err := parseFlags(fs, args)
|
||||||
|
if err != nil {
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
if len(names) > 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr: doctor takes no arguments")
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
cat, err := loadCatalog(g.catalogs)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
rep := doctorReport{
|
||||||
|
Version: version.Version,
|
||||||
|
Host: platform.Hostname(),
|
||||||
|
OS: runtime.GOOS,
|
||||||
|
Arch: runtime.GOARCH,
|
||||||
|
Elevated: platform.IsElevated(),
|
||||||
|
CanSudo: run.CanEscalate(),
|
||||||
|
Dirs: map[string]string{
|
||||||
|
"data": platform.DataDir(),
|
||||||
|
"logs": platform.LogDir(),
|
||||||
|
"cache": platform.CacheDir(),
|
||||||
|
},
|
||||||
|
CatalogApp: len(cat.Apps),
|
||||||
|
ForThisOS: len(cat.ForPlatform(runtime.GOOS)),
|
||||||
|
Profiles: len(cat.Profiles),
|
||||||
|
Providers: map[string]bool{},
|
||||||
|
}
|
||||||
|
|
||||||
|
opts := provider.Opts{Timeout: 30 * time.Second}
|
||||||
|
providers := provider.ForOS(runtime.GOOS)
|
||||||
|
for _, p := range providers {
|
||||||
|
rep.Providers[p.Name()] = p.Available(ctx, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.json {
|
||||||
|
if err := writeJSON(rep); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitFailure
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(version.String())
|
||||||
|
fmt.Printf("\nhost: %s\n", rep.Host)
|
||||||
|
fmt.Printf("platform: %s/%s\n", rep.OS, rep.Arch)
|
||||||
|
fmt.Printf("elevated: %s\n", yesNo(rep.Elevated))
|
||||||
|
if runtime.GOOS != "windows" {
|
||||||
|
fmt.Printf("sudo -n: %s\n", yesNo(rep.CanSudo))
|
||||||
|
}
|
||||||
|
fmt.Printf("\ncatalog: %d apps (%d for %s), %d profiles\n",
|
||||||
|
rep.CatalogApp, rep.ForThisOS, rep.OS, rep.Profiles)
|
||||||
|
fmt.Println("overlays:")
|
||||||
|
for _, dir := range platform.CatalogDirs() {
|
||||||
|
fmt.Printf(" %s\n", dir)
|
||||||
|
}
|
||||||
|
fmt.Println("directories:")
|
||||||
|
for _, key := range []string{"data", "logs", "cache"} {
|
||||||
|
fmt.Printf(" %-6s %s\n", key, rep.Dirs[key])
|
||||||
|
}
|
||||||
|
fmt.Println("providers:")
|
||||||
|
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||||
|
for _, p := range providers {
|
||||||
|
state := "missing"
|
||||||
|
if rep.Providers[p.Name()] {
|
||||||
|
state = "available"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " %s\t%s\t%s\n", p.Name(), state, p.Label())
|
||||||
|
}
|
||||||
|
w.Flush()
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func yesNo(b bool) string {
|
||||||
|
if b {
|
||||||
|
return "yes"
|
||||||
|
}
|
||||||
|
return "no"
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------------------------------------------- catalog ---
|
||||||
|
|
||||||
|
func catalogCommand(args []string) int {
|
||||||
|
if len(args) == 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr: catalog needs a subcommand (validate)")
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "validate":
|
||||||
|
cat, err := loadCatalog(args[1:])
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
fmt.Printf("catalog ok: %d apps, %d profiles\n", len(cat.Apps), len(cat.Profiles))
|
||||||
|
for _, goos := range []string{"windows", "darwin", "linux"} {
|
||||||
|
fmt.Printf(" %-8s %d apps\n", goos, len(cat.ForPlatform(goos)))
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(os.Stderr, "deployr: unknown catalog subcommand %q\n", args[0])
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(v any) error {
|
||||||
|
enc := json.NewEncoder(os.Stdout)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
return enc.Encode(v)
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
// Package detect decides whether an application is already present on the
|
||||||
|
// machine, independently of which package manager (if any) put it there.
|
||||||
|
package detect
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/run"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Entry is one Windows uninstall-registry record.
|
||||||
|
type Entry struct {
|
||||||
|
DisplayName string
|
||||||
|
DisplayVersion string
|
||||||
|
Publisher string
|
||||||
|
UninstallString string
|
||||||
|
QuietUninstallString string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Installed evaluates the detect rules and reports presence plus, when it can
|
||||||
|
// be determined cheaply, the installed version.
|
||||||
|
func Installed(d catalog.Detect) (bool, string) {
|
||||||
|
if d.Empty() {
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(d.Registry) > 0 && runtime.GOOS == "windows" {
|
||||||
|
if entry, ok := FindRegistry(d.Registry); ok {
|
||||||
|
return true, entry.DisplayVersion
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, p := range d.Paths {
|
||||||
|
if platform.PathExists(p) {
|
||||||
|
return true, bundleVersion(p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range d.Commands {
|
||||||
|
if run.Available(c) {
|
||||||
|
return true, ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// bundleVersion reads CFBundleShortVersionString from a macOS .app bundle.
|
||||||
|
// Everything else has no cheap, universal version probe, so we report none
|
||||||
|
// rather than guessing.
|
||||||
|
func bundleVersion(path string) string {
|
||||||
|
if runtime.GOOS != "darwin" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
path = platform.ExpandPath(path)
|
||||||
|
if !strings.HasSuffix(path, ".app") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
out, err := exec.CommandContext(ctx, "/usr/bin/defaults", "read",
|
||||||
|
filepath.Join(path, "Contents", "Info"), "CFBundleShortVersionString").Output()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindRegistry returns the first Windows uninstall entry whose DisplayName
|
||||||
|
// matches one of the patterns. Matching is a case-insensitive prefix test, so
|
||||||
|
// "Google Chrome" matches "Google Chrome" and "Google Chrome (64-bit)" alike.
|
||||||
|
func FindRegistry(patterns []string) (Entry, bool) {
|
||||||
|
if runtime.GOOS != "windows" || len(patterns) == 0 {
|
||||||
|
return Entry{}, false
|
||||||
|
}
|
||||||
|
entries := RegistryEntries()
|
||||||
|
for _, pattern := range patterns {
|
||||||
|
p := strings.ToLower(strings.TrimSpace(pattern))
|
||||||
|
if p == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, e := range entries {
|
||||||
|
name := strings.ToLower(e.DisplayName)
|
||||||
|
if strings.HasPrefix(name, p) || strings.Contains(name, p) {
|
||||||
|
return e, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Entry{}, false
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package detect
|
||||||
|
|
||||||
|
// RegistryEntries has nothing to read outside Windows.
|
||||||
|
func RegistryEntries() []Entry { return nil }
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package detect
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows/registry"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
regOnce sync.Once
|
||||||
|
regCache []Entry
|
||||||
|
)
|
||||||
|
|
||||||
|
// uninstallRoots covers 64-bit, 32-bit-on-64-bit and per-user installs. Missing
|
||||||
|
// any one of them is the classic reason a "not installed" check is wrong.
|
||||||
|
var uninstallRoots = []struct {
|
||||||
|
key registry.Key
|
||||||
|
path string
|
||||||
|
flags uint32
|
||||||
|
}{
|
||||||
|
{registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`, registry.READ | registry.WOW64_64KEY},
|
||||||
|
{registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`, registry.READ | registry.WOW64_32KEY},
|
||||||
|
{registry.CURRENT_USER, `SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`, registry.READ},
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegistryEntries reads the Windows uninstall registry once per process.
|
||||||
|
func RegistryEntries() []Entry {
|
||||||
|
regOnce.Do(func() {
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, root := range uninstallRoots {
|
||||||
|
k, err := registry.OpenKey(root.key, root.path, root.flags)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
names, err := k.ReadSubKeyNames(-1)
|
||||||
|
k.Close()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, name := range names {
|
||||||
|
sub, err := registry.OpenKey(root.key, root.path+`\`+name, root.flags)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
display, _, err := sub.GetStringValue("DisplayName")
|
||||||
|
if err != nil || display == "" {
|
||||||
|
sub.Close()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// System components and update patches are noise.
|
||||||
|
if v, _, err := sub.GetIntegerValue("SystemComponent"); err == nil && v == 1 {
|
||||||
|
sub.Close()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
e := Entry{DisplayName: display}
|
||||||
|
e.DisplayVersion, _, _ = sub.GetStringValue("DisplayVersion")
|
||||||
|
e.Publisher, _, _ = sub.GetStringValue("Publisher")
|
||||||
|
e.UninstallString, _, _ = sub.GetStringValue("UninstallString")
|
||||||
|
e.QuietUninstallString, _, _ = sub.GetStringValue("QuietUninstallString")
|
||||||
|
sub.Close()
|
||||||
|
|
||||||
|
key := display + "\x00" + e.DisplayVersion
|
||||||
|
if seen[key] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[key] = true
|
||||||
|
regCache = append(regCache, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return regCache
|
||||||
|
}
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
// Package download fetches vendor installers with retries and optional
|
||||||
|
// checksum pinning.
|
||||||
|
package download
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/logx"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/version"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrChecksumMissing is returned when --require-checksum is set and the
|
||||||
|
// catalog entry has no sha256.
|
||||||
|
var ErrChecksumMissing = errors.New("no sha256 in catalog and checksum verification is required")
|
||||||
|
|
||||||
|
// Options controls a download.
|
||||||
|
type Options struct {
|
||||||
|
URL string
|
||||||
|
SHA256 string
|
||||||
|
Dir string // destination directory
|
||||||
|
Filename string // override the derived filename
|
||||||
|
Timeout time.Duration // whole-transfer budget
|
||||||
|
RequireChecksum bool
|
||||||
|
Attempts int
|
||||||
|
Log *logx.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch downloads a file and returns its path on disk. The transfer lands in a
|
||||||
|
// .part file and is renamed only after the checksum passes, so a killed run can
|
||||||
|
// never leave a truncated installer that looks complete.
|
||||||
|
func Fetch(ctx context.Context, o Options) (string, error) {
|
||||||
|
if o.Attempts <= 0 {
|
||||||
|
o.Attempts = 3
|
||||||
|
}
|
||||||
|
if o.Timeout <= 0 {
|
||||||
|
o.Timeout = 20 * time.Minute
|
||||||
|
}
|
||||||
|
if o.SHA256 == "" && o.RequireChecksum {
|
||||||
|
return "", ErrChecksumMissing
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(o.Dir, 0o755); err != nil {
|
||||||
|
return "", fmt.Errorf("create download dir: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
name := o.Filename
|
||||||
|
if name == "" {
|
||||||
|
name = filenameFromURL(o.URL)
|
||||||
|
}
|
||||||
|
dest := filepath.Join(o.Dir, name)
|
||||||
|
|
||||||
|
// A cached copy is only trustworthy when the catalog pins a checksum.
|
||||||
|
if o.SHA256 != "" {
|
||||||
|
if sum, err := hashFile(dest); err == nil && strings.EqualFold(sum, o.SHA256) {
|
||||||
|
if o.Log != nil {
|
||||||
|
o.Log.Debugf("using cached download %s", dest)
|
||||||
|
}
|
||||||
|
return dest, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var lastErr error
|
||||||
|
for attempt := 1; attempt <= o.Attempts; attempt++ {
|
||||||
|
if attempt > 1 {
|
||||||
|
delay := time.Duration(attempt-1) * 3 * time.Second
|
||||||
|
if o.Log != nil {
|
||||||
|
o.Log.Debugf("retrying download in %s (attempt %d/%d)", delay, attempt, o.Attempts)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return "", ctx.Err()
|
||||||
|
case <-time.After(delay):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p, err := fetchOnce(ctx, o, dest)
|
||||||
|
if err == nil {
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
lastErr = err
|
||||||
|
if errors.Is(err, context.Canceled) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", lastErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchOnce(ctx context.Context, o Options, dest string) (string, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, o.Timeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, o.URL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("bad url %q: %w", o.URL, err)
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "deployr/"+version.Version)
|
||||||
|
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("download %s: %w", o.URL, err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return "", fmt.Errorf("download %s: HTTP %s", o.URL, resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Many vendors serve an evergreen URL that redirects to a versioned file;
|
||||||
|
// prefer the real name so the cache directory stays readable.
|
||||||
|
if o.Filename == "" {
|
||||||
|
if n := filenameFromResponse(resp); n != "" {
|
||||||
|
dest = filepath.Join(o.Dir, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
part := dest + ".part"
|
||||||
|
f, err := os.Create(part)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("create %s: %w", part, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
hasher := sha256.New()
|
||||||
|
written, err := io.Copy(io.MultiWriter(f, hasher), resp.Body)
|
||||||
|
closeErr := f.Close()
|
||||||
|
if err != nil {
|
||||||
|
os.Remove(part)
|
||||||
|
return "", fmt.Errorf("download %s: %w", o.URL, err)
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
os.Remove(part)
|
||||||
|
return "", closeErr
|
||||||
|
}
|
||||||
|
if written == 0 {
|
||||||
|
os.Remove(part)
|
||||||
|
return "", fmt.Errorf("download %s: empty response", o.URL)
|
||||||
|
}
|
||||||
|
|
||||||
|
sum := hex.EncodeToString(hasher.Sum(nil))
|
||||||
|
if o.SHA256 != "" && !strings.EqualFold(sum, o.SHA256) {
|
||||||
|
os.Remove(part)
|
||||||
|
return "", fmt.Errorf("checksum mismatch for %s: expected %s, got %s", o.URL, o.SHA256, sum)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.Rename(part, dest); err != nil {
|
||||||
|
os.Remove(part)
|
||||||
|
return "", fmt.Errorf("finalise %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
if o.Log != nil {
|
||||||
|
o.Log.Debugf("downloaded %s (%.1f MB, sha256 %s)", dest, float64(written)/(1<<20), sum[:16])
|
||||||
|
}
|
||||||
|
return dest, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func filenameFromResponse(resp *http.Response) string {
|
||||||
|
if cd := resp.Header.Get("Content-Disposition"); cd != "" {
|
||||||
|
if _, params, err := mime.ParseMediaType(cd); err == nil {
|
||||||
|
if n := sanitize(params["filename"]); n != "" {
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// resp.Request reflects the final URL after redirects.
|
||||||
|
if resp.Request != nil && resp.Request.URL != nil {
|
||||||
|
return filenameFromURL(resp.Request.URL.String())
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func filenameFromURL(raw string) string {
|
||||||
|
u, err := url.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
return "installer.bin"
|
||||||
|
}
|
||||||
|
name := sanitize(path.Base(u.Path))
|
||||||
|
if name == "" || name == "." || name == "/" {
|
||||||
|
return "installer.bin"
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
// sanitize strips any directory component so a hostile or sloppy
|
||||||
|
// Content-Disposition header cannot write outside the cache directory.
|
||||||
|
func sanitize(name string) string {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
name = strings.ReplaceAll(name, "\\", "/")
|
||||||
|
name = path.Base(name)
|
||||||
|
if name == "." || name == "/" || name == ".." {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
func hashFile(path string) (string, error) {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
h := sha256.New()
|
||||||
|
if _, err := io.Copy(h, f); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(h.Sum(nil)), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
// Package engine turns a list of catalog apps into work: it decides whether an
|
||||||
|
// app needs touching, picks an install route that exists on this machine, and
|
||||||
|
// records what happened in a form both a technician and a script can read.
|
||||||
|
package engine
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/detect"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/logx"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Action is the operation being performed.
|
||||||
|
type Action string
|
||||||
|
|
||||||
|
// The supported actions.
|
||||||
|
const (
|
||||||
|
ActionInstall Action = "install"
|
||||||
|
ActionUpdate Action = "update"
|
||||||
|
ActionUninstall Action = "uninstall"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Status is the per-app outcome.
|
||||||
|
type Status string
|
||||||
|
|
||||||
|
// The possible per-app outcomes.
|
||||||
|
const (
|
||||||
|
// StatusChanged means the machine was modified.
|
||||||
|
StatusChanged Status = "ok"
|
||||||
|
// StatusSkipped means no work was needed.
|
||||||
|
StatusSkipped Status = "skip"
|
||||||
|
// StatusFailed means every route failed.
|
||||||
|
StatusFailed Status = "fail"
|
||||||
|
// StatusUnsupported means the catalog has no recipe for this platform.
|
||||||
|
StatusUnsupported Status = "n/a"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config controls one engine run.
|
||||||
|
type Config struct {
|
||||||
|
Action Action
|
||||||
|
DryRun bool
|
||||||
|
Force bool // act even when the app is already in the desired state
|
||||||
|
Strict bool // stop at the first failing source instead of falling through
|
||||||
|
Timeout time.Duration
|
||||||
|
CacheDir string
|
||||||
|
RequireChecksum bool
|
||||||
|
KeepDownloads bool
|
||||||
|
OnlyProvider string // restrict every app to a single provider
|
||||||
|
Log *logx.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attempt records one source that was tried and did not work out.
|
||||||
|
type Attempt struct {
|
||||||
|
Provider string `json:"provider"`
|
||||||
|
Error string `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Result is the outcome for one app.
|
||||||
|
type Result struct {
|
||||||
|
App string `json:"app"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Status Status `json:"status"`
|
||||||
|
Provider string `json:"provider,omitempty"`
|
||||||
|
Version string `json:"version,omitempty"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
RebootRequired bool `json:"reboot_required,omitempty"`
|
||||||
|
DurationMS int64 `json:"duration_ms"`
|
||||||
|
Attempts []Attempt `json:"attempts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Summary is the whole run, and is what --json prints.
|
||||||
|
type Summary struct {
|
||||||
|
Action Action `json:"action"`
|
||||||
|
Host string `json:"host"`
|
||||||
|
OS string `json:"os"`
|
||||||
|
Arch string `json:"arch"`
|
||||||
|
StartedAt string `json:"started_at"`
|
||||||
|
DurationMS int64 `json:"duration_ms"`
|
||||||
|
DryRun bool `json:"dry_run,omitempty"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Changed int `json:"changed"`
|
||||||
|
Skipped int `json:"skipped"`
|
||||||
|
Failed int `json:"failed"`
|
||||||
|
Unsupported int `json:"unsupported"`
|
||||||
|
RebootRequired bool `json:"reboot_required"`
|
||||||
|
Results []Result `json:"results"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExitCode maps a run onto a process exit status an RMM can branch on:
|
||||||
|
// 0 = nothing went wrong, 1 = at least one app failed.
|
||||||
|
func (s Summary) ExitCode() int {
|
||||||
|
if s.Failed > 0 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run performs the action for every app, in order. Work is deliberately
|
||||||
|
// sequential: package managers take machine-wide locks, and two installers
|
||||||
|
// racing on the same box is how you corrupt an MSI database.
|
||||||
|
func Run(ctx context.Context, apps []*catalog.App, cfg Config) Summary {
|
||||||
|
start := time.Now()
|
||||||
|
sum := Summary{
|
||||||
|
Action: cfg.Action,
|
||||||
|
Host: platform.Hostname(),
|
||||||
|
OS: runtime.GOOS,
|
||||||
|
Arch: runtime.GOARCH,
|
||||||
|
StartedAt: start.UTC().Format(time.RFC3339),
|
||||||
|
DryRun: cfg.DryRun,
|
||||||
|
Total: len(apps),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, app := range apps {
|
||||||
|
res := runOne(ctx, app, cfg)
|
||||||
|
sum.Results = append(sum.Results, res)
|
||||||
|
|
||||||
|
switch res.Status {
|
||||||
|
case StatusChanged:
|
||||||
|
sum.Changed++
|
||||||
|
case StatusSkipped:
|
||||||
|
sum.Skipped++
|
||||||
|
case StatusFailed:
|
||||||
|
sum.Failed++
|
||||||
|
case StatusUnsupported:
|
||||||
|
sum.Unsupported++
|
||||||
|
}
|
||||||
|
if res.RebootRequired {
|
||||||
|
sum.RebootRequired = true
|
||||||
|
}
|
||||||
|
if cfg.Log != nil {
|
||||||
|
logResult(cfg.Log, res)
|
||||||
|
}
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sum.DurationMS = time.Since(start).Milliseconds()
|
||||||
|
return sum
|
||||||
|
}
|
||||||
|
|
||||||
|
func logResult(log *logx.Logger, r Result) {
|
||||||
|
detail := r.Message
|
||||||
|
if r.Error != "" {
|
||||||
|
detail = r.Error
|
||||||
|
}
|
||||||
|
if r.Provider != "" && r.Status == StatusChanged {
|
||||||
|
via := "via " + r.Provider
|
||||||
|
if r.Version != "" {
|
||||||
|
via += " (" + r.Version + ")"
|
||||||
|
}
|
||||||
|
if detail == "" {
|
||||||
|
detail = via
|
||||||
|
} else {
|
||||||
|
detail = via + " - " + detail
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.Resultf(string(r.Status), "%-22s %s", r.App, detail)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runOne(ctx context.Context, app *catalog.App, cfg Config) Result {
|
||||||
|
start := time.Now()
|
||||||
|
res := Result{App: app.ID, Name: app.Name}
|
||||||
|
defer func() { res.DurationMS = time.Since(start).Milliseconds() }()
|
||||||
|
|
||||||
|
target := app.TargetFor(runtime.GOOS)
|
||||||
|
if target == nil {
|
||||||
|
res.Status = StatusUnsupported
|
||||||
|
res.Message = fmt.Sprintf("no %s recipe in the catalog", runtime.GOOS)
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
installed, version := detect.Installed(target.Detect)
|
||||||
|
|
||||||
|
// Decide up front whether there is anything to do at all. Detection is
|
||||||
|
// provider-independent, so this is also correct for software a technician
|
||||||
|
// installed by hand.
|
||||||
|
switch cfg.Action {
|
||||||
|
case ActionInstall:
|
||||||
|
if installed && !cfg.Force {
|
||||||
|
res.Status = StatusSkipped
|
||||||
|
res.Version = version
|
||||||
|
res.Message = "already installed"
|
||||||
|
if version != "" {
|
||||||
|
res.Message += " (" + version + ")"
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
case ActionUpdate, ActionUninstall:
|
||||||
|
if !installed && !cfg.Force && !target.Detect.Empty() {
|
||||||
|
res.Status = StatusSkipped
|
||||||
|
res.Message = "not installed"
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
opts := provider.Opts{
|
||||||
|
DryRun: cfg.DryRun,
|
||||||
|
Timeout: cfg.Timeout,
|
||||||
|
Log: cfg.Log,
|
||||||
|
CacheDir: cfg.CacheDir,
|
||||||
|
Arch: runtime.GOARCH,
|
||||||
|
RequireChecksum: cfg.RequireChecksum,
|
||||||
|
KeepDownloads: cfg.KeepDownloads,
|
||||||
|
Detect: target.Detect,
|
||||||
|
}
|
||||||
|
|
||||||
|
usable := 0
|
||||||
|
for _, src := range target.Sources {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
res.Status = StatusFailed
|
||||||
|
res.Error = "cancelled"
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
if !src.SupportsArch(runtime.GOARCH) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if cfg.OnlyProvider != "" && !strings.EqualFold(src.Provider, cfg.OnlyProvider) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
p, ok := provider.Get(src.Provider)
|
||||||
|
if !ok {
|
||||||
|
res.Attempts = append(res.Attempts, Attempt{Provider: src.Provider, Error: "unknown provider"})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !p.Available(ctx, opts) {
|
||||||
|
res.Attempts = append(res.Attempts, Attempt{Provider: src.Provider, Error: "not available on this machine"})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
usable++
|
||||||
|
|
||||||
|
if cfg.Log != nil {
|
||||||
|
cfg.Log.Debugf("%s: trying %s (%s)", app.ID, src.Provider, src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
out provider.Outcome
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
switch cfg.Action {
|
||||||
|
case ActionInstall:
|
||||||
|
out, err = p.Install(ctx, src, opts)
|
||||||
|
case ActionUpdate:
|
||||||
|
out, err = p.Update(ctx, src, opts)
|
||||||
|
case ActionUninstall:
|
||||||
|
out, err = p.Uninstall(ctx, src, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
res.Attempts = append(res.Attempts, Attempt{Provider: src.Provider, Error: err.Error()})
|
||||||
|
if cfg.Strict {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
res.Provider = p.Name()
|
||||||
|
res.RebootRequired = out.RebootRequired
|
||||||
|
res.Message = out.Message
|
||||||
|
if out.NoOp {
|
||||||
|
res.Status = StatusSkipped
|
||||||
|
if res.Message == "" {
|
||||||
|
res.Message = "nothing to do"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res.Status = StatusChanged
|
||||||
|
}
|
||||||
|
res.Version = finalVersion(ctx, p, src, opts, out, target, cfg)
|
||||||
|
if out.RebootRequired {
|
||||||
|
res.Message = strings.TrimSpace(res.Message + " (reboot required)")
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
res.Status = StatusFailed
|
||||||
|
switch {
|
||||||
|
case usable == 0 && len(res.Attempts) > 0:
|
||||||
|
res.Error = "no usable install route on this machine"
|
||||||
|
case len(res.Attempts) == 0:
|
||||||
|
res.Error = "no source matches this machine"
|
||||||
|
default:
|
||||||
|
res.Error = summarizeAttempts(res.Attempts)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// finalVersion reports what is on the machine after the operation, preferring
|
||||||
|
// the provider's own answer and falling back to the catalog's detect rules.
|
||||||
|
func finalVersion(ctx context.Context, p provider.Provider, src catalog.Source, opts provider.Opts,
|
||||||
|
out provider.Outcome, target *catalog.Target, cfg Config) string {
|
||||||
|
if out.Version != "" {
|
||||||
|
return out.Version
|
||||||
|
}
|
||||||
|
if cfg.DryRun || cfg.Action == ActionUninstall {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if v, ok := p.Query(ctx, src, opts); ok && v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
if _, v := detect.Installed(target.Detect); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func summarizeAttempts(attempts []Attempt) string {
|
||||||
|
parts := make([]string, 0, len(attempts))
|
||||||
|
for _, a := range attempts {
|
||||||
|
parts = append(parts, a.Provider+": "+a.Error)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "; ")
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
// Package logx is a tiny leveled logger that writes human-readable lines to a
|
||||||
|
// stream and, optionally, tees everything to a log file. Output is deliberately
|
||||||
|
// plain ASCII so it survives RMM script-output capture and legacy consoles.
|
||||||
|
package logx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Level controls verbosity.
|
||||||
|
type Level int
|
||||||
|
|
||||||
|
const (
|
||||||
|
// LevelDebug logs every command that is executed.
|
||||||
|
LevelDebug Level = iota
|
||||||
|
// LevelInfo is the default.
|
||||||
|
LevelInfo
|
||||||
|
// LevelWarn hides progress chatter.
|
||||||
|
LevelWarn
|
||||||
|
// LevelError only reports failures.
|
||||||
|
LevelError
|
||||||
|
)
|
||||||
|
|
||||||
|
// Logger writes to a console stream and an optional file.
|
||||||
|
type Logger struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
console io.Writer
|
||||||
|
file *os.File
|
||||||
|
level Level
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a Logger writing to w at the given level.
|
||||||
|
func New(w io.Writer, level Level) *Logger {
|
||||||
|
if w == nil {
|
||||||
|
w = io.Discard
|
||||||
|
}
|
||||||
|
return &Logger{console: w, level: level}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AttachFile starts teeing output to path, creating parent directories.
|
||||||
|
// A failure here is never fatal: logging to a file is a convenience, and an
|
||||||
|
// endpoint with a read-only or missing state directory must still be able to
|
||||||
|
// install software.
|
||||||
|
func (l *Logger) AttachFile(path string) error {
|
||||||
|
if path == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
l.mu.Lock()
|
||||||
|
l.file = f
|
||||||
|
l.mu.Unlock()
|
||||||
|
l.writeFileOnly(fmt.Sprintf("\n=== deployr run started %s ===\n", time.Now().Format(time.RFC3339)))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close flushes and closes the log file, if any.
|
||||||
|
func (l *Logger) Close() {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
if l.file != nil {
|
||||||
|
_ = l.file.Close()
|
||||||
|
l.file = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetLevel changes verbosity at runtime.
|
||||||
|
func (l *Logger) SetLevel(level Level) {
|
||||||
|
l.mu.Lock()
|
||||||
|
l.level = level
|
||||||
|
l.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) writeFileOnly(s string) {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
if l.file != nil {
|
||||||
|
_, _ = io.WriteString(l.file, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Logger) emit(level Level, prefix, format string, args ...any) {
|
||||||
|
msg := fmt.Sprintf(format, args...)
|
||||||
|
line := msg + "\n"
|
||||||
|
if prefix != "" {
|
||||||
|
line = prefix + " " + line
|
||||||
|
}
|
||||||
|
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
if l.file != nil {
|
||||||
|
_, _ = io.WriteString(l.file, time.Now().Format("15:04:05")+" "+line)
|
||||||
|
}
|
||||||
|
if level >= l.level {
|
||||||
|
_, _ = io.WriteString(l.console, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debugf logs command-level detail.
|
||||||
|
func (l *Logger) Debugf(format string, args ...any) { l.emit(LevelDebug, " |", format, args...) }
|
||||||
|
|
||||||
|
// Infof logs normal progress.
|
||||||
|
func (l *Logger) Infof(format string, args ...any) { l.emit(LevelInfo, "", format, args...) }
|
||||||
|
|
||||||
|
// Warnf logs a recoverable problem.
|
||||||
|
func (l *Logger) Warnf(format string, args ...any) { l.emit(LevelWarn, "warn:", format, args...) }
|
||||||
|
|
||||||
|
// Errorf logs a failure.
|
||||||
|
func (l *Logger) Errorf(format string, args ...any) { l.emit(LevelError, "error:", format, args...) }
|
||||||
|
|
||||||
|
// Resultf logs a per-app outcome line, e.g. "[ok] chrome installed via winget".
|
||||||
|
func (l *Logger) Resultf(status, format string, args ...any) {
|
||||||
|
l.emit(LevelWarn, fmt.Sprintf("[%-4s]", status), format, args...)
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package platform
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsElevated reports whether the process is running as root.
|
||||||
|
func IsElevated() bool { return os.Geteuid() == 0 }
|
||||||
|
|
||||||
|
// ConsoleUser returns the user logged in at the macOS GUI console. Homebrew
|
||||||
|
// refuses to run as root, so a root-context run (RMM, MDM) has to drop to this
|
||||||
|
// user to touch brew. Returns "" when there is no console user or on Linux.
|
||||||
|
func ConsoleUser() string {
|
||||||
|
if runtime.GOOS != "darwin" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
out, err := exec.Command("/usr/bin/stat", "-f", "%Su", "/dev/console").Output()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
u := strings.TrimSpace(string(out))
|
||||||
|
if u == "" || u == "root" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrivilegeHint explains how to obtain the rights deployr needs.
|
||||||
|
func PrivilegeHint() string {
|
||||||
|
return "re-run deployr with sudo, or configure passwordless sudo for the account your RMM uses"
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package platform
|
||||||
|
|
||||||
|
import "golang.org/x/sys/windows"
|
||||||
|
|
||||||
|
// IsElevated reports whether the process holds an elevated token. Under the
|
||||||
|
// SYSTEM account (how RMM agents run scripts) this is true.
|
||||||
|
func IsElevated() bool {
|
||||||
|
tok := windows.GetCurrentProcessToken()
|
||||||
|
return tok.IsElevated()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConsoleUser is meaningless on Windows.
|
||||||
|
func ConsoleUser() string { return "" }
|
||||||
|
|
||||||
|
// PrivilegeHint explains how to obtain the rights deployr needs.
|
||||||
|
func PrivilegeHint() string {
|
||||||
|
return "run deployr from an elevated (Administrator) shell, or as SYSTEM via your RMM"
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
// Package platform answers the "where am I running and with what rights"
|
||||||
|
// questions: OS/arch, elevation, and the well-known directories deployr uses
|
||||||
|
// for logs, downloads and catalog overlays.
|
||||||
|
package platform
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// OS returns the normalized operating system name: windows, darwin or linux.
|
||||||
|
func OS() string { return runtime.GOOS }
|
||||||
|
|
||||||
|
// Arch returns the normalized CPU architecture: amd64, arm64, 386, arm.
|
||||||
|
func Arch() string { return runtime.GOARCH }
|
||||||
|
|
||||||
|
// Supported reports whether deployr knows how to operate on this OS.
|
||||||
|
func Supported() bool {
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "windows", "darwin", "linux":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hostname is the machine name, or "unknown" when it cannot be determined.
|
||||||
|
func Hostname() string {
|
||||||
|
h, err := os.Hostname()
|
||||||
|
if err != nil || h == "" {
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
// DataDir is the machine-wide state directory. It falls back to a per-user
|
||||||
|
// directory when the system location is not writable, so an unelevated run
|
||||||
|
// still works for user-scope package managers.
|
||||||
|
func DataDir() string {
|
||||||
|
return firstWritable(systemDataDir(), userDir("deployr"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// LogDir is where run logs are written.
|
||||||
|
func LogDir() string {
|
||||||
|
return firstWritable(systemLogDir(), filepath.Join(userDir("deployr"), "logs"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// CacheDir holds downloaded installers.
|
||||||
|
func CacheDir() string {
|
||||||
|
return firstWritable(filepath.Join(systemDataDir(), "cache"), filepath.Join(userDir("deployr"), "cache"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// CatalogDirs lists the directories scanned for catalog overlay files
|
||||||
|
// (*.yaml / *.yml), in increasing order of precedence.
|
||||||
|
func CatalogDirs() []string {
|
||||||
|
dirs := []string{filepath.Join(systemDataDir(), "catalog.d")}
|
||||||
|
if runtime.GOOS != "windows" {
|
||||||
|
dirs = append(dirs, "/etc/deployr/catalog.d")
|
||||||
|
}
|
||||||
|
dirs = append(dirs, filepath.Join(userDir("deployr"), "catalog.d"))
|
||||||
|
return dirs
|
||||||
|
}
|
||||||
|
|
||||||
|
func systemDataDir() string {
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "windows":
|
||||||
|
pd := os.Getenv("ProgramData")
|
||||||
|
if pd == "" {
|
||||||
|
pd = `C:\ProgramData`
|
||||||
|
}
|
||||||
|
return filepath.Join(pd, "Deployr")
|
||||||
|
case "darwin":
|
||||||
|
return "/Library/Application Support/Deployr"
|
||||||
|
default:
|
||||||
|
return "/var/lib/deployr"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func systemLogDir() string {
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "windows":
|
||||||
|
return filepath.Join(systemDataDir(), "logs")
|
||||||
|
case "darwin":
|
||||||
|
return "/Library/Logs/Deployr"
|
||||||
|
default:
|
||||||
|
return "/var/log/deployr"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func userDir(name string) string {
|
||||||
|
base, err := os.UserCacheDir()
|
||||||
|
if err != nil || base == "" {
|
||||||
|
base = os.TempDir()
|
||||||
|
}
|
||||||
|
return filepath.Join(base, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// firstWritable returns the first candidate directory that exists or can be
|
||||||
|
// created, falling back to the last candidate unconditionally.
|
||||||
|
func firstWritable(candidates ...string) string {
|
||||||
|
for i, dir := range candidates {
|
||||||
|
if dir == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(dir, 0o755); err == nil {
|
||||||
|
return dir
|
||||||
|
}
|
||||||
|
if i == len(candidates)-1 {
|
||||||
|
return dir
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return os.TempDir()
|
||||||
|
}
|
||||||
|
|
||||||
|
var winVar = regexp.MustCompile(`%([A-Za-z_][A-Za-z0-9_()]*)%`)
|
||||||
|
|
||||||
|
// ExpandPath resolves ~, $VAR/${VAR} and Windows-style %VAR% in a path.
|
||||||
|
// Unset variables expand to empty, matching shell behaviour.
|
||||||
|
func ExpandPath(p string) string {
|
||||||
|
if p == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(p, "~") {
|
||||||
|
if home, err := os.UserHomeDir(); err == nil {
|
||||||
|
p = filepath.Join(home, strings.TrimPrefix(p, "~"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p = winVar.ReplaceAllStringFunc(p, func(m string) string {
|
||||||
|
return os.Getenv(strings.Trim(m, "%"))
|
||||||
|
})
|
||||||
|
p = os.ExpandEnv(p)
|
||||||
|
return filepath.Clean(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PathExists reports whether a file or directory exists at the expanded path.
|
||||||
|
// Glob metacharacters are honoured so a catalog can match e.g.
|
||||||
|
// "%ProgramFiles%/Mozilla Firefox/firefox.exe".
|
||||||
|
func PathExists(p string) bool {
|
||||||
|
p = ExpandPath(p)
|
||||||
|
if p == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(p, "*?[") {
|
||||||
|
matches, err := filepath.Glob(p)
|
||||||
|
return err == nil && len(matches) > 0
|
||||||
|
}
|
||||||
|
_, err := os.Stat(p)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package platform
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExpandPathWindowsStyleVariables(t *testing.T) {
|
||||||
|
t.Setenv("DEPLOYR_TEST_DIR", filepath.Join("C:", "Apps"))
|
||||||
|
got := ExpandPath("%DEPLOYR_TEST_DIR%/tool/bin.exe")
|
||||||
|
want := filepath.Clean(filepath.Join("C:", "Apps", "tool", "bin.exe"))
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("ExpandPath = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpandPathUnixStyleVariables(t *testing.T) {
|
||||||
|
t.Setenv("DEPLOYR_TEST_DIR", filepath.Join("/opt", "apps"))
|
||||||
|
got := ExpandPath("$DEPLOYR_TEST_DIR/tool")
|
||||||
|
want := filepath.Clean(filepath.Join("/opt", "apps", "tool"))
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("ExpandPath = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Variable names with parentheses are common on Windows -- %ProgramFiles(x86)%
|
||||||
|
// is the one that matters -- so the expander has to accept them.
|
||||||
|
func TestExpandPathHandlesParenthesisedVariables(t *testing.T) {
|
||||||
|
t.Setenv("DEPLOYR_TEST(x86)", "/legacy")
|
||||||
|
got := ExpandPath("%DEPLOYR_TEST(x86)%/app")
|
||||||
|
if !strings.Contains(got, "legacy") {
|
||||||
|
t.Errorf("ExpandPath = %q, want it to contain the expanded value", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpandPathTilde(t *testing.T) {
|
||||||
|
home, err := os.UserHomeDir()
|
||||||
|
if err != nil {
|
||||||
|
t.Skip("no home directory in this environment")
|
||||||
|
}
|
||||||
|
if got := ExpandPath("~/deployr"); got != filepath.Clean(filepath.Join(home, "deployr")) {
|
||||||
|
t.Errorf("ExpandPath = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpandPathEmpty(t *testing.T) {
|
||||||
|
if got := ExpandPath(""); got != "" {
|
||||||
|
t.Errorf("ExpandPath(\"\") = %q, want an empty string", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPathExists(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
file := filepath.Join(dir, "present.txt")
|
||||||
|
if err := os.WriteFile(file, []byte("x"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !PathExists(file) {
|
||||||
|
t.Error("an existing file should be detected")
|
||||||
|
}
|
||||||
|
if PathExists(filepath.Join(dir, "absent.txt")) {
|
||||||
|
t.Error("a missing file should not be detected")
|
||||||
|
}
|
||||||
|
if !PathExists(filepath.Join(dir, "*.txt")) {
|
||||||
|
t.Error("a glob matching a file should be detected")
|
||||||
|
}
|
||||||
|
if PathExists(filepath.Join(dir, "*.log")) {
|
||||||
|
t.Error("a glob matching nothing should not be detected")
|
||||||
|
}
|
||||||
|
if PathExists("") {
|
||||||
|
t.Error("an empty path should not be detected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDirectoriesAreAbsolute(t *testing.T) {
|
||||||
|
for name, dir := range map[string]string{
|
||||||
|
"data": DataDir(),
|
||||||
|
"logs": LogDir(),
|
||||||
|
"cache": CacheDir(),
|
||||||
|
} {
|
||||||
|
if !filepath.IsAbs(dir) {
|
||||||
|
t.Errorf("%s dir %q is not absolute", name, dir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(CatalogDirs()) == 0 {
|
||||||
|
t.Error("there should be at least one catalog overlay directory")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSupported(t *testing.T) {
|
||||||
|
if !Supported() {
|
||||||
|
t.Errorf("%s should be a supported platform", runtime.GOOS)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/run"
|
||||||
|
)
|
||||||
|
|
||||||
|
// brew drives Homebrew, as either a formula ("brew") or a cask ("cask")
|
||||||
|
// provider. The two share every code path except the --cask flag.
|
||||||
|
type brew struct {
|
||||||
|
cask bool
|
||||||
|
|
||||||
|
once sync.Once
|
||||||
|
path string
|
||||||
|
user string // account to run brew as; empty means "the current user"
|
||||||
|
ok bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) Name() string {
|
||||||
|
if b.cask {
|
||||||
|
return "cask"
|
||||||
|
}
|
||||||
|
return "brew"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) OSes() []string {
|
||||||
|
if b.cask {
|
||||||
|
return []string{"darwin"}
|
||||||
|
}
|
||||||
|
return []string{"darwin", "linux"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) Label() string {
|
||||||
|
if b.cask {
|
||||||
|
return "Homebrew Cask"
|
||||||
|
}
|
||||||
|
return "Homebrew"
|
||||||
|
}
|
||||||
|
|
||||||
|
// brewPaths are the standard prefixes: Apple silicon, Intel macOS, and
|
||||||
|
// Linuxbrew. PATH is checked first for a non-standard install.
|
||||||
|
var brewPaths = []string{
|
||||||
|
"/opt/homebrew/bin/brew",
|
||||||
|
"/usr/local/bin/brew",
|
||||||
|
"/home/linuxbrew/.linuxbrew/bin/brew",
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolve locates brew and decides which account should run it. Homebrew
|
||||||
|
// refuses to run as root, so a root context (RMM, MDM, sudo) has to drop to the
|
||||||
|
// account that owns the Homebrew prefix. When there is no such account, this
|
||||||
|
// route is simply unavailable and the engine falls through to the next source.
|
||||||
|
func (b *brew) resolve() (string, string, bool) {
|
||||||
|
b.once.Do(func() {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p, found := run.Which("brew"); found {
|
||||||
|
b.path = p
|
||||||
|
} else {
|
||||||
|
for _, p := range brewPaths {
|
||||||
|
if _, err := os.Stat(p); err == nil {
|
||||||
|
b.path = p
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if b.path == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if os.Geteuid() != 0 {
|
||||||
|
b.ok = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Running as root: the owner of the brew binary is the account that
|
||||||
|
// installed it and the one whose permissions the cellar expects.
|
||||||
|
if owner, found := fileOwner(b.path); found && owner != "root" {
|
||||||
|
b.user, b.ok = owner, true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if u := platform.ConsoleUser(); u != "" {
|
||||||
|
b.user, b.ok = u, true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return b.path, b.user, b.ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) Available(context.Context, Opts) bool {
|
||||||
|
_, _, ok := b.resolve()
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||||
|
path, user, _ := b.resolve()
|
||||||
|
return run.Exec(ctx, run.Options{
|
||||||
|
Name: path,
|
||||||
|
Args: args,
|
||||||
|
AsUser: user,
|
||||||
|
Env: []string{
|
||||||
|
"NONINTERACTIVE=1",
|
||||||
|
"HOMEBREW_NO_ENV_HINTS=1",
|
||||||
|
"HOMEBREW_NO_ANALYTICS=1",
|
||||||
|
},
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
DryRun: o.DryRun,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// flag returns --cask for the cask provider, or nothing.
|
||||||
|
func (b *brew) flag() []string {
|
||||||
|
if b.cask {
|
||||||
|
return []string{"--cask"}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
args := append([]string{"install"}, b.flag()...)
|
||||||
|
args = append(args, src.ID)
|
||||||
|
args = append(args, src.Args...)
|
||||||
|
res := b.exec(ctx, o, args...)
|
||||||
|
return b.outcome(res, src, o, "install")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
args := append([]string{"upgrade"}, b.flag()...)
|
||||||
|
if b.cask {
|
||||||
|
// Casks whose app self-updates are skipped by default; --greedy is the
|
||||||
|
// only way a patching tool actually patches them.
|
||||||
|
args = append(args, "--greedy")
|
||||||
|
}
|
||||||
|
args = append(args, src.ID)
|
||||||
|
res := b.exec(ctx, o, args...)
|
||||||
|
return b.outcome(res, src, o, "upgrade")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
args := append([]string{"uninstall"}, b.flag()...)
|
||||||
|
args = append(args, src.ID)
|
||||||
|
res := b.exec(ctx, o, args...)
|
||||||
|
return b.outcome(res, src, o, "uninstall")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||||
|
args := append([]string{"list", "--versions"}, b.flag()...)
|
||||||
|
args = append(args, src.ID)
|
||||||
|
res := b.exec(ctx, o, args...)
|
||||||
|
if res.Failed() {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
fields := strings.Fields(res.Stdout)
|
||||||
|
if len(fields) >= 2 {
|
||||||
|
return fields[len(fields)-1], true
|
||||||
|
}
|
||||||
|
if len(fields) == 1 {
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) benign(res run.Result) bool {
|
||||||
|
for _, phrase := range []string{
|
||||||
|
"already installed",
|
||||||
|
"it seems there is already an app at",
|
||||||
|
"no available upgrade",
|
||||||
|
"already up-to-date",
|
||||||
|
} {
|
||||||
|
if res.Contains(phrase) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *brew) outcome(res run.Result, src catalog.Source, o Opts, verb string) (Outcome, error) {
|
||||||
|
if o.DryRun {
|
||||||
|
return Outcome{Message: "dry run"}, nil
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case !res.Failed():
|
||||||
|
if b.benign(res) {
|
||||||
|
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
case b.benign(res):
|
||||||
|
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||||
|
default:
|
||||||
|
return Outcome{}, fmt.Errorf("brew %s %s: %s", verb, src.ID, res.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,576 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/detect"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/download"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/run"
|
||||||
|
)
|
||||||
|
|
||||||
|
// direct installs straight from a vendor download. It is the fallback for
|
||||||
|
// software the native package managers handle badly or not at all, and the only
|
||||||
|
// route on a machine with no package manager configured.
|
||||||
|
type direct struct{}
|
||||||
|
|
||||||
|
func (d *direct) Name() string { return "direct" }
|
||||||
|
func (d *direct) OSes() []string { return []string{"windows", "darwin", "linux"} }
|
||||||
|
func (d *direct) Label() string { return "Direct vendor download" }
|
||||||
|
|
||||||
|
// Available is always true: there is no local tool to probe. A missing network
|
||||||
|
// surfaces as a download error, which is more useful than silently skipping.
|
||||||
|
func (d *direct) Available(context.Context, Opts) bool { return true }
|
||||||
|
|
||||||
|
func (d *direct) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
url := src.URLFor(o.Arch)
|
||||||
|
if url == "" {
|
||||||
|
return Outcome{}, fmt.Errorf("no download URL for %s/%s", runtime.GOOS, o.Arch)
|
||||||
|
}
|
||||||
|
kind := strings.ToLower(src.Kind)
|
||||||
|
if kind == "" {
|
||||||
|
kind = InferKind(url)
|
||||||
|
}
|
||||||
|
if kind == "" {
|
||||||
|
return Outcome{}, fmt.Errorf("cannot tell the installer type of %s; set `kind` in the catalog", url)
|
||||||
|
}
|
||||||
|
|
||||||
|
if o.DryRun {
|
||||||
|
if o.Log != nil {
|
||||||
|
o.Log.Debugf("would download %s (%s) and install it", url, kind)
|
||||||
|
}
|
||||||
|
return Outcome{Message: "dry run"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
path, err := download.Fetch(ctx, download.Options{
|
||||||
|
URL: url,
|
||||||
|
SHA256: src.SHA256,
|
||||||
|
Dir: o.CacheDir,
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
RequireChecksum: o.RequireChecksum,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return Outcome{}, err
|
||||||
|
}
|
||||||
|
if !o.KeepDownloads {
|
||||||
|
defer os.Remove(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "windows":
|
||||||
|
return d.installWindows(ctx, path, kind, src, o)
|
||||||
|
case "darwin":
|
||||||
|
return d.installDarwin(ctx, path, kind, src, o)
|
||||||
|
case "linux":
|
||||||
|
return d.installLinux(ctx, path, kind, src, o)
|
||||||
|
default:
|
||||||
|
return Outcome{}, fmt.Errorf("direct installs are not supported on %s", runtime.GOOS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update reinstalls from the catalog URL. Vendor "latest" links are evergreen,
|
||||||
|
// so a reinstall is how you patch anything that has no package manager behind
|
||||||
|
// it. Installers of this kind are in-place upgrades, not duplicates.
|
||||||
|
func (d *direct) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
return d.Install(ctx, src, o)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Query cannot report a version: the download tells us nothing about what is on
|
||||||
|
// disk. Presence and version come from the catalog's detect rules instead.
|
||||||
|
func (d *direct) Query(context.Context, catalog.Source, Opts) (string, bool) { return "", false }
|
||||||
|
|
||||||
|
// -------------------------------------------------------------- windows ---
|
||||||
|
|
||||||
|
func (d *direct) installWindows(ctx context.Context, path, kind string, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
var res run.Result
|
||||||
|
switch kind {
|
||||||
|
case "msi":
|
||||||
|
args := append([]string{"/i", path, "/qn", "/norestart"}, src.SilentArgs...)
|
||||||
|
res = run.Exec(ctx, run.Options{Name: "msiexec", Args: args, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
case "msu":
|
||||||
|
res = run.Exec(ctx, run.Options{Name: "wusa", Args: []string{path, "/quiet", "/norestart"}, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
case "exe":
|
||||||
|
if len(src.SilentArgs) == 0 {
|
||||||
|
// Running a bare vendor .exe would pop a wizard on someone's
|
||||||
|
// screen and then hang until the timeout. Refuse instead.
|
||||||
|
return Outcome{}, errors.New("exe installer needs silent_args in the catalog")
|
||||||
|
}
|
||||||
|
res = run.Exec(ctx, run.Options{Name: path, Args: src.SilentArgs, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
case "zip":
|
||||||
|
dest := platform.ExpandPath(src.Dest)
|
||||||
|
if dest == "" {
|
||||||
|
return Outcome{}, errors.New("zip payload needs a dest in the catalog")
|
||||||
|
}
|
||||||
|
if err := extractZip(path, dest); err != nil {
|
||||||
|
return Outcome{}, err
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
default:
|
||||||
|
return Outcome{}, fmt.Errorf("unsupported installer kind %q on windows", kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case !res.Failed():
|
||||||
|
return Outcome{}, nil
|
||||||
|
case isRebootExit(res.ExitCode):
|
||||||
|
return Outcome{RebootRequired: true}, nil
|
||||||
|
case res.ExitCode == 1618:
|
||||||
|
return Outcome{}, errors.New("another Windows installation is already in progress")
|
||||||
|
default:
|
||||||
|
return Outcome{}, fmt.Errorf("installer failed: %s", res.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------------------------------------------- darwin ---
|
||||||
|
|
||||||
|
func (d *direct) installDarwin(ctx context.Context, path, kind string, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
switch kind {
|
||||||
|
case "pkg":
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: "/usr/sbin/installer", Args: []string{"-pkg", path, "-target", "/"},
|
||||||
|
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("installer -pkg: %s", res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
|
||||||
|
case "dmg":
|
||||||
|
return d.installDMG(ctx, path, src, o)
|
||||||
|
|
||||||
|
case "zip":
|
||||||
|
dest := platform.ExpandPath(src.Dest)
|
||||||
|
if dest == "" {
|
||||||
|
dest = "/Applications"
|
||||||
|
}
|
||||||
|
// ditto preserves resource forks and code signatures; unzip does not.
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: "/usr/bin/ditto", Args: []string{"-x", "-k", path, dest},
|
||||||
|
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("ditto: %s", res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
|
||||||
|
case "tar.gz", "tgz":
|
||||||
|
return untar(ctx, path, src, o, "/usr/local")
|
||||||
|
|
||||||
|
default:
|
||||||
|
return Outcome{}, fmt.Errorf("unsupported installer kind %q on macOS", kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// installDMG mounts a disk image, installs whatever is inside it, and always
|
||||||
|
// detaches -- a leaked mount blocks the next run.
|
||||||
|
func (d *direct) installDMG(ctx context.Context, path string, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
mount, err := os.MkdirTemp("", "deployr-dmg-")
|
||||||
|
if err != nil {
|
||||||
|
return Outcome{}, err
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(mount)
|
||||||
|
|
||||||
|
attach := run.Exec(ctx, run.Options{
|
||||||
|
Name: "/usr/bin/hdiutil",
|
||||||
|
Args: []string{"attach", path, "-nobrowse", "-noverify", "-quiet", "-mountpoint", mount},
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
if attach.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("hdiutil attach: %s", attach.Error())
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
detachCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
run.Exec(detachCtx, run.Options{
|
||||||
|
Name: "/usr/bin/hdiutil", Args: []string{"detach", mount, "-quiet", "-force"}, Log: o.Log,
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
|
||||||
|
entries, err := os.ReadDir(mount)
|
||||||
|
if err != nil {
|
||||||
|
return Outcome{}, fmt.Errorf("read mounted image: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A .pkg inside the image is the vendor's own installer: prefer it.
|
||||||
|
for _, e := range entries {
|
||||||
|
if strings.HasSuffix(strings.ToLower(e.Name()), ".pkg") {
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: "/usr/sbin/installer", Args: []string{"-pkg", filepath.Join(mount, e.Name()), "-target", "/"},
|
||||||
|
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("installer -pkg: %s", res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
appName := src.AppName
|
||||||
|
if appName == "" {
|
||||||
|
for _, e := range entries {
|
||||||
|
if strings.HasSuffix(e.Name(), ".app") {
|
||||||
|
appName = e.Name()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if appName == "" {
|
||||||
|
return Outcome{}, errors.New("no .app or .pkg found in the disk image; set app_name in the catalog")
|
||||||
|
}
|
||||||
|
|
||||||
|
source := filepath.Join(mount, appName)
|
||||||
|
if _, err := os.Stat(source); err != nil {
|
||||||
|
return Outcome{}, fmt.Errorf("%s not found in the disk image", appName)
|
||||||
|
}
|
||||||
|
target := filepath.Join("/Applications", appName)
|
||||||
|
|
||||||
|
// ditto onto an existing bundle merges directories and leaves stale files
|
||||||
|
// behind, so replace it outright.
|
||||||
|
if _, err := os.Stat(target); err == nil {
|
||||||
|
rm := run.Exec(ctx, run.Options{Name: "/bin/rm", Args: []string{"-rf", target}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
if rm.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("replace %s: %s", target, rm.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: "/usr/bin/ditto", Args: []string{source, target},
|
||||||
|
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("copy %s: %s", appName, res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- linux ---
|
||||||
|
|
||||||
|
func (d *direct) installLinux(ctx context.Context, path, kind string, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
switch kind {
|
||||||
|
case "deb":
|
||||||
|
// apt-get resolves the dependencies dpkg -i would leave broken.
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: "apt-get", Args: append(append([]string{"install", "-y"}, aptConfArgs...), path),
|
||||||
|
Env: aptEnv, NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("apt-get install %s: %s", filepath.Base(path), res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
|
||||||
|
case "rpm":
|
||||||
|
for _, mgr := range []struct {
|
||||||
|
bin string
|
||||||
|
args []string
|
||||||
|
}{
|
||||||
|
{"dnf", []string{"install", "-y", path}},
|
||||||
|
{"zypper", []string{"--non-interactive", "install", "--allow-unsigned-rpm", path}},
|
||||||
|
{"yum", []string{"install", "-y", path}},
|
||||||
|
{"rpm", []string{"-Uvh", path}},
|
||||||
|
} {
|
||||||
|
if !run.Available(mgr.bin) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
res := run.Exec(ctx, run.Options{Name: mgr.bin, Args: mgr.args, NeedRoot: true, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
if res.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("%s install: %s", mgr.bin, res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
}
|
||||||
|
return Outcome{}, errors.New("no RPM-capable package manager found")
|
||||||
|
|
||||||
|
case "sh", "run":
|
||||||
|
if err := os.Chmod(path, 0o755); err != nil {
|
||||||
|
return Outcome{}, err
|
||||||
|
}
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: "/bin/sh", Args: append([]string{path}, src.SilentArgs...),
|
||||||
|
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("install script: %s", res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
|
||||||
|
case "appimage":
|
||||||
|
dest := platform.ExpandPath(src.Dest)
|
||||||
|
if dest == "" {
|
||||||
|
dest = filepath.Join("/usr/local/bin", strings.TrimSuffix(src.ID, ".AppImage"))
|
||||||
|
}
|
||||||
|
if err := copyFile(path, dest, 0o755); err != nil {
|
||||||
|
return Outcome{}, err
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
|
||||||
|
case "zip":
|
||||||
|
dest := platform.ExpandPath(src.Dest)
|
||||||
|
if dest == "" {
|
||||||
|
return Outcome{}, errors.New("zip payload needs a dest in the catalog")
|
||||||
|
}
|
||||||
|
if err := extractZip(path, dest); err != nil {
|
||||||
|
return Outcome{}, err
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
|
||||||
|
case "tar.gz", "tgz":
|
||||||
|
return untar(ctx, path, src, o, "/usr/local")
|
||||||
|
|
||||||
|
default:
|
||||||
|
return Outcome{}, fmt.Errorf("unsupported installer kind %q on linux", kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func untar(ctx context.Context, path string, src catalog.Source, o Opts, fallbackDest string) (Outcome, error) {
|
||||||
|
dest := platform.ExpandPath(src.Dest)
|
||||||
|
if dest == "" {
|
||||||
|
dest = fallbackDest
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(dest, 0o755); err != nil {
|
||||||
|
return Outcome{}, err
|
||||||
|
}
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: "tar", Args: []string{"-xzf", path, "-C", dest},
|
||||||
|
NeedRoot: true, Timeout: o.Timeout, Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("tar: %s", res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ uninstall ---
|
||||||
|
|
||||||
|
func (d *direct) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
if o.DryRun {
|
||||||
|
return Outcome{Message: "dry run"}, nil
|
||||||
|
}
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "windows":
|
||||||
|
return d.uninstallWindows(ctx, src, o)
|
||||||
|
case "darwin":
|
||||||
|
name := src.AppName
|
||||||
|
if name == "" {
|
||||||
|
return Outcome{}, errors.New("no app_name in the catalog; remove this app manually")
|
||||||
|
}
|
||||||
|
target := filepath.Join("/Applications", name)
|
||||||
|
if _, err := os.Stat(target); err != nil {
|
||||||
|
return Outcome{NoOp: true, Message: "not installed"}, nil
|
||||||
|
}
|
||||||
|
res := run.Exec(ctx, run.Options{Name: "/bin/rm", Args: []string{"-rf", target}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
if res.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("remove %s: %s", target, res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
default:
|
||||||
|
pkg := src.UninstallID
|
||||||
|
if pkg == "" {
|
||||||
|
return Outcome{}, errors.New("no uninstall_id in the catalog; remove this app manually")
|
||||||
|
}
|
||||||
|
for _, mgr := range [][]string{
|
||||||
|
{"apt-get", "remove", "-y", pkg},
|
||||||
|
{"dnf", "remove", "-y", pkg},
|
||||||
|
{"zypper", "--non-interactive", "remove", pkg},
|
||||||
|
} {
|
||||||
|
if !run.Available(mgr[0]) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
res := run.Exec(ctx, run.Options{Name: mgr[0], Args: mgr[1:], Env: aptEnv, NeedRoot: true, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
if res.Failed() {
|
||||||
|
return Outcome{}, fmt.Errorf("%s: %s", mgr[0], res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
}
|
||||||
|
return Outcome{}, errors.New("no package manager available to remove this app")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// uninstallWindows finds the app's uninstall registry entry -- which exists no
|
||||||
|
// matter how it was installed -- and runs it silently.
|
||||||
|
func (d *direct) uninstallWindows(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
patterns := o.Detect.Registry
|
||||||
|
if src.UninstallID != "" {
|
||||||
|
patterns = append([]string{src.UninstallID}, patterns...)
|
||||||
|
}
|
||||||
|
entry, ok := detect.FindRegistry(patterns)
|
||||||
|
if !ok {
|
||||||
|
return Outcome{NoOp: true, Message: "no uninstall entry found"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if guid, isMSI := msiProductCode(entry.UninstallString); isMSI {
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: "msiexec", Args: []string{"/x", guid, "/qn", "/norestart"},
|
||||||
|
Timeout: o.Timeout, Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() && !isRebootExit(res.ExitCode) {
|
||||||
|
return Outcome{}, fmt.Errorf("msiexec /x: %s", res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{RebootRequired: isRebootExit(res.ExitCode)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
cmdline := entry.QuietUninstallString
|
||||||
|
if cmdline == "" {
|
||||||
|
// Without a quiet string the vendor uninstaller would open a window on
|
||||||
|
// the user's desktop and wait. That is worse than reporting failure.
|
||||||
|
return Outcome{}, fmt.Errorf("%s has no silent uninstall command; remove it manually", entry.DisplayName)
|
||||||
|
}
|
||||||
|
name, args := splitCommandLine(cmdline)
|
||||||
|
if name == "" {
|
||||||
|
return Outcome{}, fmt.Errorf("cannot parse uninstall command %q", cmdline)
|
||||||
|
}
|
||||||
|
res := run.Exec(ctx, run.Options{Name: name, Args: args, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
if res.Failed() && !isRebootExit(res.ExitCode) {
|
||||||
|
return Outcome{}, fmt.Errorf("uninstall %s: %s", entry.DisplayName, res.Error())
|
||||||
|
}
|
||||||
|
return Outcome{RebootRequired: isRebootExit(res.ExitCode)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// msiProductCode extracts the {GUID} from an MSI uninstall string such as
|
||||||
|
// `MsiExec.exe /I{90160000-008C-0000-1000-0000000FF1CE}`.
|
||||||
|
func msiProductCode(uninstall string) (string, bool) {
|
||||||
|
if !strings.Contains(strings.ToLower(uninstall), "msiexec") {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
start := strings.Index(uninstall, "{")
|
||||||
|
end := strings.Index(uninstall, "}")
|
||||||
|
if start < 0 || end < start {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return uninstall[start : end+1], true
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitCommandLine splits a Windows command line into program and arguments,
|
||||||
|
// honouring double quotes around paths with spaces.
|
||||||
|
func splitCommandLine(s string) (string, []string) {
|
||||||
|
var parts []string
|
||||||
|
var cur strings.Builder
|
||||||
|
inQuote := false
|
||||||
|
for _, r := range s {
|
||||||
|
switch {
|
||||||
|
case r == '"':
|
||||||
|
inQuote = !inQuote
|
||||||
|
case (r == ' ' || r == '\t') && !inQuote:
|
||||||
|
if cur.Len() > 0 {
|
||||||
|
parts = append(parts, cur.String())
|
||||||
|
cur.Reset()
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
cur.WriteRune(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cur.Len() > 0 {
|
||||||
|
parts = append(parts, cur.String())
|
||||||
|
}
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
return parts[0], parts[1:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------- misc ---
|
||||||
|
|
||||||
|
// InferKind guesses the installer format from the URL file extension. It is
|
||||||
|
// exported so a catalog test can check that every direct source resolves to a
|
||||||
|
// kind deployr knows how to install.
|
||||||
|
func InferKind(rawURL string) string {
|
||||||
|
lower := strings.ToLower(rawURL)
|
||||||
|
if i := strings.IndexAny(lower, "?#"); i >= 0 {
|
||||||
|
lower = lower[:i]
|
||||||
|
}
|
||||||
|
for _, ext := range []string{".tar.gz", ".tgz", ".msi", ".msu", ".exe", ".dmg", ".pkg", ".deb", ".rpm", ".zip", ".appimage"} {
|
||||||
|
if strings.HasSuffix(lower, ext) {
|
||||||
|
switch ext {
|
||||||
|
case ".tgz":
|
||||||
|
return "tar.gz"
|
||||||
|
case ".appimage":
|
||||||
|
return "appimage"
|
||||||
|
default:
|
||||||
|
return strings.TrimPrefix(ext, ".")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyFile(src, dest string, mode os.FileMode) error {
|
||||||
|
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
in, err := os.Open(src)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer in.Close()
|
||||||
|
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := io.Copy(out, in); err != nil {
|
||||||
|
out.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return out.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// extractZip unpacks an archive, rejecting entries that would escape the
|
||||||
|
// destination directory (zip slip).
|
||||||
|
func extractZip(archive, dest string) error {
|
||||||
|
r, err := zip.OpenReader(archive)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("open %s: %w", archive, err)
|
||||||
|
}
|
||||||
|
defer r.Close()
|
||||||
|
|
||||||
|
if err := os.MkdirAll(dest, 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
root, err := filepath.Abs(dest)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, f := range r.File {
|
||||||
|
target := filepath.Join(root, filepath.FromSlash(f.Name))
|
||||||
|
if !strings.HasPrefix(target, root+string(os.PathSeparator)) && target != root {
|
||||||
|
return fmt.Errorf("refusing to extract %q outside %s", f.Name, dest)
|
||||||
|
}
|
||||||
|
if f.FileInfo().IsDir() {
|
||||||
|
if err := os.MkdirAll(target, 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rc, err := f.Open()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, f.Mode()|0o200)
|
||||||
|
if err != nil {
|
||||||
|
rc.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, copyErr := io.Copy(out, rc)
|
||||||
|
rc.Close()
|
||||||
|
closeErr := out.Close()
|
||||||
|
if copyErr != nil {
|
||||||
|
return copyErr
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
return closeErr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,395 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/run"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------- apt ---
|
||||||
|
|
||||||
|
type apt struct {
|
||||||
|
refreshOnce sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func newApt() *apt { return &apt{} }
|
||||||
|
|
||||||
|
func (a *apt) Name() string { return "apt" }
|
||||||
|
func (a *apt) OSes() []string { return []string{"linux"} }
|
||||||
|
func (a *apt) Label() string { return "APT (Debian/Ubuntu)" }
|
||||||
|
|
||||||
|
func (a *apt) Available(context.Context, Opts) bool {
|
||||||
|
return runtime.GOOS == "linux" && run.Available("apt-get")
|
||||||
|
}
|
||||||
|
|
||||||
|
// aptEnv keeps dpkg from opening a curses prompt and from asking about changed
|
||||||
|
// config files -- either one hangs an unattended run forever.
|
||||||
|
var aptEnv = []string{"DEBIAN_FRONTEND=noninteractive", "APT_LISTCHANGES_FRONTEND=none"}
|
||||||
|
|
||||||
|
var aptConfArgs = []string{
|
||||||
|
"-o", "Dpkg::Options::=--force-confdef",
|
||||||
|
"-o", "Dpkg::Options::=--force-confold",
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *apt) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||||
|
return run.Exec(ctx, run.Options{
|
||||||
|
Name: "apt-get",
|
||||||
|
Args: args,
|
||||||
|
Env: aptEnv,
|
||||||
|
NeedRoot: true,
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
DryRun: o.DryRun,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// refresh updates the package index once per process. A stale index is the most
|
||||||
|
// common reason an install fails on a machine that has been off for a while.
|
||||||
|
func (a *apt) refresh(ctx context.Context, o Opts) {
|
||||||
|
a.refreshOnce.Do(func() {
|
||||||
|
if o.DryRun {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if res := a.exec(ctx, o, "update", "-qq"); res.Failed() && o.Log != nil {
|
||||||
|
o.Log.Debugf("apt-get update failed (continuing): %s", res.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *apt) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
a.refresh(ctx, o)
|
||||||
|
args := append([]string{"install", "-y"}, aptConfArgs...)
|
||||||
|
args = append(args, src.ID)
|
||||||
|
args = append(args, src.Args...)
|
||||||
|
res := a.exec(ctx, o, args...)
|
||||||
|
return simpleOutcome(res, o, "apt-get install", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *apt) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
a.refresh(ctx, o)
|
||||||
|
args := append([]string{"install", "--only-upgrade", "-y"}, aptConfArgs...)
|
||||||
|
args = append(args, src.ID)
|
||||||
|
res := a.exec(ctx, o, args...)
|
||||||
|
return simpleOutcome(res, o, "apt-get upgrade", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *apt) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := a.exec(ctx, o, "remove", "-y", src.ID)
|
||||||
|
return simpleOutcome(res, o, "apt-get remove", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *apt) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: "dpkg-query",
|
||||||
|
Args: []string{"-W", "-f=${Version}", src.ID},
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() || strings.TrimSpace(res.Stdout) == "" {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(res.Stdout), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ dnf/zypper ---
|
||||||
|
|
||||||
|
// rpmMgr covers the RPM-family managers, which differ only in their
|
||||||
|
// non-interactive switch and subcommand names.
|
||||||
|
type rpmMgr struct {
|
||||||
|
name string // provider name: dnf or zypper
|
||||||
|
bins []string // candidate executables, in preference order
|
||||||
|
|
||||||
|
once sync.Once
|
||||||
|
bin string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rpmMgr) Name() string { return r.name }
|
||||||
|
func (r *rpmMgr) OSes() []string { return []string{"linux"} }
|
||||||
|
|
||||||
|
func (r *rpmMgr) Label() string {
|
||||||
|
if r.name == "zypper" {
|
||||||
|
return "Zypper (openSUSE)"
|
||||||
|
}
|
||||||
|
return "DNF/YUM (Fedora/RHEL)"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rpmMgr) resolve() string {
|
||||||
|
r.once.Do(func() {
|
||||||
|
if runtime.GOOS != "linux" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, b := range r.bins {
|
||||||
|
if run.Available(b) {
|
||||||
|
r.bin = b
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return r.bin
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rpmMgr) Available(context.Context, Opts) bool { return r.resolve() != "" }
|
||||||
|
|
||||||
|
func (r *rpmMgr) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||||
|
if r.name == "zypper" {
|
||||||
|
args = append([]string{"--non-interactive"}, args...)
|
||||||
|
} else {
|
||||||
|
args = append(args, "-y")
|
||||||
|
}
|
||||||
|
return run.Exec(ctx, run.Options{
|
||||||
|
Name: r.resolve(),
|
||||||
|
Args: args,
|
||||||
|
NeedRoot: true,
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
DryRun: o.DryRun,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rpmMgr) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := r.exec(ctx, o, append([]string{"install", src.ID}, src.Args...)...)
|
||||||
|
return simpleOutcome(res, o, r.name+" install", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rpmMgr) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
verb := "upgrade"
|
||||||
|
if r.name == "zypper" {
|
||||||
|
verb = "update"
|
||||||
|
}
|
||||||
|
res := r.exec(ctx, o, verb, src.ID)
|
||||||
|
return simpleOutcome(res, o, r.name+" "+verb, src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rpmMgr) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := r.exec(ctx, o, "remove", src.ID)
|
||||||
|
return simpleOutcome(res, o, r.name+" remove", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rpmMgr) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: "rpm",
|
||||||
|
Args: []string{"-q", "--qf", "%{VERSION}-%{RELEASE}", src.ID},
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() || strings.TrimSpace(res.Stdout) == "" {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(res.Stdout), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- pacman ---
|
||||||
|
|
||||||
|
type pacman struct{}
|
||||||
|
|
||||||
|
func (p *pacman) Name() string { return "pacman" }
|
||||||
|
func (p *pacman) OSes() []string { return []string{"linux"} }
|
||||||
|
func (p *pacman) Label() string { return "pacman (Arch)" }
|
||||||
|
|
||||||
|
func (p *pacman) Available(context.Context, Opts) bool {
|
||||||
|
return runtime.GOOS == "linux" && run.Available("pacman")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pacman) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||||
|
return run.Exec(ctx, run.Options{
|
||||||
|
Name: "pacman",
|
||||||
|
Args: args,
|
||||||
|
NeedRoot: true,
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
DryRun: o.DryRun,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pacman) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := p.exec(ctx, o, append([]string{"-S", "--noconfirm", "--needed", src.ID}, src.Args...)...)
|
||||||
|
return simpleOutcome(res, o, "pacman -S", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pacman) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
// Arch does not support upgrading a single package against a stale index;
|
||||||
|
// -Syu with a target is the supported way to avoid a partial upgrade.
|
||||||
|
res := p.exec(ctx, o, "-Syu", "--noconfirm", src.ID)
|
||||||
|
return simpleOutcome(res, o, "pacman -Syu", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pacman) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := p.exec(ctx, o, "-Rns", "--noconfirm", src.ID)
|
||||||
|
return simpleOutcome(res, o, "pacman -Rns", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pacman) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||||
|
res := run.Exec(ctx, run.Options{Name: "pacman", Args: []string{"-Q", src.ID}, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
if res.Failed() {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
fields := strings.Fields(res.Stdout)
|
||||||
|
if len(fields) >= 2 {
|
||||||
|
return fields[1], true
|
||||||
|
}
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------------------------------------------- flatpak ---
|
||||||
|
|
||||||
|
type flatpak struct{}
|
||||||
|
|
||||||
|
func (f *flatpak) Name() string { return "flatpak" }
|
||||||
|
func (f *flatpak) OSes() []string { return []string{"linux"} }
|
||||||
|
func (f *flatpak) Label() string { return "Flatpak" }
|
||||||
|
|
||||||
|
func (f *flatpak) Available(context.Context, Opts) bool {
|
||||||
|
return runtime.GOOS == "linux" && run.Available("flatpak")
|
||||||
|
}
|
||||||
|
|
||||||
|
// scope installs system-wide when we have root and per-user otherwise, so an
|
||||||
|
// unprivileged run still succeeds instead of erroring out.
|
||||||
|
func (f *flatpak) scope() string {
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
return "--system"
|
||||||
|
}
|
||||||
|
return "--user"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flatpak) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||||
|
return run.Exec(ctx, run.Options{
|
||||||
|
Name: "flatpak",
|
||||||
|
Args: args,
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
DryRun: o.DryRun,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flatpak) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
repo := src.Repo
|
||||||
|
if repo == "" {
|
||||||
|
repo = "flathub"
|
||||||
|
}
|
||||||
|
args := []string{"install", f.scope(), "-y", "--noninteractive", repo, src.ID}
|
||||||
|
res := f.exec(ctx, o, append(args, src.Args...)...)
|
||||||
|
return simpleOutcome(res, o, "flatpak install", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flatpak) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := f.exec(ctx, o, "update", f.scope(), "-y", "--noninteractive", src.ID)
|
||||||
|
return simpleOutcome(res, o, "flatpak update", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flatpak) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := f.exec(ctx, o, "uninstall", f.scope(), "-y", "--noninteractive", src.ID)
|
||||||
|
return simpleOutcome(res, o, "flatpak uninstall", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flatpak) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||||
|
res := f.exec(ctx, o, "info", src.ID)
|
||||||
|
if res.Failed() {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
for _, line := range strings.Split(res.Stdout, "\n") {
|
||||||
|
if strings.HasPrefix(strings.TrimSpace(line), "Version:") {
|
||||||
|
return strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "Version:")), true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ snap ---
|
||||||
|
|
||||||
|
type snap struct{}
|
||||||
|
|
||||||
|
func (s *snap) Name() string { return "snap" }
|
||||||
|
func (s *snap) OSes() []string { return []string{"linux"} }
|
||||||
|
func (s *snap) Label() string { return "Snap" }
|
||||||
|
|
||||||
|
func (s *snap) Available(context.Context, Opts) bool {
|
||||||
|
return runtime.GOOS == "linux" && run.Available("snap")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *snap) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||||
|
return run.Exec(ctx, run.Options{
|
||||||
|
Name: "snap",
|
||||||
|
Args: args,
|
||||||
|
NeedRoot: true,
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
DryRun: o.DryRun,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *snap) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := s.exec(ctx, o, append([]string{"install", src.ID}, src.Args...)...)
|
||||||
|
return simpleOutcome(res, o, "snap install", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *snap) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := s.exec(ctx, o, "refresh", src.ID)
|
||||||
|
return simpleOutcome(res, o, "snap refresh", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *snap) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := s.exec(ctx, o, "remove", src.ID)
|
||||||
|
return simpleOutcome(res, o, "snap remove", src.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *snap) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||||
|
res := run.Exec(ctx, run.Options{Name: "snap", Args: []string{"list", src.ID}, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
if res.Failed() {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
lines := strings.Split(strings.TrimSpace(res.Stdout), "\n")
|
||||||
|
if len(lines) < 2 {
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
fields := strings.Fields(lines[1])
|
||||||
|
if len(fields) >= 2 {
|
||||||
|
return fields[1], true
|
||||||
|
}
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------------------------------------------- shared ---
|
||||||
|
|
||||||
|
// noOpPhrases are the ways the Linux managers say "there was nothing to do".
|
||||||
|
var noOpPhrases = []string{
|
||||||
|
"is already the newest version",
|
||||||
|
"nothing to do",
|
||||||
|
"no packages marked for update",
|
||||||
|
"nothing to upgrade",
|
||||||
|
"is already installed",
|
||||||
|
"reinstalling",
|
||||||
|
"no updates available",
|
||||||
|
"already installed",
|
||||||
|
}
|
||||||
|
|
||||||
|
// simpleOutcome maps a package manager result onto an Outcome, treating
|
||||||
|
// "nothing to do" as success rather than an error.
|
||||||
|
func simpleOutcome(res run.Result, o Opts, what, id string) (Outcome, error) {
|
||||||
|
if o.DryRun {
|
||||||
|
return Outcome{Message: "dry run"}, nil
|
||||||
|
}
|
||||||
|
noop := false
|
||||||
|
for _, phrase := range noOpPhrases {
|
||||||
|
if res.Contains(phrase) {
|
||||||
|
noop = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case !res.Failed():
|
||||||
|
if noop {
|
||||||
|
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||||
|
}
|
||||||
|
return Outcome{}, nil
|
||||||
|
case noop:
|
||||||
|
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||||
|
default:
|
||||||
|
return Outcome{}, fmt.Errorf("%s %s: %s", what, id, res.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"os/user"
|
||||||
|
"strconv"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fileOwner returns the account name that owns path.
|
||||||
|
func fileOwner(path string) (string, bool) {
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||||
|
if !ok {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
u, err := user.LookupId(strconv.FormatUint(uint64(stat.Uid), 10))
|
||||||
|
if err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return u.Username, true
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
// fileOwner is only meaningful for the Unix privilege-dropping path.
|
||||||
|
func fileOwner(string) (string, bool) { return "", false }
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
// Package provider wraps the package managers and installer formats deployr can
|
||||||
|
// drive. Every provider answers the same five questions — am I present, can I
|
||||||
|
// install, update, uninstall, and what version is here — so the engine can walk
|
||||||
|
// a catalog entry's sources without caring which route wins.
|
||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/logx"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Opts is the ambient configuration for a provider operation.
|
||||||
|
type Opts struct {
|
||||||
|
DryRun bool
|
||||||
|
Timeout time.Duration
|
||||||
|
Log *logx.Logger
|
||||||
|
CacheDir string
|
||||||
|
Arch string
|
||||||
|
RequireChecksum bool
|
||||||
|
// Detect carries the app's presence rules, which the direct provider needs
|
||||||
|
// to locate an uninstall entry it did not create.
|
||||||
|
Detect catalog.Detect
|
||||||
|
// KeepDownloads leaves fetched installers in the cache directory.
|
||||||
|
KeepDownloads bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Outcome describes what a provider actually did.
|
||||||
|
type Outcome struct {
|
||||||
|
// Version installed, when the provider can report it.
|
||||||
|
Version string
|
||||||
|
// RebootRequired is set when the installer returned 3010/1641.
|
||||||
|
RebootRequired bool
|
||||||
|
// NoOp is set when the request was already satisfied.
|
||||||
|
NoOp bool
|
||||||
|
// Message is a short human explanation, e.g. "already up to date".
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Provider is one install route.
|
||||||
|
type Provider interface {
|
||||||
|
// Name is the identifier used in catalog sources.
|
||||||
|
Name() string
|
||||||
|
// OSes lists the GOOS values this provider can operate on.
|
||||||
|
OSes() []string
|
||||||
|
// Label is a human description for `deployr doctor`.
|
||||||
|
Label() string
|
||||||
|
// Available reports whether this route is usable on this machine right now.
|
||||||
|
Available(ctx context.Context, o Opts) bool
|
||||||
|
// Install makes the package present.
|
||||||
|
Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error)
|
||||||
|
// Update brings an installed package to the latest version.
|
||||||
|
Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error)
|
||||||
|
// Uninstall removes the package.
|
||||||
|
Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error)
|
||||||
|
// Query returns the version this provider believes is installed.
|
||||||
|
Query(ctx context.Context, src catalog.Source, o Opts) (string, bool)
|
||||||
|
}
|
||||||
|
|
||||||
|
var registry = map[string]Provider{}
|
||||||
|
|
||||||
|
func register(p Provider) { registry[p.Name()] = p }
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
register(&winget{})
|
||||||
|
register(&choco{})
|
||||||
|
register(&brew{cask: false})
|
||||||
|
register(&brew{cask: true})
|
||||||
|
register(newApt())
|
||||||
|
register(&rpmMgr{name: "dnf", bins: []string{"dnf5", "dnf", "yum"}})
|
||||||
|
register(&rpmMgr{name: "zypper", bins: []string{"zypper"}})
|
||||||
|
register(&pacman{})
|
||||||
|
register(&flatpak{})
|
||||||
|
register(&snap{})
|
||||||
|
register(&direct{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns the provider registered under name.
|
||||||
|
func Get(name string) (Provider, bool) {
|
||||||
|
p, ok := registry[strings.ToLower(strings.TrimSpace(name))]
|
||||||
|
return p, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// All returns every provider, sorted by name.
|
||||||
|
func All() []Provider {
|
||||||
|
out := make([]Provider, 0, len(registry))
|
||||||
|
for _, p := range registry {
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
sort.Slice(out, func(i, j int) bool { return out[i].Name() < out[j].Name() })
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ForOS returns the providers that can run on a GOOS, sorted by name.
|
||||||
|
func ForOS(goos string) []Provider {
|
||||||
|
var out []Provider
|
||||||
|
for _, p := range All() {
|
||||||
|
for _, os := range p.OSes() {
|
||||||
|
if os == goos {
|
||||||
|
out = append(out, p)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Names lists every registered provider name.
|
||||||
|
func Names() []string {
|
||||||
|
out := make([]string, 0, len(registry))
|
||||||
|
for name := range registry {
|
||||||
|
out = append(out, name)
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Windows installers signal "done, but reboot" rather than failing.
|
||||||
|
const (
|
||||||
|
exitRebootInitiated = 1641
|
||||||
|
exitRebootRequired = 3010
|
||||||
|
)
|
||||||
|
|
||||||
|
func isRebootExit(code int) bool {
|
||||||
|
return code == exitRebootInitiated || code == exitRebootRequired
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInferKind(t *testing.T) {
|
||||||
|
cases := map[string]string{
|
||||||
|
"https://x.test/setup.msi": "msi",
|
||||||
|
"https://x.test/setup.EXE": "exe",
|
||||||
|
"https://x.test/app.dmg": "dmg",
|
||||||
|
"https://x.test/app.pkg": "pkg",
|
||||||
|
"https://x.test/app_amd64.deb": "deb",
|
||||||
|
"https://x.test/app.x86_64.rpm": "rpm",
|
||||||
|
"https://x.test/tool.zip": "zip",
|
||||||
|
"https://x.test/tool.tar.gz": "tar.gz",
|
||||||
|
"https://x.test/tool.tgz": "tar.gz",
|
||||||
|
"https://x.test/Tool-1.2.AppImage": "appimage",
|
||||||
|
"https://x.test/download?product=firefox&os=win64": "",
|
||||||
|
// The extension has to be in the path, not the query string: a
|
||||||
|
// download endpoint that merely mentions .msi in a parameter tells us
|
||||||
|
// nothing reliable, and such entries must set `kind` explicitly.
|
||||||
|
"https://download.mozilla.org/?product=firefox-msi-latest-ssl": "",
|
||||||
|
"https://x.test/setup.msi?token=abc#frag": "msi",
|
||||||
|
}
|
||||||
|
for url, want := range cases {
|
||||||
|
if got := InferKind(url); got != want {
|
||||||
|
t.Errorf("InferKind(%q) = %q, want %q", url, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMSIProductCode(t *testing.T) {
|
||||||
|
guid, ok := msiProductCode(`MsiExec.exe /I{90160000-008C-0000-1000-0000000FF1CE}`)
|
||||||
|
if !ok || guid != "{90160000-008C-0000-1000-0000000FF1CE}" {
|
||||||
|
t.Errorf("got %q, %v", guid, ok)
|
||||||
|
}
|
||||||
|
if _, ok := msiProductCode(`"C:\Program Files\App\uninstall.exe" /S`); ok {
|
||||||
|
t.Error("a non-MSI uninstall string should not yield a product code")
|
||||||
|
}
|
||||||
|
if _, ok := msiProductCode("MsiExec.exe /I no-braces"); ok {
|
||||||
|
t.Error("a malformed MSI string should not yield a product code")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSplitCommandLine(t *testing.T) {
|
||||||
|
name, args := splitCommandLine(`"C:\Program Files\App\uninst.exe" /S /norestart`)
|
||||||
|
if name != `C:\Program Files\App\uninst.exe` {
|
||||||
|
t.Errorf("name = %q", name)
|
||||||
|
}
|
||||||
|
if len(args) != 2 || args[0] != "/S" || args[1] != "/norestart" {
|
||||||
|
t.Errorf("args = %v", args)
|
||||||
|
}
|
||||||
|
|
||||||
|
if name, args := splitCommandLine("uninst.exe"); name != "uninst.exe" || len(args) != 0 {
|
||||||
|
t.Errorf("bare command parsed as %q %v", name, args)
|
||||||
|
}
|
||||||
|
if name, _ := splitCommandLine(" "); name != "" {
|
||||||
|
t.Errorf("blank command line parsed as %q", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWingetListVersion(t *testing.T) {
|
||||||
|
out := "Name Id Version Available Source\n" +
|
||||||
|
"-----------------------------------------------------------------\n" +
|
||||||
|
"Google Chrome Google.Chrome 129.0.6668.90 winget\n"
|
||||||
|
if got := wingetListVersion(out, "Google.Chrome"); got != "129.0.6668.90" {
|
||||||
|
t.Errorf("version = %q", got)
|
||||||
|
}
|
||||||
|
if got := wingetListVersion(out, "Mozilla.Firefox"); got != "" {
|
||||||
|
t.Errorf("expected no version for an absent id, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExtractZipRejectsPathTraversal(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
archive := filepath.Join(dir, "evil.zip")
|
||||||
|
|
||||||
|
f, err := os.Create(archive)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
zw := zip.NewWriter(f)
|
||||||
|
w, err := zw.Create("../escaped.txt")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := w.Write([]byte("nope")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := zw.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
f.Close()
|
||||||
|
|
||||||
|
dest := filepath.Join(dir, "out")
|
||||||
|
if err := extractZip(archive, dest); err == nil {
|
||||||
|
t.Fatal("expected extractZip to refuse an entry outside the destination")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, "escaped.txt")); err == nil {
|
||||||
|
t.Fatal("a file escaped the destination directory")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExtractZipWritesFiles(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
archive := filepath.Join(dir, "good.zip")
|
||||||
|
|
||||||
|
f, err := os.Create(archive)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
zw := zip.NewWriter(f)
|
||||||
|
w, err := zw.Create("bin/tool.txt")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := w.Write([]byte("hello")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := zw.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
f.Close()
|
||||||
|
|
||||||
|
dest := filepath.Join(dir, "out")
|
||||||
|
if err := extractZip(archive, dest); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := os.ReadFile(filepath.Join(dest, "bin", "tool.txt"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(got) != "hello" {
|
||||||
|
t.Errorf("content = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRegistryCoversEveryCatalogProvider makes sure a provider named in the
|
||||||
|
// catalog can actually be looked up, and that the OS lists are sane.
|
||||||
|
func TestRegistryIsConsistent(t *testing.T) {
|
||||||
|
for _, name := range Names() {
|
||||||
|
p, ok := Get(name)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("Names() returned %q but Get() does not know it", name)
|
||||||
|
}
|
||||||
|
if p.Name() != name {
|
||||||
|
t.Errorf("provider registered as %q reports Name() = %q", name, p.Name())
|
||||||
|
}
|
||||||
|
if len(p.OSes()) == 0 {
|
||||||
|
t.Errorf("provider %q supports no operating systems", name)
|
||||||
|
}
|
||||||
|
if p.Label() == "" {
|
||||||
|
t.Errorf("provider %q has no label", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestForOSFiltersByPlatform(t *testing.T) {
|
||||||
|
for _, goos := range []string{"windows", "darwin", "linux"} {
|
||||||
|
providers := ForOS(goos)
|
||||||
|
if len(providers) == 0 {
|
||||||
|
t.Errorf("no providers for %s", goos)
|
||||||
|
}
|
||||||
|
for _, p := range providers {
|
||||||
|
found := false
|
||||||
|
for _, os := range p.OSes() {
|
||||||
|
if os == goos {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Errorf("ForOS(%q) returned %q", goos, p.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
for _, p := range ForOS("windows") {
|
||||||
|
if p.Name() == "apt" {
|
||||||
|
t.Error("apt should not be offered on windows")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsRebootExit(t *testing.T) {
|
||||||
|
for _, code := range []int{1641, 3010} {
|
||||||
|
if !isRebootExit(code) {
|
||||||
|
t.Errorf("%d should be a reboot exit", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, code := range []int{0, 1, 1618} {
|
||||||
|
if isRebootExit(code) {
|
||||||
|
t.Errorf("%d should not be a reboot exit", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/run"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- winget ---
|
||||||
|
|
||||||
|
type winget struct {
|
||||||
|
once sync.Once
|
||||||
|
path string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *winget) Name() string { return "winget" }
|
||||||
|
func (w *winget) OSes() []string { return []string{"windows"} }
|
||||||
|
func (w *winget) Label() string { return "Windows Package Manager (winget)" }
|
||||||
|
|
||||||
|
// resolve finds winget.exe. The PATH entry is an app-execution alias that only
|
||||||
|
// exists inside a user session, so a run as SYSTEM (which is how an RMM invokes
|
||||||
|
// us) has to reach into the WindowsApps payload directly.
|
||||||
|
func (w *winget) resolve() string {
|
||||||
|
w.once.Do(func() {
|
||||||
|
if runtime.GOOS != "windows" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p, ok := run.Which("winget"); ok {
|
||||||
|
w.path = p
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pf := os.Getenv("ProgramFiles")
|
||||||
|
if pf == "" {
|
||||||
|
pf = "C:\\Program Files"
|
||||||
|
}
|
||||||
|
patterns := []string{
|
||||||
|
filepath.Join(pf, "WindowsApps", "Microsoft.DesktopAppInstaller_*_x64__8wekyb3d8bbwe", "winget.exe"),
|
||||||
|
filepath.Join(pf, "WindowsApps", "Microsoft.DesktopAppInstaller_*_arm64__8wekyb3d8bbwe", "winget.exe"),
|
||||||
|
filepath.Join(pf, "WindowsApps", "Microsoft.DesktopAppInstaller_*", "winget.exe"),
|
||||||
|
}
|
||||||
|
var newest string
|
||||||
|
var newestTime int64
|
||||||
|
for _, pattern := range patterns {
|
||||||
|
matches, _ := filepath.Glob(pattern)
|
||||||
|
for _, m := range matches {
|
||||||
|
info, err := os.Stat(m)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ts := info.ModTime().Unix(); ts > newestTime {
|
||||||
|
newest, newestTime = m, ts
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.path = newest
|
||||||
|
})
|
||||||
|
return w.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *winget) Available(context.Context, Opts) bool { return w.resolve() != "" }
|
||||||
|
|
||||||
|
func (w *winget) base() []string {
|
||||||
|
return []string{
|
||||||
|
"--exact",
|
||||||
|
"--silent",
|
||||||
|
"--accept-package-agreements",
|
||||||
|
"--accept-source-agreements",
|
||||||
|
"--disable-interactivity",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *winget) exec(ctx context.Context, o Opts, args []string) run.Result {
|
||||||
|
return run.Exec(ctx, run.Options{
|
||||||
|
Name: w.resolve(),
|
||||||
|
Args: args,
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
DryRun: o.DryRun,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *winget) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
args := append([]string{"install", "--id", src.ID}, w.base()...)
|
||||||
|
args = append(args, src.Args...)
|
||||||
|
|
||||||
|
// Prefer a machine-wide install so the software is there for every user --
|
||||||
|
// and because a user-scope install performed as SYSTEM lands in a profile
|
||||||
|
// nobody logs into. Not every package ships a machine-scope installer, so
|
||||||
|
// fall back rather than fail.
|
||||||
|
scoped := append(append([]string{}, args...), "--scope", "machine")
|
||||||
|
res := w.exec(ctx, o, scoped)
|
||||||
|
if res.Failed() && !w.benign(res) && wantsOtherScope(res) {
|
||||||
|
if o.Log != nil {
|
||||||
|
o.Log.Debugf("winget: %s has no machine-scope installer, retrying in default scope", src.ID)
|
||||||
|
}
|
||||||
|
res = w.exec(ctx, o, args)
|
||||||
|
}
|
||||||
|
return w.outcome(res, src, o, "install")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *winget) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
args := append([]string{"upgrade", "--id", src.ID}, w.base()...)
|
||||||
|
args = append(args, src.Args...)
|
||||||
|
res := w.exec(ctx, o, args)
|
||||||
|
return w.outcome(res, src, o, "upgrade")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *winget) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
args := []string{"uninstall", "--id", src.ID, "--exact", "--silent",
|
||||||
|
"--accept-source-agreements", "--disable-interactivity"}
|
||||||
|
res := w.exec(ctx, o, args)
|
||||||
|
return w.outcome(res, src, o, "uninstall")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *winget) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||||
|
res := run.Exec(ctx, run.Options{
|
||||||
|
Name: w.resolve(),
|
||||||
|
Args: []string{"list", "--id", src.ID, "--exact", "--accept-source-agreements", "--disable-interactivity"},
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
if res.Failed() {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return wingetListVersion(res.Stdout, src.ID), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// wingetListVersion pulls the version column out of `winget list` output. The
|
||||||
|
// table is space-aligned and localised, so we anchor on the package id and take
|
||||||
|
// the token after it rather than trusting column positions.
|
||||||
|
func wingetListVersion(out, id string) string {
|
||||||
|
for _, line := range strings.Split(out, "\n") {
|
||||||
|
if !strings.Contains(line, id) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fields := strings.Fields(line)
|
||||||
|
for i, f := range fields {
|
||||||
|
if strings.EqualFold(f, id) && i+1 < len(fields) {
|
||||||
|
return fields[i+1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// benign recognises the outcomes winget reports as errors but which mean the
|
||||||
|
// machine is already in the state we asked for.
|
||||||
|
func (w *winget) benign(res run.Result) bool {
|
||||||
|
for _, phrase := range []string{
|
||||||
|
"already installed",
|
||||||
|
"no applicable upgrade",
|
||||||
|
"no newer package versions",
|
||||||
|
"no available upgrade",
|
||||||
|
"no installed package found matching",
|
||||||
|
} {
|
||||||
|
if res.Contains(phrase) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func wantsOtherScope(res run.Result) bool {
|
||||||
|
return res.Contains("scope") || res.Contains("no applicable installer")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *winget) outcome(res run.Result, src catalog.Source, o Opts, verb string) (Outcome, error) {
|
||||||
|
if o.DryRun {
|
||||||
|
return Outcome{Message: "dry run"}, nil
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case !res.Failed():
|
||||||
|
return Outcome{}, nil
|
||||||
|
case isRebootExit(res.ExitCode):
|
||||||
|
return Outcome{RebootRequired: true}, nil
|
||||||
|
case w.benign(res):
|
||||||
|
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||||
|
default:
|
||||||
|
return Outcome{}, fmt.Errorf("winget %s %s: %s", verb, src.ID, res.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ chocolatey ---
|
||||||
|
|
||||||
|
type choco struct{}
|
||||||
|
|
||||||
|
func (c *choco) Name() string { return "choco" }
|
||||||
|
func (c *choco) OSes() []string { return []string{"windows"} }
|
||||||
|
func (c *choco) Label() string { return "Chocolatey" }
|
||||||
|
|
||||||
|
func (c *choco) Available(context.Context, Opts) bool {
|
||||||
|
return runtime.GOOS == "windows" && run.Available("choco")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *choco) exec(ctx context.Context, o Opts, args ...string) run.Result {
|
||||||
|
return run.Exec(ctx, run.Options{
|
||||||
|
Name: "choco",
|
||||||
|
Args: append(args, "-y", "--no-progress", "--limit-output"),
|
||||||
|
Timeout: o.Timeout,
|
||||||
|
DryRun: o.DryRun,
|
||||||
|
Log: o.Log,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *choco) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := c.exec(ctx, o, append([]string{"install", src.ID}, src.Args...)...)
|
||||||
|
return c.outcome(res, src, o, "install")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *choco) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := c.exec(ctx, o, append([]string{"upgrade", src.ID}, src.Args...)...)
|
||||||
|
return c.outcome(res, src, o, "upgrade")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *choco) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
|
||||||
|
res := c.exec(ctx, o, "uninstall", src.ID, "--remove-dependencies")
|
||||||
|
return c.outcome(res, src, o, "uninstall")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *choco) Query(ctx context.Context, src catalog.Source, o Opts) (string, bool) {
|
||||||
|
// Chocolatey 2.x dropped --local-only; 1.x needs it or `list` queries the
|
||||||
|
// remote feed instead of the machine.
|
||||||
|
for _, args := range [][]string{
|
||||||
|
{"list", "--local-only", "--exact", src.ID, "-r"},
|
||||||
|
{"list", "--exact", src.ID, "-r"},
|
||||||
|
} {
|
||||||
|
res := run.Exec(ctx, run.Options{Name: "choco", Args: args, Timeout: o.Timeout, Log: o.Log})
|
||||||
|
if res.Failed() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, line := range strings.Split(res.Stdout, "\n") {
|
||||||
|
parts := strings.Split(strings.TrimSpace(line), "|")
|
||||||
|
if len(parts) == 2 && strings.EqualFold(parts[0], src.ID) {
|
||||||
|
return parts[1], true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *choco) outcome(res run.Result, src catalog.Source, o Opts, verb string) (Outcome, error) {
|
||||||
|
if o.DryRun {
|
||||||
|
return Outcome{Message: "dry run"}, nil
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case !res.Failed():
|
||||||
|
if res.Contains("already installed") || res.Contains("is not installed") {
|
||||||
|
return Outcome{NoOp: true, Message: "already up to date"}, nil
|
||||||
|
}
|
||||||
|
return Outcome{RebootRequired: res.Contains("pending reboot")}, nil
|
||||||
|
case isRebootExit(res.ExitCode):
|
||||||
|
return Outcome{RebootRequired: true}, nil
|
||||||
|
default:
|
||||||
|
return Outcome{}, fmt.Errorf("choco %s %s: %s", verb, src.ID, res.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
// Package run executes external commands the way an unattended deployment tool
|
||||||
|
// has to: never interactive, always bounded by a timeout, always captured.
|
||||||
|
package run
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/logx"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrNeedRoot is returned when a command requires root and no non-interactive
|
||||||
|
// escalation path exists.
|
||||||
|
var ErrNeedRoot = errors.New("root privileges required and passwordless sudo is unavailable")
|
||||||
|
|
||||||
|
// DefaultTimeout bounds a single installer invocation. Large suites (Office,
|
||||||
|
// Visual Studio) legitimately take a long time; anything past this is hung.
|
||||||
|
const DefaultTimeout = 30 * time.Minute
|
||||||
|
|
||||||
|
// Options describes one command invocation.
|
||||||
|
type Options struct {
|
||||||
|
Name string // executable, resolved via PATH unless absolute
|
||||||
|
Args []string // arguments
|
||||||
|
Env []string // extra KEY=VALUE pairs layered over the parent env
|
||||||
|
Dir string // working directory
|
||||||
|
Timeout time.Duration // zero means DefaultTimeout
|
||||||
|
// NeedRoot makes the command run as root on Unix: already-root runs
|
||||||
|
// unchanged, otherwise it is prefixed with non-interactive sudo.
|
||||||
|
NeedRoot bool
|
||||||
|
// AsUser drops from root to this account on Unix (Homebrew refuses root).
|
||||||
|
AsUser string
|
||||||
|
DryRun bool
|
||||||
|
Log *logx.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
// Result is the outcome of a command.
|
||||||
|
type Result struct {
|
||||||
|
Cmd string
|
||||||
|
Args []string
|
||||||
|
ExitCode int
|
||||||
|
Stdout string
|
||||||
|
Stderr string
|
||||||
|
Duration time.Duration
|
||||||
|
TimedOut bool
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Failed reports whether the command did not complete with exit status 0.
|
||||||
|
func (r Result) Failed() bool { return r.Err != nil || r.ExitCode != 0 }
|
||||||
|
|
||||||
|
// Output returns stdout and stderr joined and trimmed, for error messages.
|
||||||
|
func (r Result) Output() string {
|
||||||
|
return strings.TrimSpace(strings.TrimSpace(r.Stdout) + "\n" + strings.TrimSpace(r.Stderr))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Contains reports whether the combined output contains needle, case-insensitively.
|
||||||
|
// Package managers communicate a lot through prose rather than exit codes.
|
||||||
|
func (r Result) Contains(needle string) bool {
|
||||||
|
return strings.Contains(strings.ToLower(r.Output()), strings.ToLower(needle))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Describe renders the command line for logs.
|
||||||
|
func (r Result) Describe() string {
|
||||||
|
if len(r.Args) == 0 {
|
||||||
|
return r.Cmd
|
||||||
|
}
|
||||||
|
return r.Cmd + " " + strings.Join(r.Args, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error summarises a failure in one line.
|
||||||
|
func (r Result) Error() string {
|
||||||
|
switch {
|
||||||
|
case r.TimedOut:
|
||||||
|
return fmt.Sprintf("timed out after %s", r.Duration.Round(time.Second))
|
||||||
|
case r.Err != nil:
|
||||||
|
return r.Err.Error()
|
||||||
|
default:
|
||||||
|
msg := fmt.Sprintf("exit status %d", r.ExitCode)
|
||||||
|
if out := lastLine(r.Output()); out != "" {
|
||||||
|
msg += ": " + out
|
||||||
|
}
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func lastLine(s string) string {
|
||||||
|
lines := strings.Split(strings.TrimSpace(s), "\n")
|
||||||
|
for i := len(lines) - 1; i >= 0; i-- {
|
||||||
|
if l := strings.TrimSpace(lines[i]); l != "" {
|
||||||
|
if len(l) > 200 {
|
||||||
|
return l[:200] + "..."
|
||||||
|
}
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exec runs a command to completion and returns its captured result.
|
||||||
|
func Exec(ctx context.Context, o Options) Result {
|
||||||
|
name, args := o.Name, append([]string(nil), o.Args...)
|
||||||
|
env := append([]string(nil), o.Env...)
|
||||||
|
|
||||||
|
if runtime.GOOS != "windows" {
|
||||||
|
var err error
|
||||||
|
name, args, env, err = escalate(name, args, env, o)
|
||||||
|
if err != nil {
|
||||||
|
return Result{Cmd: o.Name, Args: o.Args, Err: err, ExitCode: -1}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res := Result{Cmd: name, Args: args}
|
||||||
|
|
||||||
|
if o.Log != nil {
|
||||||
|
o.Log.Debugf("exec: %s", res.Describe())
|
||||||
|
}
|
||||||
|
if o.DryRun {
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
timeout := o.Timeout
|
||||||
|
if timeout <= 0 {
|
||||||
|
timeout = DefaultTimeout
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
cmd := exec.CommandContext(ctx, name, args...)
|
||||||
|
cmd.Dir = o.Dir
|
||||||
|
if len(env) > 0 {
|
||||||
|
cmd.Env = append(os.Environ(), env...)
|
||||||
|
}
|
||||||
|
// Nothing may ever wait on a prompt: stdin is closed, not inherited.
|
||||||
|
cmd.Stdin = nil
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
cmd.Stdout = &stdout
|
||||||
|
cmd.Stderr = &stderr
|
||||||
|
// Give a killed process a moment to die before we give up on its pipes.
|
||||||
|
cmd.WaitDelay = 10 * time.Second
|
||||||
|
hideWindow(cmd)
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
err := cmd.Run()
|
||||||
|
res.Duration = time.Since(start)
|
||||||
|
res.Stdout = stdout.String()
|
||||||
|
res.Stderr = stderr.String()
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case ctx.Err() == context.DeadlineExceeded:
|
||||||
|
res.TimedOut = true
|
||||||
|
res.ExitCode = -1
|
||||||
|
res.Err = fmt.Errorf("timed out after %s", timeout)
|
||||||
|
case err == nil:
|
||||||
|
res.ExitCode = 0
|
||||||
|
default:
|
||||||
|
var ee *exec.ExitError
|
||||||
|
if errors.As(err, &ee) {
|
||||||
|
res.ExitCode = ee.ExitCode()
|
||||||
|
} else {
|
||||||
|
res.ExitCode = -1
|
||||||
|
res.Err = err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if o.Log != nil && res.Failed() {
|
||||||
|
o.Log.Debugf("exit %d after %s: %s", res.ExitCode, res.Duration.Round(time.Millisecond), lastLine(res.Output()))
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// escalate rewrites a command for Unix privilege requirements: sudo up to root
|
||||||
|
// when NeedRoot, or sudo down to AsUser when running as root.
|
||||||
|
func escalate(name string, args, env []string, o Options) (string, []string, []string, error) {
|
||||||
|
root := os.Geteuid() == 0
|
||||||
|
|
||||||
|
if o.AsUser != "" && root {
|
||||||
|
prefixed := []string{"-u", o.AsUser, "-H"}
|
||||||
|
if len(env) > 0 {
|
||||||
|
// sudo scrubs the environment, so re-apply it on the far side.
|
||||||
|
prefixed = append(prefixed, "/usr/bin/env")
|
||||||
|
prefixed = append(prefixed, env...)
|
||||||
|
env = nil
|
||||||
|
}
|
||||||
|
prefixed = append(prefixed, name)
|
||||||
|
return "sudo", append(prefixed, args...), env, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if o.NeedRoot && !root {
|
||||||
|
if !sudoNonInteractive() {
|
||||||
|
return "", nil, nil, ErrNeedRoot
|
||||||
|
}
|
||||||
|
return "sudo", append([]string{"-n", name}, args...), env, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return name, args, env, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
sudoOnce sync.Once
|
||||||
|
sudoOK bool
|
||||||
|
)
|
||||||
|
|
||||||
|
// sudoNonInteractive reports whether `sudo -n` succeeds without a password.
|
||||||
|
// Probing once per process keeps us from spraying auth failures into the logs.
|
||||||
|
func sudoNonInteractive() bool {
|
||||||
|
sudoOnce.Do(func() {
|
||||||
|
if _, err := exec.LookPath("sudo"); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
sudoOK = exec.CommandContext(ctx, "sudo", "-n", "true").Run() == nil
|
||||||
|
})
|
||||||
|
return sudoOK
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
pathMu sync.Mutex
|
||||||
|
pathCache = map[string]string{}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Which resolves an executable, caching both hits and misses.
|
||||||
|
func Which(name string) (string, bool) {
|
||||||
|
pathMu.Lock()
|
||||||
|
defer pathMu.Unlock()
|
||||||
|
if p, ok := pathCache[name]; ok {
|
||||||
|
return p, p != ""
|
||||||
|
}
|
||||||
|
p, err := exec.LookPath(name)
|
||||||
|
if err != nil {
|
||||||
|
pathCache[name] = ""
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
pathCache[name] = p
|
||||||
|
return p, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Available reports whether an executable exists on PATH.
|
||||||
|
func Available(name string) bool {
|
||||||
|
_, ok := Which(name)
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// CanEscalate reports whether privileged commands can run without a prompt:
|
||||||
|
// already root, or passwordless sudo is configured. On Windows the process
|
||||||
|
// token decides, so this is not the right question and it answers true.
|
||||||
|
func CanEscalate() bool {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return os.Geteuid() == 0 || sudoNonInteractive()
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package run
|
||||||
|
|
||||||
|
import "os/exec"
|
||||||
|
|
||||||
|
func hideWindow(*exec.Cmd) {}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package run
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/exec"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
// hideWindow keeps installer console windows from flashing on an interactive
|
||||||
|
// desktop while a technician is working.
|
||||||
|
func hideWindow(cmd *exec.Cmd) {
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// Package version carries build metadata stamped in via -ldflags.
|
||||||
|
package version
|
||||||
|
|
||||||
|
import "runtime"
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Version is the semantic version of this build.
|
||||||
|
Version = "dev"
|
||||||
|
// Commit is the git commit the binary was built from.
|
||||||
|
Commit = "none"
|
||||||
|
// Date is the build timestamp (RFC3339).
|
||||||
|
Date = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
// String renders the full build identity, e.g.
|
||||||
|
// "deployr 0.1.0 (a1b2c3d, built 2026-08-26T10:00:00Z, go1.27.0 windows/amd64)".
|
||||||
|
func String() string {
|
||||||
|
return "deployr " + Version + " (" + Commit + ", built " + Date + ", " +
|
||||||
|
runtime.Version() + " " + runtime.GOOS + "/" + runtime.GOARCH + ")"
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Cross-compiles deployr for every supported platform.
|
||||||
|
|
||||||
|
.EXAMPLE
|
||||||
|
.\scripts\build.ps1 # build everything into dist\
|
||||||
|
.\scripts\build.ps1 -Version 1.0.0 # stamp a release version
|
||||||
|
.\scripts\build.ps1 -Only windows/amd64
|
||||||
|
#>
|
||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[string]$Version = "dev",
|
||||||
|
[string]$Only = "",
|
||||||
|
[string]$OutDir = "dist"
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
$root = Split-Path -Parent $PSScriptRoot
|
||||||
|
Set-Location $root
|
||||||
|
|
||||||
|
$targets = @(
|
||||||
|
"windows/amd64",
|
||||||
|
"windows/arm64",
|
||||||
|
"darwin/amd64",
|
||||||
|
"darwin/arm64",
|
||||||
|
"linux/amd64",
|
||||||
|
"linux/arm64"
|
||||||
|
)
|
||||||
|
if ($Only) { $targets = @($Only) }
|
||||||
|
|
||||||
|
$commit = "none"
|
||||||
|
try { $commit = (git rev-parse --short HEAD 2>$null).Trim() } catch { }
|
||||||
|
if (-not $commit) { $commit = "none" }
|
||||||
|
$date = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||||
|
|
||||||
|
$pkg = "git.starwarslab.us/ATOM_IT/Deployr/internal/version"
|
||||||
|
$ldflags = "-s -w -X $pkg.Version=$Version -X $pkg.Commit=$commit -X $pkg.Date=$date"
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
|
||||||
|
|
||||||
|
foreach ($target in $targets) {
|
||||||
|
$parts = $target.Split("/")
|
||||||
|
$os = $parts[0]
|
||||||
|
$arch = $parts[1]
|
||||||
|
$name = "deployr_${Version}_${os}_${arch}"
|
||||||
|
if ($os -eq "windows") { $name += ".exe" }
|
||||||
|
|
||||||
|
Write-Host "building $target -> $OutDir\$name"
|
||||||
|
$env:GOOS = $os
|
||||||
|
$env:GOARCH = $arch
|
||||||
|
$env:CGO_ENABLED = "0"
|
||||||
|
go build -trimpath -ldflags $ldflags -o "$OutDir\$name" ./cmd/deployr
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "build failed for $target" }
|
||||||
|
}
|
||||||
|
|
||||||
|
$env:GOOS = ""; $env:GOARCH = ""; $env:CGO_ENABLED = ""
|
||||||
|
|
||||||
|
Get-ChildItem $OutDir -File |
|
||||||
|
Where-Object { $_.Name -ne "SHA256SUMS" } |
|
||||||
|
ForEach-Object { "{0} {1}" -f (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLower(), $_.Name } |
|
||||||
|
Set-Content -Path (Join-Path $OutDir "SHA256SUMS") -Encoding utf8
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Get-ChildItem $OutDir | Format-Table Name, @{N = "MB"; E = { [math]::Round($_.Length / 1MB, 1) } }
|
||||||
Executable
+37
@@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Cross-compiles deployr for every supported platform.
|
||||||
|
#
|
||||||
|
# ./scripts/build.sh # build everything into dist/
|
||||||
|
# VERSION=1.0.0 ./scripts/build.sh # stamp a release version
|
||||||
|
# TARGETS="linux/amd64" ./scripts/build.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
VERSION="${VERSION:-dev}"
|
||||||
|
OUTDIR="${OUTDIR:-dist}"
|
||||||
|
TARGETS="${TARGETS:-windows/amd64 windows/arm64 darwin/amd64 darwin/arm64 linux/amd64 linux/arm64}"
|
||||||
|
|
||||||
|
COMMIT="$(git rev-parse --short HEAD 2>/dev/null || echo none)"
|
||||||
|
DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
|
||||||
|
PKG="git.starwarslab.us/ATOM_IT/Deployr/internal/version"
|
||||||
|
LDFLAGS="-s -w -X ${PKG}.Version=${VERSION} -X ${PKG}.Commit=${COMMIT} -X ${PKG}.Date=${DATE}"
|
||||||
|
|
||||||
|
mkdir -p "$OUTDIR"
|
||||||
|
|
||||||
|
for target in $TARGETS; do
|
||||||
|
os="${target%%/*}"
|
||||||
|
arch="${target##*/}"
|
||||||
|
name="deployr_${VERSION}_${os}_${arch}"
|
||||||
|
[ "$os" = "windows" ] && name="${name}.exe"
|
||||||
|
|
||||||
|
echo "building ${target} -> ${OUTDIR}/${name}"
|
||||||
|
CGO_ENABLED=0 GOOS="$os" GOARCH="$arch" \
|
||||||
|
go build -trimpath -ldflags "$LDFLAGS" -o "${OUTDIR}/${name}" ./cmd/deployr
|
||||||
|
done
|
||||||
|
|
||||||
|
( cd "$OUTDIR" && rm -f SHA256SUMS && sha256sum ./* > SHA256SUMS 2>/dev/null || shasum -a 256 ./* > SHA256SUMS )
|
||||||
|
|
||||||
|
echo
|
||||||
|
ls -lh "$OUTDIR"
|
||||||
Reference in new issue
Block a user