diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d7380d3..03664e76 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,33 +1,60 @@ -name: ci +name: CI + on: - - push - - pull_request + push: + branches: + - main + pull_request: + workflow_call: + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + permissions: contents: read + jobs: test: + name: Ruby ${{ matrix.ruby }} runs-on: ubuntu-latest + timeout-minutes: 10 strategy: fail-fast: false matrix: - ruby: - - "2.6" - - "2.7" - - "3.0" - - "3.1" - - "3.2" - - "3.3" - - "3.4" - env: - BUNDLE_WITHOUT: development + ruby: ['3.2', '3.3', '3.4', '4.0'] steps: - - name: Checkout code - uses: actions/checkout@v4 - - name: Set up Ruby + - name: Check out source + uses: actions/checkout@v5 + + - name: Set up Ruby ${{ matrix.ruby }} uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} - bundler-cache: true # runs 'bundle install' and caches installed gems automatically - rubygems: latest # runs 'gem update --system' - - name: Run test - run: bundle exec rake spec + bundler-cache: true + + - name: Run tests + run: bundle exec rspec + + quality: + name: Quality and package + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Check out source + uses: actions/checkout@v5 + + - name: Set up Ruby 4.0 + uses: ruby/setup-ruby@v1 + with: + ruby-version: "4.0" + bundler-cache: true + + - name: Run RuboCop + run: bundle exec rubocop --format github + + - name: Build gem + run: gem build foruiman.gemspec + + - name: Smoke-test packaged gem + run: bundle exec ruby script/smoke_gem.rb diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..40384afa --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,47 @@ +name: Release + +on: + push: + tags: + - "v*" + +permissions: + contents: read + +jobs: + ci: + name: Verify release + uses: ./.github/workflows/ci.yml + + publish: + name: Publish to RubyGems.org + needs: ci + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: release + permissions: + contents: write + id-token: write + steps: + - name: Check out source + uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Set up Ruby 4.0 + uses: ruby/setup-ruby@v1 + with: + ruby-version: "4.0" + bundler-cache: true + + - name: Verify tag matches gem version + shell: bash + run: | + version="$(ruby -Ilib -rforuiman/version -e 'print Foruiman::VERSION')" + if [[ "$GITHUB_REF_NAME" != "v$version" ]]; then + echo "Tag $GITHUB_REF_NAME does not match gem version $version" >&2 + exit 1 + fi + + - name: Publish gem + uses: rubygems/release-gem@v1 diff --git a/.gitignore b/.gitignore index 02160624..96ad8745 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,7 @@ -/.bundle -/.env -/coverage -/man/*.html -/man/*.markdown +/.bundle/ +/vendor/ /pkg/ -/vendor -Gemfile.lock +/*.gem +/coverage/ +/.rspec_status +/.env diff --git a/.rspec b/.rspec new file mode 100644 index 00000000..033e0bcf --- /dev/null +++ b/.rspec @@ -0,0 +1,3 @@ +--require spec_helper +--format progress +--order random diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 00000000..844f6423 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,18 @@ +AllCops: + TargetRubyVersion: 3.2 + NewCops: enable + Exclude: + - vendor/**/* + +Style/Documentation: + Enabled: false +Style/StringLiterals: + EnforcedStyle: double_quotes +Style/ClassAndModuleChildren: + Enabled: false +Metrics: + Enabled: false +Layout/LineLength: + Max: 120 +Gemspec/RequireMFA: + Enabled: true diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..8f32b968 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,37 @@ +# Changelog + +## Unreleased + +- Test Ruby 3.2, 3.3, 3.4, and 4.0 in a reusable CI workflow and keep the + development dependency set compatible with Ruby 3.2. +- Add a tag-driven RubyGems trusted-publishing workflow gated by the full CI suite. +- Make renderer row-width checks independent of the runner's terminal settings. + +## 0.1.2 + +- Fix lowercase `r` on the `all` tab to restart every process; keep `R` available + from any tab and make the footer describe the selected restart scope. +- Show the active Procfile in the header, including custom paths and working + directories, with filename priority in narrow terminals. +- Follow the terminal's global theme through its ANSI palette and default + background. Use reverse-video selection for light, dark, and monochrome themes. +- Verify group restarts with real keyboard input and process cleanup, and cover + Procfile titles, theme inheritance, and preserved child colors. + +## 0.1.1 + +- Redesign the TUI with a forest palette, framed process navigation, selected-tab + backgrounds, status colors, aligned log columns, a scrollbar, and grouped help. +- Support truecolor, 256 colors, and `NO_COLOR`; preserve child ANSI styles without + letting resets overwrite the interface background. +- Adapt chrome and log metadata to terminal size, keep selected tabs visible, + and use the actual visible log height for scrolling and paging. +- Include a static preview fixture and expand color, layout, and PTY coverage. + +## 0.1.0 + +- Fork-derived MVP based on Foreman `f65ddba83932bd4670e014389d6e27ea1e20b469`. +- Strict Procfiles, layered environments, and validated port allocation. +- Independent process supervision, bounded log rings, and asynchronous restarts. +- Terminal tabs, scrolling, Unicode-aware rows, and exception-safe restoration. +- Automatic plain mode and process-group cleanup with TERM/KILL escalation. diff --git a/Changelog.md b/Changelog.md deleted file mode 100644 index 5357bc28..00000000 --- a/Changelog.md +++ /dev/null @@ -1,730 +0,0 @@ -## 0.90.0 (2025-07-27) - -* remove ostruct along with deprecated exporter methods [David Dollar] -* fix(gemspec): declare thor as a runtime dependency [Rui Chen] - -## 0.89.1 (2025-07-26) - -* handle ruby 3.4 changes [David Dollar] -* thor doesnt work on older ruby [David Dollar] -* test more ruby versions [David Dollar] - -## 0.89.0 (2025-07-26) - -* handle new thor exit on failure [David Dollar] -* move options out of private for new thor [David Dollar] -* unbundle thor, upgrade to 1.4.0 [David Dollar] -* dont fail tests when Procfile is present in foreman dir (closes #771) [David Dollar] - -## 0.88.1 (2024-04-12) - -* update master to main [David Dollar] - -## 0.88.0 (2024-04-12) - -* use actions/checkout@v4 [David Dollar] -* remove Gemfile.lock from repo because it's too strict [David Dollar] -* update for ci [David Dollar] -* handle empty procfile exception in cli [David Dollar] -* Update man page to reflect recent changes in systemd export [Lukáš Konarovský] -* [engine/cli.rb] Handle nil name_padding [Nick LaMuro] -* [Foreman::Procfile#load] Fail when empty [Nick LaMuro] -* spec_helper: don't try to remove /tmp [Antonio Terceiro] -* Fix misleading comment at the top of procfile.rb that indicates that hyphens "-" are not allowed in process names. [Ben Wilber] -* Rename usage of Dir/File.exists to exist [Qiu Chaofan] -* remove codeclimate [David Dollar] -* clean up and autoformat [David Dollar] -* Add GitHub token permissions for workflow [mishina] -* Migrate from Travis CI to GitHub Actions [mishina] -* Pass a block rather than an argument to `expect` [mishina] -* Replace `File.exists?` with `File.exist?` [mishina] -* Use the latest fakefs [mishina] -* Remove and ignore Gemfile.lock [mishina] -* Add GitHub Actions workflow [mishina] -* GitHub is HTTPS by default [Akira Matsuda] - -## 0.87.2 (2020-08-07) - -* update json for CVE-2020-10663 [David Dollar] - -## 0.87.1 (2020-04-02) - -* update rake for CVE-2020-8130 [David Dollar] - -## 0.87.0 (2020-01-07) - -* Update specs for systemd export [Robin Daugherty] -* Allow processes to be stopped using the app target [Robin Daugherty] -* Wait to restart [Robin Daugherty] -* systemd sets process name [Robin Daugherty] - -## 0.86.0 (2019-10-09) - -* bundle (but don't use) real thor to ensure we still get vulnerability notifications from github. [Micah Geisel] -* we don't need automatiek loaded to boot. [Micah Geisel] -* inline thor dependency. [Micah Geisel] -* CI: Use ruby 2.5.6, 2.6.4 in the matrix [Olle Jonsson] -* add wiki page with reason for not bundling to readme [David Dollar] -* CI: Use 2.4.6, 2.5.5, 2.6.3 [Olle Jonsson] -* update yard for GHSA-xfhh-rx56-rxcr [David Dollar] - -## 0.85.0 (2018-06-18) - -* updates rubies in travis - ensures only running with PID would be killed - updates dependencies; runs `codeclimate-test-reporter` after successful build - updates rubies for travis - squashes commits [LeFnord] -* Deprecate safe_level of ERB.new in Ruby 2.6 [Koichi ITO] -* gitignore [David Dollar] -* update yard [David Dollar] -* Don't upcase env names for daemon processes [Matthew Savage] -* Don't upcase env names in Launchd [Matthew Savage] -* No upcase for env name in Systemd [Matthew Savage] -* Don't force env var names to be upcased [Matthew Savage] -* Test that invalid Procfile entries are ignored [Kevin Litchfield] -* Remove unused block parameter [Kevin Litchfield] - -## 0.84.0 (2017-03-28) - -* add test for systemd template (closes: #664) [Timur Batyrshin] -* quote env vars as was suggested in https://github.com/ddollar/foreman/pull/652 [Timur Batyrshin] -* update specs [Koen Punt] -* update specs [Koen Punt] -* forward user signals (SIGUSR1, SIGUSR2) [Tilo Prütz] -* make systemctl stop/restart/reload work [Koen Punt] -* 0.83.0 [David Dollar] -* use default stop signal for supervisord [Chris Blättermann] -* updated fakefs to silence warnings during tests [Chris Blättermann] -* Add option to suppress timestamps [Glenn Oppegard] -* Add ruby 2.3.3 to travis [Tejas Bubane] -* Change systemd KillMode to "mixed" [Reto Kaiser] -* Relax systemd template spec matcher for env var [Reto Kaiser] -* Don't print newline in systemd template if no ENV vars given [Reto Kaiser] -* pp must be required before fakefs [Reto Kaiser] -* Typo [Lin] -* Fixed empty Environment line for Travis [Lin] -* More compact and escaped environment variable names [Lin] -* Add spm (go port) [Ömer Ufuk Efendioğlu] -* Port to rspec 3 [Antonio Terceiro] -* README: Use fancy SVG badges [ci skip] [Olle Jonsson] -* defined process filename format only once [Koen Punt] -* clean all upstart process files [Koen Punt] -* Fix small typo in man page [Dov Murik] -* Foreman Export Upstart should not duplicate ports [Steven Daniels] - -## 0.82.0 (2016-05-21) - -* Fixes #626. Use -m for concurrency when using the export command. [Jori Hardman] -* Add stop timeout to systemd services [Christian Haase] -* systemd exporter creates target dependencies via symlinks [Christian Haase] -* Update systemd exporter to generate instantiated services [Christian Haase] -* changelog [David Dollar] - -## 0.81.0 (2016-04-26) - -* Revert "Create a new process group when spawning a new process. This should prevent from SIGINT propagating to spawned processes. (#528)" [David Dollar] -* Fix cleaning up unrelated configuration files (#617) [Per-Henrik Lundblom] - -## 0.80.2 (2016-04-24) - -* fix nil status error [David Dollar] - -## 0.80.1 (2016-04-23) - -* ignore gems [David Dollar] -* add package dir [David Dollar] - -## 0.80.0 (2016-04-23) - -* Update README.md (#614) [Hernan Y.Ke] -* Fix Windows crash, caused by read_nonblock (#576) [Igor Antonov] -* update gems [David Dollar] -* Propagate process failure [4r2r] -* update gems [David Dollar] -* remove win32console dependency [Takumi IINO] -* Added possible fix for pkg install on El Capitan. (#585) [Jeroen Visser] -* use proper check to see if file exists (#577) [Mateusz Byczkowski] -* Allow supervisord environment vars to have "=" (#572) [Stephen Yeargin] -* Document $PORT and $PS (#562) [Mike Burns] -* An location -> A location (#543) [Eliot Sykes] -* Fix signal exception name (#530) [Oleksiy Kovyrin] -* Make a single thread responsible for handling graceful shutdown (#529) [Oleksiy Kovyrin] -* Create a new process group when spawning a new process. This should prevent from SIGINT propagating to spawned processes. (#528) [Oleksiy Kovyrin] -* use the latest bundler [David Dollar] -* check all the rubies [David Dollar] -* Revert "test on 2.x releases" [David Dollar] -* test on 2.x releases [David Dollar] -* remove dotenv as it's not worth the dependency hell. closes #505, #538 [David Dollar] -* Port tests to fakefs 0.4 [Antonio Terceiro] -* add documentation to cli (formation options describtion) (#523) [Leonid Batizhevsky] -* Replaces 'concurrency' with 'formation' in manpage (#524) [Piers Mainwaring] -* Work around potential nil $? (#526) [David Zülke] -* update gems [David Dollar] -* remove ruby 1.9 support [David Dollar] -* Update README URLs based on HTTP redirects [ReadmeCritic] -* Add port to Haskell to README [Daisuke Fujimura] -* Adds 'Crank' to README.md: a port of Foreman to Crystal [arktisklada] -* fix specs [Pierpaolo Frasa] -* Fixed erb tags in systemd process.service template. [Tomasz Łoszko] -* use PartOf [Pierpaolo Frasa] -* don't stop systemd master target immediately [Pierpaolo Frasa] -* Add goreman (go port) [Francois] -* Strip non-quoted whitespace [pik] -* Procfile#[] return nil for non-existing entries [Simon Rozet] -* update changeling [David Dollar] - -## 0.78.0 (2015-03-13) - -* remove dotenv as it's not worth the dependency hell [David Dollar] -* Do not parse options after "run" argument, to avoid conflicts. [Giovanni Bajo] -* Update docs with --timeout [Stephen Bussey] - -## 0.77.0 (2015-01-01) - -* 0.77.0 [David Dollar] -* Do not change the output of clean [Łukasz Korecki] -* Only delete upstart files matching application name. [Łukasz Korecki] -* Add failling test for case where app.conf and app-worker.conf would be deleted [Łukasz Korecki] -* Test against Ruby 2.2 on Travis CI [Ryunosuke SATO] -* Nicer formatting for exported supervisord files [Marc Abramowitz] - -## 0.76.0 (2014-11-25) - -* 0.76.0 [David Dollar] -* Merge pull request #501 from dylanegan/tech/update_dotenv [David Dollar] -* Update dotenv. :v: [Dylan Egan] -* Merge pull request #498 from dgouldin/master [David Dollar] -* Preventing SIGINT from killing `foreman run` directly [David Gouldin] -* see travis.yml [David Dollar] -* Merge pull request #495 from formigarafa/patch-4 [David Dollar] -* Updated Readme [Rafael Santos] -* testing under latest versions of ruby 2.1 [Rafael Santos] -* remove noreman and alphabetize, closes #482 [David Dollar] -* Merge pull request #481 from formigarafa/patch-1 [David Dollar] -* Merge pull request #479 from rrrene/patch-1 [David Dollar] -* Updated Readme to specify supported ruby 2.1 series [Rafael Santos] -* Update travis.yml to include ruby 2.1 series [Rafael Santos] -* added ruby 2.1 series to supported versions [Rafael Santos] -* Add docs badge to README [René Föhring] -* update docs [David Dollar] -* update docs [David Dollar] - -## 0.75.0 (2014-08-27) - -* 0.75.0 [David Dollar] -* Merge pull request #478 from sergeyromanov/patch-1 [David Dollar] -* add Perl port (proclet) [Сергей Романов] -* Merge pull request #477 from dickeyxxx/windows-compat [David Dollar] -* prevent windows from crashing on startup [dickeyxxx] -* Merge pull request #474 from jingweno/patch-1 [David Dollar] -* Add `gaffer` [Jingwen Owen Ou] -* ignore .env [David Dollar] -* clean up gitignore [David Dollar] -* update docs [David Dollar] - -## 0.74.0 (2014-06-19) - -* 0.74.0 [David Dollar] -* fix gemfile.lock [David Dollar] -* Revert "Merge pull request #461 from nearapogee/master" [David Dollar] -* use FOREMAN_ for releases [David Dollar] -* update docs [David Dollar] - -## 0.73.0 (2014-06-19) - -* 0.73.0 [David Dollar] - -## 0.72.0 (2014-06-19) - -* add concurrency example to docs [David Dollar] -* update docs [David Dollar] - -## 0.71.0 (2014-06-02) - -* 0.71.0 [David Dollar] -* update release task to do everything [David Dollar] -* update docs [David Dollar] - -## 0.70.0 (2014-06-02) - -* 0.70.0 [David Dollar] -* handle interrupts during run [David Dollar] -* update thor and dotenv [David Dollar] -* excise jruby [David Dollar] -* update docs [David Dollar] -* 0.69.0 [David Dollar] -* bring all versions into execution parity [David Dollar] -* remove unused code [David Dollar] -* expand test coverage [David Dollar] -* make test more reliable [David Dollar] -* upgrade rspec [David Dollar] -* not used [David Dollar] -* Merge pull request #461 from nearapogee/master [David Dollar] -* add logging back into upstart exports. [Matt Smith] -* fix typo [David Dollar] -* add code climate test coverage [David Dollar] -* refactor a bit [David Dollar] -* Merge pull request #460 from TiuTalk/add-badges [David Dollar] -* Add CodeClimate badge [Thiago Belem] -* Add Travis badge [Thiago Belem] -* update docs [David Dollar] - -## 0.68.0 (2014-05-22) - -* 0.68.0 [David Dollar] -* tweak docs [David Dollar] -* remove jruby [David Dollar] -* separate development and test gems [David Dollar] -* tweak bundler args [David Dollar] -* excise ruby 1.8 and posix-spawn [David Dollar] -* update travis.yml for builds [David Dollar] -* fix up specs [David Dollar] -* updated rspec tests from old `should` syntax to newer `expect` syntax [irmiller22] -* updated RSpec to 2.14 [irmiller22] -* Merge pull request #454 from kevin-cantwell/master [David Dollar] -* allows project path to contain spaces [Kevin Cantwell] -* tweak readme wording [David Dollar] -* Merge pull request #444 from seamusabshere/patch-3 [David Dollar] -* hey Rubyists, don't put foreman in Gemfile [Seamus Abshere] -* update docs [David Dollar] - -## 0.67.0 (2014-04-24) - -* 0.67.0 [David Dollar] -* use thor 0.17.0 [David Dollar] -* update docs [David Dollar] - -## 0.66.0 (2014-04-23) - -* 0.66.0 [David Dollar] -* Merge pull request #439 from ssendev/patch-1 [David Dollar] -* don't fail if chown dir dosn't exist [ssendev] -* don't fail export if log/run dosn't exist [ssendev] -* update docs [David Dollar] - -## 0.65.0 (2014-04-23) - -* 0.65.0 [David Dollar] -* bump and freeze thor [David Dollar] -* Merge pull request #438 from phemmer/native_upstart [David Dollar] -* Clean up upstart export to use native upstart features [Patrick Hemmer] -* Merge pull request #364 from shokai/replace_PORT_launchd_export [David Dollar] -* Merge pull request #368 from avtobiff/remove-taskman-script [David Dollar] -* Don't make log and run dirs on export [Omar Khan] -* Merge pull request #395 from brandonhilkert/supervisor-export-env [David Dollar] -* Merge pull request #396 from phemmer/systemd-dependencies [David Dollar] -* Merge pull request #400 from toooooooby/patch-1 [David Dollar] -* Merge pull request #401 from ahawkins/patch-1 [David Dollar] -* Merge pull request #421 from JonRowe/test_writable_if_no_chown [David Dollar] -* Merge pull request #428 from beeblebrox/fix-process-exec [David Dollar] -* Merge pull request #432 from comron/fix-runit-log-permissions [David Dollar] -* Merge pull request #433 from charliesome/fix-relative-path [David Dollar] -* fix changelog [David Dollar] -* update docs [David Dollar] -* add an extra ../ when dealing with relative paths [Charlie Somerville] -* Fix mkdir mode flag when creating runit log directories [Comron Sattari] -* export: fix systemd dependencies [Patrick Hemmer] -* Exec process, otherwise only the shell receives signal. [James N. Hart] -* Test to see if we can already write to chowned dir's if chown fails [Jon Rowe] -* Use %Q{} to allow commands with quotes [Adam Hawkins] -* Improve the runit exporter to log with the stderr [TOBY] -* Quotes the values of ENV in supervisor export to guard against non-numeric values. Fixes #394. [Brandon Hilkert] -* Remove taskman script [Per Andersson] -* replace $PORT in launchd export [Sho Hashimoto] - -## 0.64.0 (2014-04-22) - -* 0.64.0 [David Dollar] -* 0.63.1 [David Dollar] -* be more specific with dotenv dependency [David Dollar] -* Merge pull request #388 from brixen/patch-1 [David Dollar] -* Update README.md [Brian Shirai] -* Merge pull request #366 from wfarr/tgz-install-foreman-to-bin [David Dollar] -* Install tgz/foreman to bin/foreman in tgz package [Will Farrington] -* Merge pull request #305 from marclennox/master [David Dollar] -* Merge pull request #360 from kjwierenga/feature/require-posix-spawn [David Dollar] -* Fail with an error on Ruby 1.8 when posix-spawn is not present. [Klaas Jan Wierenga] -* Require and use 'posix/spawn' when running ruby 1.8 without using Foreman.ruby_18? (which is the subject under test). [Klaas Jan Wierenga] -* Added start-stop-daemon support. [Marc Lennox] -* Merge pull request #353 from austiniam/master [David Dollar] -* fixed conflicts [Austin Cherry] -* modified to use shellescape instead of gsub [Austin] -* added support for directories with single quotes. fixes #315 [Austin] -* kill the children, not self [David Dollar] -* fix docs, thanks to @Invizory [David Dollar] -* not sure how this snuck in, not in the exporter format [David Dollar] -* update docs [David Dollar] -* Merge pull request #340 from ldmosquera/set_env_var_with_process_name [David Dollar] -* Merge pull request #355 from JoeyButler/fix_typo_in_man [David Dollar] -* Merge pull request #359 from kjwierenga/feature/make-ruby-18-compatible [David Dollar] -* The wrapped_command has spaces which triggers Ruby to fork a system shell (with /bin/sh -c). This causes orphaned processes on some systems (i.e. Linux). Fix this by splitting the command using String#shellsplit and using ruby's splat operator (*) to pass discrete arguments to spawn. [Klaas Jan Wierenga] -* Enable ruby 1.8.7 building on Travis. All specs should pass now on ruby 1.8.7. [Klaas Jan Wierenga] -* Use POSIX::Spawn to make foreman ruby 1.8 compatible and have all specs passing. [Klaas Jan Wierenga] -* Use pipe factory method to handle 1.8 incompatible signature for IO.pipe. [Klaas Jan Wierenga] -* Ruby 1.8 doesn't have the concept of string encodings. Compare to the string as is. [Klaas Jan Wierenga] -* Merge pull request #294 from bfulton/master [David Dollar] -* updated systemd export spec after rebasing included 5ef8bbdb [Bright Fulton] -* Fix typo in manual page. [Joey Butler] -* Add unit test for PS env var [Leonardo Mosquera] -* Change FOREMAN_PROCESS_NAME to just PS [Leonardo Mosquera] -* changelog [David Dollar] -* fix spec after d4ab495 [Bright Fulton] -* better default for things which intentionally daemonize child processes, the default KillMode is control-group which survives daemonization [Bright Fulton] -* rough draft for systemd export support [bfulton] -* modified to use shellescape instead of gsub [Austin] -* third time is the charm. :) [Austin] -* fixes #315 [Austin] -* added support for directories with single quotes. fixes #315 [Austin] -* Set FOREMAN_PROCESS_NAME env var for spawned procs [Leonardo Mosquera] - -## 0.63.0 (2013-04-15) - -* Revert "Ensure foreman is the process group leader" [John Griffin] -* remove posix-spawn dependency as it does not work in jruby 1.7.3 [Andrew Brown & Corey Downing] -* Replace Foreman::Env with dotenv [Brandon Keepers] -* [foreman-runner] fix sourcing as . is rarely in PATH [Barry Allard] -* Fixed specs to pass. [Kentaro Kuribayashi] -* Permit underscore for command name in Procfile. [Kentaro Kuribayashi] -* Update man/foreman.1 [Patrick Ellis] -* Remove tmux option from man page [Donald Plummer] -* Prevent upstart export from deleting similarly named upstart files [Andy Morris] -* Add MIT license text [Per Andersson] -* use "start|stop\ on runlevel [x]" for upstart config [Nick Messick] - -## 0.62.0 (2013-03-08) - -* Merge pull request #334 from ged/reentrant_signal_handlers [David Dollar] -* Merge pull request #335 from ged/20_encoding_fix [David Dollar] -* Try to allow children to shut down gracefully [Michael Granger] -* Add deferred signal-handling (fixes #332). [Michael Granger] -* Fix spec encoding problem under Ruby 2.0.0. [Michael Granger] -* add ruby 2.0 to travis [David Dollar] -* Merge pull request #327 from patheticpat/master [David Dollar] -* Fixed a typo in cli options description [Michael Kaiser] -* handled by mingw now [David Dollar] - -## 0.61.0 (2013-01-14) - -* Fix bug in color definitons [nseo] -* Fix for high CPU load when processes close output [Pavel Forkert] -* Ensure foreman is the process group leader [Christos Trochalakis] -* Don't ignore blank lines in the output [Matt Venables] -* Add license to gemspec [petedmarsh] -* Since JRuby 1.9 doesn't require posix/spawn, only follow that path if JRuby is loaded and running in 1.8 mode. [Adam Hutchison] -* Remove explicit requirement on rubygems. [Cyril Rohr] -* Dont use shared_path variable before multistage has a chance at it [Aditya Sanghi] -* Strip Windows Line Endings [Paul Morton] -* Fix man page: --directory is actually --root. [Evan Jones] -* Add timeout switch to CLI [Paulo Luis Franchini Casaretto] -* Remove expectation of double quotes around environment variables from test comparisons [Kevin McAllister] -* Remove explicit wrapping of Shellwords.escape in double quotes [Kevin McAllister] - -## 0.60.2 (2012-10-08) - -* Fix for nil value on io select loop, fixes #260 [Silvio Relli] - -## 0.60.1 (2012-10-08) - -* sleep on select() to avoid spinning the cpu [Silvio Relli] - -## 0.60.0 (2012-09-25) - -* foreman run can run things from the Procfile like heroku run. [Dan Peterson] - -## 0.59.0 (2012-09-15) - -* Use /bin/sh instead of bash for foreman-runner [Jeremy Evans] - -## 0.58.0 (2012-09-14) - -* dont set HOME [David Dollar] -* Add StandardOutPath to launchd export [Aaron Kalin] -* Add command argument string splitting [Aaron Kalin] -* Cleanup launchd exporter [Aaron Kalin] -* Enable trim_mode via '-' in ERB templates [Aaron Kalin] -* Add support for setting environment variables [Aaron Kalin] -* foreman run should exit with the same code as its command [Omar Khan] -* Handle multiline strings in .env file [Szymon Nowak] -* Use path and env variables in the inittab export [Indrek Juhkam] -* fixed the directory option [Arnaud Lachaume] -* Add capistrano export support [Daniel Farrell] - -## 0.57.0 (2012-08-21) - -* fix startup checks for upstart exporter [Aditya Sanghi] - -## 0.56.0 (2012-08-19) - -* read .profile, not .profile.d [David Dollar] - -## 0.55.0 (2012-08-14) - -* use a forked process to exec a run with environment [David Dollar] - -## 0.54.0 (2012-08-14) - -* use Foreman::Process to extract command running [David Dollar] -* changed to check env for bash [brntbeer] - -## 0.53.0 (2012-07-24) - -* put app root in $HOME [David Dollar] - -## 0.52.0 (2012-07-24) - -* wrap command in a runner that sources .profile.d scripts [David Dollar] -* fix upstart export specs [David Dollar] -* Make upstart export start/stop with network [Daniel Farrell] - -## 0.51.0 (2012-07-11) - -* dont try to colorize windows [David Dollar] - -## 0.50.0 (2012-07-11) - -* handle windows [David Dollar] - -## 0.49.0 (2012-07-11) - -* 1.8 compatibility [David Dollar] -* use one pgroup for all of foreman and kill that since ruby 1.8 sucks at pgroups [David Dollar] -* better debugging [David Dollar] - -## 0.48.0 (2012-07-10) - -* allow old exporter format to work, but with deprecation warning [David Dollar] -* remove debugging code [David Dollar] -* Merge pull request #219 from MarkDBlackwell/patch-1 [David Dollar] -* Avoid crash by verifying the existence of SIGHUP before accessing it. [Mark D. Blackwell] -* allow color to be forced on [David Dollar] -* terminate gracefully if stdout goes away [David Dollar] -* always flush output [David Dollar] -* Merge pull request #212 from morgoth/added-version-command [David Dollar] -* added command for displaying foreman version [Wojciech Wnętrzak] -* Merge pull request #211 from morgoth/fixed-yaml-usage [David Dollar] -* fixed using YAML [Wojciech Wnętrzak] -* test on more things, but don't fail [David Dollar] -* changelog [David Dollar] -* 0.48.0.pre1 [David Dollar] -* foreman doesn't work on ruby 1.8, may try to fix later [David Dollar] -* use bash [David Dollar] -* massive refactoring for programmatic control and stability [David Dollar] -* Merge pull request #164 from hsume2/master [David Dollar] -* Only run tmux specs if tmux is installed [Henry Hsu] -* Do not assume BUNDLE_GEMFILE [Henry Hsu] -* Add support for starting procfile in tmux session [Henry Hsu] - -## 0.47.0 (2012-06-07) - -* Fix multi-word argument handling in `foreman run`. [Daniel Brockman] -* Make 'PORT=5000 foreman start' work [Koen Van der Auwera] -* Terminate gracefully upon SIGHUP [Stefan Schüßler] -* Set port from .env if specified [Koen Van der Auwera] -* Updated bluepill exporter to use environment variables from .env [Aneeth] -* Added launchd exporter [Maxwell Swadling] -* Quote and escape environment variables in upstart templates [Matt Griffin] -* Added list of ports to other languages to README [elf Pavlik] - -## 0.46.0 (2012-05-02) - -* Add Profile load/write/append API [Michael Granger] -* Guard against missing Procfile in engine.rb [Brian Kaney] - -## 0.45.0 (2012-04-26) - -* create and chown log dir in upstart export. [Phil Hagelberg] -* remove parka from dist files [David Dollar] - -## 0.44.0 (2012-04-23) - -* make var output order repeatable in supervisord export [David Dollar] -* make --procfile and --app-root influence each other in a more intuitive way [David Dollar] -* Look for .env and app_root in the same dir as the Procfile. [Phil Hagelberg] - -## 0.43.0 (2012-04-20) - -* wrap supervisord env vars in quotes [Raphael Randschau] - -## 0.42.0 (2012-04-18) - -* Move read_environment to a public class method. [Phil Hagelberg] -* Drop parka dependency [Phil Hagelberg] -* add group support for supervisord [Raphael Randschau] -* fix enviroment export [Raphael Randschau] - -## 0.41.0 (2012-03-16) - -* replace term-ansicolor with built-in colorization [David Dollar] -* supervisord export template [Raphael Randschau] - -## 0.40.0 (2012-02-24) - -* support various quoting styles in .env [David Dollar] -* remove load_env! as it's made unnecessary by foreman run [David Dollar] -* Provide a useful error if `foreman check` fails to find a Procfile [R. Tyler Croy] -* update docs [David Dollar] - -## 0.39.0 (2012-02-07) - -* rename bin/runner to bin/foreman-runner [David Dollar] -* fix tgz release [David Dollar] -* bundle update hpricot [John Firebaugh] -* touch up .pkg release tasks [David Dollar] - -## 0.38.0 (2012-02-02) - -* bring back single process starting [David Dollar] -* more attempts at getting ci working with jruby [David Dollar] -* ignore .rbenv-version [David Dollar] -* force to binary encoding if supported [David Dollar] - -## 0.37.2 (2012-01-29) - -* handle directories with spaces in runner [David Dollar] -* update docs [David Dollar] - -## 0.37.1 (2012-01-29) - -* use binary pipes to better handle UTF-8 data [David Dollar] -* set up example procfile with UTF-8 item [David Dollar] -* remove autotest [David Dollar] -* fix up authors generation [David Dollar] -* fix up packaging after moving tasks [David Dollar] -* fix up changelog tasks [David Dollar] - -## 0.37.0 (2012-01-29) - -* put an entire line of output inside a single mutex so we don't cross the streams [David Dollar] -* fix race condition with process termination [David Dollar] -* allow external custom exporters [Chris Lowder] -* fix the test for an empty string in bin/runner [Florian Apolloner] -* ensure we have non-nil data, fixes #111 [David Dollar] -* make sure error method exists, fixes #104 [David Dollar] -* clean up chdir usage [David Dollar] -* normalize platform names [David Dollar] -* add windows support [David Dollar] -* add jruby support [David Dollar] -* pass basedir along to the runner script [David Dollar] -* harden runner script [David Dollar] -* add many missing specs [brainopia] -* clean up fakefs usage in specs [brainopia] -* runit creates a full path to export directory. [Fletcher Nichol] - -## 0.36.1 (2012-01-18) - -* 0.36.1 [David Dollar] -* bump term-ansicolor in gemspec [David Dollar] - -## 0.36.0 (2012-01-17) - -* 0.36.0 [David Dollar] -* sync the writer stream [David Dollar] -* capture stderr as well [David Dollar] - -## 0.35.0 (2012-01-16) - -* update rake [David Dollar] -* 0.35.0 [David Dollar] -* Merge pull request #132 from Viximo/feature/concurrency [David Dollar] -* Fix export specs [Matt Griffin] -* Merge branch 'master' of https://github.com/michaeldwan/foreman into feature/concurrency [Matt Griffin] -* default process concurrency is 0 when concurrency options specified, otherwise default concurrency is 1 [Michael Dwan] - -## 0.34.1 (2012-01-16) - -* 0.34.1 [David Dollar] -* fix missing start desc [David Dollar] - -## 0.34.0 (2012-01-16) - -* 0.34.0 [David Dollar] -* update man page [David Dollar] -* update docs for -d [David Dollar] -* Merge pull request #101 from ndbroadbent/foreman [David Dollar] -* Wrap around to the first colour when all the colours are used [Craig R Webster] -* run specs in random order [David Dollar] -* update rspec [David Dollar] -* pedantry [David Dollar] -* Set executable bit on runit run scripts. [Matthijs Langenberg] -* Merge pull request #114 from gburt/master [David Dollar] -* add more colors [Gabriel Burt] -* Added option to specify app_root, if executing a Procfile from a shared location [Nathan Broadbent] - -## 0.33.1 (2012-01-16) - -* 0.33.1 [David Dollar] -* Merge pull request #129 from fnichol/resolve-home-template [David Dollar] -* Expand template path under user's home directory. [Fletcher Nichol] - -## 0.33.0 (2012-01-15) - -* 0.33.0 [David Dollar] -* Revert "Merge pull request #125 from brainopia/master" [David Dollar] - -## 0.32.0 (2012-01-12) - -* 0.32.0 [David Dollar] -* Merge pull request #125 from brainopia/master [David Dollar] -* Merge pull request #121 from Viximo/feature/run [David Dollar] -* Return some whitespace that was accidentally removed [Matt Griffin] -* Steal the run method back from Thor so that it can be used in place for exec for running commands in the foreman environment. [Matt Griffin] -* Remove old cruft [brainopia] -* In case someone wants to use bin/runner directly [brainopia] -* Fix for double fork [brainopia] -* Use ruby exec which works with escaped cmd and replaces shell [brainopia] -* Fix foreman to work with cmds containing pipes and redirects [brainopia] -* Add "exec" action to allow execution of arbitrary commands with the app's environment. [Matt Griffin] -* tweak readme [David Dollar] - -## 0.31.0 (2012-01-04) - -* 0.31.0 [David Dollar] -* make fork more robust [David Dollar] -* remove unnecessary debug [David Dollar] -* add more information when shutting down [David Dollar] -* Merge pull request #110 from lstoll/master [David Dollar] -* Use different port ranges for each process type [Lincoln Stoll] - -## 0.30.1 (2011-12-23) - -* 0.30.1 [David Dollar] -* require thread for mutex [David Dollar] - -## 0.30.0 (2011-12-22) - -* 0.30.0 [David Dollar] -* compatibility with ruby 1.8 [David Dollar] - -## 0.29.0 (2011-12-22) - -* 0.29.0 [David Dollar] -* 0.28.0.pre2 [David Dollar] -* fix pipe error [David Dollar] -* 0.28.0.pre1 [David Dollar] -* Merge branch 'fork' [David Dollar] -* wip [David Dollar] -* wip [David Dollar] -* wip [David Dollar] -* wip [David Dollar] -* wip [David Dollar] - -## 0.27.0 (2011-12-05) - -* 0.27.0 [David Dollar] -* add changelog [David Dollar] -* Merge pull request #103 from csquared/load_env_from_irb [David Dollar] -* refactor load_env to apply_environment [Chris Continanza] -* rename load! to load_env! [Chris Continanza] -* use ./.env as default [Chris Continanza] -* load contents from env file [Chris Continanza] -* refactor engine to expose env methods [Chris Continanza] -* disable email notifications [David Dollar] -* add travis config [David Dollar] - -## 0.26.1 2011-12-05 - -* Merge pull request #103 from csquared/load_env_from_irb [David Dollar] -* refactor load_env to apply_environment [Chris Continanza] -* rename load! to load_env! [Chris Continanza] -* use ./.env as default [Chris Continanza] -* load contents from env file [Chris Continanza] -* refactor engine to expose env methods [Chris Continanza] -* disable email notifications [David Dollar] -* add travis config [David Dollar] diff --git a/Gemfile b/Gemfile index 07a37fc8..154b9634 100644 --- a/Gemfile +++ b/Gemfile @@ -1,18 +1,11 @@ -source "http://rubygems.org" +# frozen_string_literal: true +source "https://rubygems.org" gemspec -group :test do - gem 'rake' - gem 'fakefs' - gem 'rspec', '~> 3.5' - gem "simplecov", :require => false - gem 'timecop' -end - -group :development do - gem 'aws-s3' - gem 'ronn-ng' - gem 'yard', '~> 0.9.11' - gem 'automatiek' -end +gem "rake", "~> 13.0" +gem "rspec", "~> 3.13" +gem "rubocop", "~> 1.80" +# RuboCop accepts parallel 1.x or 2.x, but parallel 2.x requires Ruby 3.3. +# Keep development dependencies installable on Foruiman's Ruby 3.2 floor. +gem "parallel", "~> 1.27" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 00000000..203b99c9 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,96 @@ +PATH + remote: . + specs: + foruiman (0.1.2) + thor (>= 1.3, < 2) + unicode-display_width (>= 3.1, < 4) + +GEM + remote: https://rubygems.org/ + specs: + ast (2.4.3) + diff-lcs (1.6.2) + json (2.19.4) + language_server-protocol (3.17.0.5) + lint_roller (1.1.0) + parallel (1.28.0) + parser (3.3.11.1) + ast (~> 2.4.1) + racc + prism (1.9.0) + racc (1.8.1) + rainbow (3.1.1) + rake (13.4.2) + regexp_parser (2.12.0) + rspec (3.13.1) + rspec-core (~> 3.13.0) + rspec-expectations (~> 3.13.0) + rspec-mocks (~> 3.13.0) + rspec-core (3.13.5) + rspec-support (~> 3.13.0) + rspec-expectations (3.13.5) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-mocks (3.13.5) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-support (3.13.5) + rubocop (1.86.1) + json (~> 2.3) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.1.0) + parallel (>= 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.9.3, < 3.0) + rubocop-ast (>= 1.49.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.49.1) + parser (>= 3.3.7.2) + prism (~> 1.7) + ruby-progressbar (1.13.0) + thor (1.5.0) + unicode-display_width (3.2.0) + unicode-emoji (~> 4.1) + unicode-emoji (4.2.0) + +PLATFORMS + ruby + x86_64-linux + +DEPENDENCIES + foruiman! + parallel (~> 1.27) + rake (~> 13.0) + rspec (~> 3.13) + rubocop (~> 1.80) + +CHECKSUMS + ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383 + diff-lcs (1.6.2) sha256=9ae0d2cba7d4df3075fe8cd8602a8604993efc0dfa934cff568969efb1909962 + foruiman (0.1.2) + json (2.19.4) sha256=670a7d333fb3b18ca5b29cb255eb7bef099e40d88c02c80bd42a3f30fe5239ac + language_server-protocol (3.17.0.5) sha256=fd1e39a51a28bf3eec959379985a72e296e9f9acfce46f6a79d31ca8760803cc + lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87 + parallel (1.28.0) sha256=33e6de1484baf2524792d178b0913fc8eb94c628d6cfe45599ad4458c638c970 + parser (3.3.11.1) sha256=d17ace7aabe3e72c3cc94043714be27cc6f852f104d81aa284c2281aecc65d54 + prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85 + racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f + rainbow (3.1.1) sha256=039491aa3a89f42efa1d6dec2fc4e62ede96eb6acd95e52f1ad581182b79bc6a + rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701 + regexp_parser (2.12.0) sha256=35a916a1d63190ab5c9009457136ae5f3c0c7512d60291d0d1378ba18ce08ebb + rspec (3.13.1) sha256=b9f9a58fa915b8d94a1d6b3195fe6dd28c4c34836a6097015142c4a9ace72140 + rspec-core (3.13.5) sha256=ab3f682897c6131c67f9a17cfee5022a597f283aebe654d329a565f9937a4fa3 + rspec-expectations (3.13.5) sha256=33a4d3a1d95060aea4c94e9f237030a8f9eae5615e9bd85718fe3a09e4b58836 + rspec-mocks (3.13.5) sha256=e4338a6f285ada9fe56f5893f5457783af8194f5d08884d17a87321d5195ea81 + rspec-support (3.13.5) sha256=add745af535dd14b18f1209ab41ef987fdfad12786176b6a3b3619b9a7279fbf + rubocop (1.86.1) sha256=44415f3f01d01a21e01132248d2fd0867572475b566ca188a0a42133a08d4531 + rubocop-ast (1.49.1) sha256=4412f3ee70f6fe4546cc489548e0f6fcf76cafcfa80fa03af67098ffed755035 + ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33 + thor (1.5.0) sha256=e3a9e55fe857e44859ce104a84675ab6e8cd59c650a49106a05f55f136425e73 + unicode-display_width (3.2.0) sha256=0cdd96b5681a5949cdbc2c55e7b420facae74c4aaf9a9815eee1087cb1853c42 + unicode-emoji (4.2.0) sha256=519e69150f75652e40bf736106cfbc8f0f73aa3fb6a65afe62fefa7f80b0f80f + +BUNDLED WITH + 4.0.6 diff --git a/README.md b/README.md index 4b981135..a45c619e 100644 --- a/README.md +++ b/README.md @@ -1,54 +1,235 @@ -# Foreman - -[![CI](https://github.com/ddollar/foreman/actions/workflows/ci.yml/badge.svg)](https://github.com/ddollar/foreman/actions/workflows/ci.yml) - -Manage Procfile-based applications - -## Installation - - $ gem install foreman - -Ruby users should take care _not_ to install foreman in their project's `Gemfile`. See this [wiki article](https://github.com/ddollar/foreman/wiki/Don't-Bundle-Foreman) for more details. - -## Getting Started - -- http://blog.daviddollar.org/2011/05/06/introducing-foreman.html - -## Supported Ruby versions - -See [ci.yml](.github/workflows/ci.yml) for a list of Ruby versions against which Foreman is tested. - -## Documentation - -- [man page](http://ddollar.github.io/foreman/) -- [wiki](https://github.com/ddollar/foreman/wiki) -- [changelog](https://github.com/ddollar/foreman/blob/main/Changelog.md) - -## Ports - -- [forego](https://github.com/ddollar/forego) - Go -- [node-foreman](https://github.com/strongloop/node-foreman) - Node.js -- [gaffer](https://github.com/jingweno/gaffer) - Java/JVM -- [goreman](https://github.com/mattn/goreman) - Go -- [honcho](https://github.com/nickstenning/honcho) - python -- [proclet](https://github.com/kazeburo/Proclet) - Perl -- [shoreman](https://github.com/chrismytton/shoreman) - shell -- [crank](https://github.com/arktisklada/crank) - Crystal -- [houseman](https://github.com/fujimura/houseman) - Haskell -- [spm](https://github.com/bytegust/spm) - Go - -## Authors - -#### Created and maintained by - -David Dollar - -#### Patches contributed by - -[Contributor List](https://github.com/ddollar/foreman/contributors) - -## License - -Foreman is licensed under the MIT license. - -See LICENSE for the full license text. +# Foruiman + +[![CI](https://github.com/Nuzair46/foruiman/actions/workflows/ci.yml/badge.svg)](https://github.com/Nuzair46/foruiman/actions/workflows/ci.yml) + +A Procfile runner with process tabs, bounded logs, scrolling, and isolated restarts. +Foruiman is a fork of [David Dollar's Foreman](https://github.com/ddollar/foreman). +The MIT license and attribution are preserved. See [provenance](docs/UPSTREAM.md) +and [intentional compatibility differences](docs/COMPATIBILITY.md). + +Requires Ruby 3.2+ and a POSIX system with `/bin/sh` and process groups. Linux is +covered by CI on Ruby 3.2, 3.3, 3.4, and 4.0. Native Windows is unsupported; use WSL. + +## Install + +```sh +gem install foruiman +``` + +To install from a checkout: + +```sh +bundle install +gem build foruiman.gemspec +gem install --local ./foruiman-*.gem +``` + +Or run directly with `bundle exec ruby bin/foruiman`. + +## Run + +Create a `Procfile`: + +```procfile +web: bundle exec rails server -p "$PORT" +worker: bundle exec sidekiq +css: yarn build:css --watch +``` + +```sh +foruiman # default command: start +foruiman start -f Procfile.dev +foruiman start web # one entry, with its original allocated port +foruiman start --no-tui # stream logs +foruiman check # validate everything without spawning +foruiman --version +foruiman help start +``` + +Processes run independently. A failed process stays visible and does not stop its +peers. Restart a selected process with `r`; its old process group is stopped and +its remaining output drained before the replacement starts. Logs survive restarts. +The terminal interface stays open after all processes exit. + +When either stdin or stdout is not a TTY, Foruiman automatically streams plain +logs. Each completed record includes a timestamp, process name, and stream: + +```text +12:30:01 web [stdout] | Listening on port 5000 +12:30:02 worker [stderr] | Connection refused +``` + +Plain mode exits after all children and owned groups finish: `0` if all succeeded, +`1` if any failed. An explicit orderly shutdown through `q`, Ctrl-C, SIGINT, +SIGTERM, or SIGHUP returns `0`, including when TERM needs escalation to KILL. +Validation and internal failures return `1`. + +## Options + +| Option | Default | Meaning | +| --- | --- | --- | +| `-f`, `--procfile FILE` | `Procfile` | Procfile, resolved against the working directory | +| `-d`, `--root DIR` | Invocation directory | Child working directory and base for relative file paths | +| `-e`, `--env FILE` | None | Explicit environment file, loaded after optional `.env` | +| `--no-dotenv` | Load `.env` if present | Skip automatic `.env` loading | +| `-p`, `--port PORT` | `5000` | First process port; each following entry adds 100 | +| `--log-lines N` | `10000` | Positive record capacity for each process and for `all` | +| `--no-tui` | Use TUI when both streams are TTYs | Force plain output (`start` only) | + +Ports must fit `1..65535`, including the last allocation. Invalid ports, capacities, +entries, duplicate names, missing explicit files, and empty Procfiles fail before +any process is started. Names use letters, digits, `_` and `-`; `all` is reserved. +Comments and blank lines are ignored. Whitespace following the colon is the entry +separator; whitespace inside and at the end of commands is preserved. Diagnostics +include the filename and line number. + +Environment precedence is inherited environment → optional `.env` in the working +directory → explicit env file → generated `PORT` and `PS`. For example, the second +entry named `worker` gets `PORT=5100` and `PS=worker.1`. An inherited or file-defined +`PORT` does not change the base port. Parent `ENV` is never modified. + +Env files use Foreman's assignment rules: `KEY=value`, `KEY='literal'`, and +`KEY="escaped value"`. Double-quoted `\n` becomes a newline and backslash escapes +are removed. Unquoted values are preserved, including spaces and `#`. Blank lines, +comments, and lines that are not assignments are ignored. No `export`, interpolation, +command substitution, or sourcing takes place in env files. Shell expansion happens +when the Procfile command runs through `/bin/sh -c`. + +## Terminal interface + +![Foruiman terminal interface with sample logs](docs/terminal-preview.png) + +The preview uses an example terminal palette; colors follow your own theme. + +The interface follows your terminal's theme, with a layout inspired by btop and +Omarchy: framed process tabs, a highlighted selection, +consistent process colors, red stderr, amber lifecycle markers, and a compact +shortcut bar. The selected process shows its state and PID; wider layouts also +show its exit code or allocated port. `LIVE` indicates an active process stream; +`FOLLOW` remains available after exit, and `PAUSED` marks a scrolled viewport. +A scrollbar and retained-line range show where you are in the log history. +The header shows the active Procfile, including paths selected with `-f`, relative +to the working directory. Narrow layouts prioritize the filename over the project +name and shorten long paths. + +The layout adapts to smaller terminals by removing extra frames and metadata +before reducing the log area. Glyphs identify process states (`●` running, `↻` +restarting, `✓` exited, `×` failed, `■` stopped), navigation, and log follow mode. +No special font or Nerd Font is required. +Colors come from the terminal's ANSI palette and default foreground/background; +Foruiman does not impose RGB colors or a background. On a setup such as Omarchy, +the terminal's global theme supplies these colors automatically. Theme changes +apply live when the terminal updates its palette. Reverse video highlights the +selected tab using the terminal's own foreground/background, including light themes. +Set `NO_COLOR=1` for monochrome; `TERM=dumb` also disables interface colors. +Selection and bold emphasis remain visible in monochrome. Child ANSI styles, +including explicit RGB colors, remain supported and reset to terminal defaults. + +A static preview is available without starting any processes: + +```sh +ruby -Ilib script/preview.rb 116 30 +ruby -Ilib script/preview.rb 80 24 web +ruby -Ilib script/preview.rb 116 30 help +``` + +## Keyboard + +Process tabs follow Procfile order; `all` is last and selected initially. The +selected tab stays visible when there are more tabs than fit across the screen. + +| Key | Action | +| --- | --- | +| Tab / Shift-Tab, Left / Right, `h` / `l` | Previous or next tab | +| `1`–`9` | Select a process tab | +| `0` | Select `all` | +| Up / Down, `k` / `j` | Scroll a line | +| PageUp / PageDown, Ctrl-U / Ctrl-D | Scroll a page | +| Home / `g` | Oldest retained record | +| End / `G` / `f` | Follow newest output | +| Space | Toggle follow | +| `r` | Restart selected process; on `all`, restart every process | +| `R` | Restart every process from any tab | +| `s` / `S` | Stop selected process / all processes | +| `?` / Escape | Toggle help / close help | +| `q` / Ctrl-C | Shut down and quit | + +Each tab keeps its own scroll position and follow setting. Scrolling pauses follow; +new output does not move the view. Eviction or a resize clamps the view to retained +records. On the `all` tab, `r` restarts all processes. To stop processes from that +tab, use `S`; lowercase `s` requires a selected process. + +The UI shows lifecycle status, PID, exit status, and shutdown progress. It redraws +at up to approximately 30 FPS, truncates long rows horizontally, and restores the +prior terminal input mode, cursor, and screen after normal exit or an exception. +Very small terminals show a compact message; shortcuts continue working. + +## Logs and cleanup + +Both per-process rings and the aggregate ring have independent limits. Immutable +records are shared between rings and have globally increasing sequence identities. +Partial output appears live in the TUI and keeps its identity when completed. +Plain mode emits at newline or EOF; records reaching the 16 KiB limit are also +completed and emitted. Each stream has bounded pending data; reads are budgeted +per event-loop iteration. Old output cannot grow retention without bound. + +Supported SGR styles (colors, intensity, italics, underline, blink, inverse, conceal, +and strike) are retained in the TUI. Cursor/screen controls, OSC, DCS, and clipboard +sequences are suppressed. UTF-8 and escape sequences may arrive in fragments. +Invalid bytes become replacement characters. Carriage returns are ignored; tabs +become four spaces. Styles reset at row boundaries, and each row carries the stream's +style snapshot. Unicode width uses `unicode-display_width`, treating combined emoji +as two cells. Plain output strips styles. + +Every entry has its own process group, separate stdout/stderr pipes, and `/dev/null` +stdin. Child programs cannot interact with the terminal. Shutdown cancels pending +restarts, sends TERM to all owned groups, escalates after five seconds, drains pipes, +and reaps direct children. Descendants are tracked even when their group leader +exits. On Linux, orphan zombies awaiting the system reaper do not hold shutdown open; +they are no longer running. Processes deliberately escaping their group by daemonizing +are outside v1. Run servers in the foreground. + +Internal exception details go to stderr in plain mode. Interactive exceptions go +to a private `foruiman-*.log` temporary file (mode 0600); the restored terminal shows +its path. Normal child output never goes to this diagnostic file. + +See [Rails usage](docs/RAILS.md), [supervisor API and architecture](docs/ARCHITECTURE.md), +and [implementation assumptions](docs/ASSUMPTIONS.md). + +## Development + +```sh +bundle install +bundle exec rspec +bundle exec rubocop +gem build foruiman.gemspec +bundle exec ruby script/smoke_gem.rb +``` + +The suite includes adapted upstream parser and environment cases, Ruby subprocess +fixtures, bounded-output tests, fake-terminal tests, and real PTYs. Process tests +clean up their fixtures even when assertions fail. Nothing here requires Rails. + +## Release + +Releases use RubyGems trusted publishing, so the repository does not store a +long-lived RubyGems API key. Configure the `foruiman` gem (or a pending trusted +publisher before its first release) with these values on RubyGems.org: + +| Setting | Value | +| --- | --- | +| Repository owner | `Nuzair46` | +| Repository name | `foruiman` | +| Workflow filename | `release.yml` | +| Environment | `release` | + +Set the version in `lib/foruiman/version.rb`, commit it, and push a matching tag: + +```sh +VERSION=$(ruby -Ilib -rforuiman/version -e 'print Foruiman::VERSION') +git tag "v$VERSION" +git push origin "v$VERSION" +``` + +GitHub Actions runs the complete Ruby 3.2–4.0 test matrix, lint and package checks, +then publishes the gem to RubyGems.org using a short-lived OpenID Connect token. diff --git a/Rakefile b/Rakefile index 8f701152..538ab48e 100644 --- a/Rakefile +++ b/Rakefile @@ -1,8 +1,7 @@ -$:.unshift File.expand_path("../lib", __FILE__) -require "foreman" +# frozen_string_literal: true -require "bundler/setup" +require "rspec/core/rake_task" +require "bundler/gem_tasks" -Dir[File.expand_path("../tasks/*.rake", __FILE__)].each do |task| - load task -end +RSpec::Core::RakeTask.new(:spec) +task default: :spec diff --git a/bin/foreman b/bin/foreman deleted file mode 100755 index 18f41af7..00000000 --- a/bin/foreman +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env ruby - -$:.unshift File.expand_path("../../lib", __FILE__) - -require "foreman/cli" - -Foreman::CLI.start diff --git a/bin/foreman-runner b/bin/foreman-runner deleted file mode 100755 index 9709a1df..00000000 --- a/bin/foreman-runner +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/sh -# -#/ Usage: foreman-runner [-d ] [-p] [...] -#/ -#/ Run a command with exec, optionally changing directory first - -set -e - -error() { - echo $@ >&2 - exit 1 -} - -usage() { - cat $0 | grep '^#/' | cut -c4- - exit -} - -read_profile="" - -while getopts ":hd:p" OPT; do - case $OPT in - d) cd "$OPTARG" ;; - p) read_profile="1" ;; - h) usage ;; - \?) error "invalid option: -$OPTARG" ;; - :) error "option -$OPTARG requires an argument" ;; - esac -done - -shift $((OPTIND-1)) - -[ -z "$1" ] && usage - -if [ "$read_profile" = "1" ]; then - if [ -f .profile ]; then - . ./.profile - fi -fi - -exec "$@" diff --git a/bin/foruiman b/bin/foruiman new file mode 100755 index 00000000..5f1c099d --- /dev/null +++ b/bin/foruiman @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +$LOAD_PATH.unshift(File.expand_path("../lib", __dir__)) +require "foruiman/cli" +Foruiman::CLI.start(ARGV) diff --git a/data/example/.profile.d/foo.sh b/data/example/.profile.d/foo.sh deleted file mode 100644 index b15710a4..00000000 --- a/data/example/.profile.d/foo.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -export FOO=bar diff --git a/data/example/Procfile b/data/example/Procfile deleted file mode 100644 index 219cd90a..00000000 --- a/data/example/Procfile +++ /dev/null @@ -1,4 +0,0 @@ -ticker: ruby ./ticker $PORT -error: ruby ./error -utf8: ruby ./utf8 -spawner: ./spawner diff --git a/data/example/Procfile.without_colon b/data/example/Procfile.without_colon deleted file mode 100644 index d6451a9a..00000000 --- a/data/example/Procfile.without_colon +++ /dev/null @@ -1,2 +0,0 @@ -ticker ./ticker $PORT -error ./error \ No newline at end of file diff --git a/data/example/error b/data/example/error deleted file mode 100755 index 2ef00b42..00000000 --- a/data/example/error +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env ruby - -$stdout.sync = true - -puts "will error in 10s" -sleep 5 -raise "Dying" diff --git a/data/example/log/neverdie.log b/data/example/log/neverdie.log deleted file mode 100644 index a8ce2552..00000000 --- a/data/example/log/neverdie.log +++ /dev/null @@ -1,4 +0,0 @@ -tick -tick -./never_die:6:in `sleep': Interrupt - from ./never_die:6 diff --git a/data/example/spawnee b/data/example/spawnee deleted file mode 100755 index afdcf490..00000000 --- a/data/example/spawnee +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh - -NAME="$1" - -sigterm() { - echo "$NAME: got sigterm" -} - -#trap sigterm SIGTERM - -while true; do - echo "$NAME: ping $$" - sleep 1 -done diff --git a/data/example/spawner b/data/example/spawner deleted file mode 100755 index 8c1a6fc3..00000000 --- a/data/example/spawner +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -./spawnee A & -./spawnee B & -./spawnee C & - -wait diff --git a/data/example/ticker b/data/example/ticker deleted file mode 100755 index fe0d6290..00000000 --- a/data/example/ticker +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env ruby - -$stdout.sync = true - -%w( SIGINT SIGTERM ).each do |signal| - trap(signal) do - puts "received #{signal} but i'm ignoring it!" - end -end - -while true - puts "tick: #{ARGV.inspect} -- FOO:#{ENV["FOO"]}" - sleep 1 -end diff --git a/data/example/utf8 b/data/example/utf8 deleted file mode 100755 index 00b90a28..00000000 --- a/data/example/utf8 +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env ruby -# encoding: BINARY - -$stdout.sync = true - -while true - puts "\u65e5\u672c\u8a9e\u6587\u5b57\u5217" - puts "\u0915\u0932\u094d\u0907\u0928\u0643\u0637\u0628\u041a\u0430\u043b\u0438\u043d\u0430" - puts "\xff\x03" - sleep 1 -end diff --git a/data/export/bluepill/master.pill.erb b/data/export/bluepill/master.pill.erb deleted file mode 100644 index a192aaa8..00000000 --- a/data/export/bluepill/master.pill.erb +++ /dev/null @@ -1,28 +0,0 @@ -Bluepill.application("<%= app %>", :foreground => false, :log_file => "/var/log/bluepill.log") do |app| - - app.uid = "<%= user %>" - app.gid = "<%= user %>" - -<% engine.each_process do |name, process| %> -<% 1.upto(engine.formation[name]) do |num| %> - <% port = engine.port_for(process, num) %> - app.process("<%= name %>-<%= num %>") do |process| - process.start_command = %Q{<%= process.command %>} - - process.working_dir = "<%= engine.root %>" - process.daemonize = true - process.environment = {<%= engine.env.merge("PORT" => port.to_s).map { |k,v| "#{k.inspect}=>#{v.inspect}" }.join(",") %>} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "<%= log %>/<%= app %>-<%= name %>-<%= num %>.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "<%= app %>-<%= name %>" - end -<% end %> -<% end %> -end diff --git a/data/export/daemon/master.conf.erb b/data/export/daemon/master.conf.erb deleted file mode 100644 index 0b2d2f70..00000000 --- a/data/export/daemon/master.conf.erb +++ /dev/null @@ -1,14 +0,0 @@ -pre-start script - -bash << "EOF" -mkdir -p <%= log %> -chown -R <%= user %> <%= log %> -mkdir -p <%= run %> -chown -R <%= user %> <%= run %> -EOF - -end script - -start on runlevel [2345] - -stop on runlevel [016] diff --git a/data/export/daemon/process.conf.erb b/data/export/daemon/process.conf.erb deleted file mode 100644 index 9220dadc..00000000 --- a/data/export/daemon/process.conf.erb +++ /dev/null @@ -1,8 +0,0 @@ -start on starting <%= app %>-<%= name.gsub('_', '-') %> -stop on stopping <%= app %>-<%= name.gsub('_', '-') %> -respawn - -env PORT=<%= port %><% engine.env.each_pair do |var, env| %> -env <%= var %>=<%= env %><% end %> - -exec start-stop-daemon --start --chuid <%= user %> --chdir <%= engine.root %> --make-pidfile --pidfile <%= run %>/<%= app %>-<%= name %>-<%= num %>.pid --exec <%= executable %><%= arguments %> >> <%= log %>/<%= app %>-<%= name %>-<%= num %>.log 2>&1 diff --git a/data/export/daemon/process_master.conf.erb b/data/export/daemon/process_master.conf.erb deleted file mode 100644 index c9cc8515..00000000 --- a/data/export/daemon/process_master.conf.erb +++ /dev/null @@ -1,2 +0,0 @@ -start on starting <%= app %> -stop on stopping <%= app %> diff --git a/data/export/launchd/launchd.plist.erb b/data/export/launchd/launchd.plist.erb deleted file mode 100644 index a746386a..00000000 --- a/data/export/launchd/launchd.plist.erb +++ /dev/null @@ -1,33 +0,0 @@ - - - - - Label - <%= "#{app}-#{name}-#{num}" %> - EnvironmentVariables - - <%- engine.env.merge("PORT" => port).each_pair do |var,env| -%> - <%= var %> - <%= env %> - <%- end -%> - - ProgramArguments - - <%- command_args.each do |command| -%> - <%= command %> - <%- end -%> - - KeepAlive - - RunAtLoad - - StandardOutPath - <%= log %>/<%= app %>-<%= name %>-<%=num%>.log - StandardErrorPath - <%= log %>/<%= app %>-<%= name %>-<%=num%>.log - UserName - <%= user %> - WorkingDirectory - <%= engine.root %> - - diff --git a/data/export/runit/log/run.erb b/data/export/runit/log/run.erb deleted file mode 100644 index f5e3a2b6..00000000 --- a/data/export/runit/log/run.erb +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -set -e - -LOG=<%= log %>/<%= name %>-<%= num %> - -test -d "$LOG" || mkdir -p -m 2750 "$LOG" && chown <%= user %> "$LOG" -exec chpst -u <%= user %> svlogd "$LOG" diff --git a/data/export/runit/run.erb b/data/export/runit/run.erb deleted file mode 100644 index 4d6ceed9..00000000 --- a/data/export/runit/run.erb +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -cd <%= engine.root %> -exec 2>&1 -exec chpst -u <%= user %> -e <%= File.join(location, "#{process_directory}/env") %> <%= process.command %> diff --git a/data/export/supervisord/app.conf.erb b/data/export/supervisord/app.conf.erb deleted file mode 100644 index 7dd12d87..00000000 --- a/data/export/supervisord/app.conf.erb +++ /dev/null @@ -1,31 +0,0 @@ -<% -app_names = [] -engine.each_process do |name, process| - 1.upto(engine.formation[name]) do |num| - port = engine.port_for(process, num) - full_name = "#{app}-#{name}-#{num}" - environment = engine.env.merge("PORT" => port.to_s).map do |key, value| - value = shell_quote(value) - value = value.gsub('\=', '=') - value = value.gsub('\&', '&') - value = value.gsub('\?', '?') - "#{key}=\"#{value}\"" - end - app_names << full_name --%> -[program:<%= full_name %>] -command=<%= process.command %> -autostart=true -autorestart=true -stdout_logfile=<%= log %>/<%= name %>-<%= num %>.log -stderr_logfile=<%= log %>/<%= name %>-<%= num %>.error.log -user=<%= user %> -directory=<%= engine.root %> -environment=<%= environment.join(',') %> - -<% - end -end --%> -[group:<%= app %>] -programs=<%= app_names.join(',') %> diff --git a/data/export/systemd/master.target.erb b/data/export/systemd/master.target.erb deleted file mode 100644 index 81ec0f32..00000000 --- a/data/export/systemd/master.target.erb +++ /dev/null @@ -1,5 +0,0 @@ -[Unit] -Wants=<%= service_names.join(' ') %> - -[Install] -WantedBy=multi-user.target diff --git a/data/export/systemd/process.service.erb b/data/export/systemd/process.service.erb deleted file mode 100644 index 87497bee..00000000 --- a/data/export/systemd/process.service.erb +++ /dev/null @@ -1,21 +0,0 @@ -[Unit] -PartOf=<%= app %>.target -StopWhenUnneeded=yes - -[Service] -User=<%= user %> -WorkingDirectory=<%= engine.root %> -Environment=PORT=<%= port %> -Environment=PS=<%= process_name %> -<% engine.env.each_pair do |var,env| -%> -Environment="<%= var %>=<%= env %>" -<% end -%> -ExecStart=/bin/bash -lc 'exec -a "<%= app %>-<%= process_name %>" <%= process.command %>' -Restart=always -RestartSec=14s -StandardInput=null -StandardOutput=syslog -StandardError=syslog -SyslogIdentifier=%n -KillMode=mixed -TimeoutStopSec=<%= engine.options[:timeout] %> diff --git a/data/export/upstart/master.conf.erb b/data/export/upstart/master.conf.erb deleted file mode 100644 index 7bf1666f..00000000 --- a/data/export/upstart/master.conf.erb +++ /dev/null @@ -1,2 +0,0 @@ -start on runlevel [2345] -stop on runlevel [!2345] diff --git a/data/export/upstart/process.conf.erb b/data/export/upstart/process.conf.erb deleted file mode 100644 index aff4b64b..00000000 --- a/data/export/upstart/process.conf.erb +++ /dev/null @@ -1,15 +0,0 @@ -start on starting <%= app %>-<%= name %> -stop on stopping <%= app %>-<%= name %> -respawn - -env PORT=<%= port %> -<% engine.env.each do |name,value| -%> -<% next if name.upcase == "PORT" -%> -env <%= name %>='<%= value.gsub(/'/, "'\"'\"'") %>' -<% end -%> - -setuid <%= user %> - -chdir <%= engine.root %> - -exec <%= process.command %> diff --git a/data/export/upstart/process_master.conf.erb b/data/export/upstart/process_master.conf.erb deleted file mode 100644 index c9cc8515..00000000 --- a/data/export/upstart/process_master.conf.erb +++ /dev/null @@ -1,2 +0,0 @@ -start on starting <%= app %> -stop on stopping <%= app %> diff --git a/dist/gem.rake b/dist/gem.rake deleted file mode 100644 index 8a080e17..00000000 --- a/dist/gem.rake +++ /dev/null @@ -1,14 +0,0 @@ -file pkg("foreman-#{version}.gem") => distribution_files do |t| - sh "gem build foreman.gemspec" - sh "mv foreman-#{version}.gem #{t.name}" -end - -task "gem:build" => pkg("foreman-#{version}.gem") - -task "gem:clean" do - clean pkg("foreman-#{version}.gem") -end - -task "gem:release" => "gem:build" do |t| - sh "gem push #{pkg("foreman-#{version}.gem")} || echo 'error'" -end diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 00000000..1c4a59e8 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,84 @@ +# Architecture and embedding + +`Procfile` retains Foreman's ordered parser/writer API with strict file validation. +`Env` retains its quoting rules and adds a non-mutating precedence merge. `Process` +wraps `/bin/sh -c` with a new process group, two output streams, and null stdin. +`CLI < Thor` validates the full configuration before starting the engine. + +`Engine` owns registration, PID/group tracking, nonblocking pipes, child reaping, +and lifecycle transitions. A single caller thread drives all mutations. Signal +handlers only set a flag and wake a self-pipe. The loop reaps only its own direct +children, services bounded reads in round-robin order, checks TERM deadlines, and +starts pending replacements once old groups and pipes are finished. Group existence +is tracked independently of leader status; Linux `/proc` distinguishes running +members from orphan zombies awaiting the system reaper. + +```ruby +require "foruiman" + +env = Foruiman::Env.load(root: Dir.pwd) +engine = Foruiman::Engine.new(procfile: "Procfile", env: env, log_lines: 2_000) +engine.on_event do |event| + # Types: output, started, restarting, stopping, exited, killed, failed. + # Fields: type, name, pid, status, record, message. + # Output records add sequence, stream, time, text, complete. +end + +engine.run # install handlers, start all, loop, clean up, restore handlers; returns 0/1 +``` + +For an embedded event loop: + +```ruby +begin + engine.start_all # or engine.start("web") + engine.tick(timeout: 0.03) + engine.restart("web") # asynchronous; peers keep running + engine.stop("worker") # asynchronous + engine.shutdown # cancels replacements and requests group cleanup + engine.tick until engine.finished? +ensure + engine.close # finishes cleanup, closes pipes; safe to repeat +end +``` + +Call engine methods and event listeners on the driving thread; this is not a +cross-thread messaging API. `run` handles INT/TERM/HUP and restores existing +handlers. An embedding loop that drives `tick` directly owns its signal handling. +`close` disconnects observers so a failed renderer/output consumer cannot prevent +process cleanup. `term_timeout:` exists for deterministic embedded tests; CLI +shutdown always uses five seconds. `state(name)` exposes lifecycle state for +rendering; callers should not mutate it. + +`LogStore` uses per-process `Ring` instances and an aggregate `Ring`, each with O(1) +append, eviction, record replacement, and identity lookup. Immutable `Data` records +are shared. A partial record has one sequence identity; completing it replaces +retained references without re-inserting an already evicted aggregate record. +Sequence order represents first observation, not line completion time. Actual +memory use depends on line length and ring capacity; retained text is bounded by +approximately `(process_count + 1) * capacity * 16 KiB`, plus fixed per-stream and +per-record overhead, with overlap shared between rings. + +`Output` bounds each stream, handles partial records, and takes style snapshots. +`ANSI::Decoder` incrementally decodes UTF-8 and suppresses terminal controls; +`ANSI::Styles` keeps bounded independent style properties across rows. A long line +is split into completed records at the size limit. + +The TUI loads only in interactive mode. `Terminal` owns raw input and alternate +screen restoration. `Keyboard` decodes fragmented key sequences. `State` stores +selection/help/feedback, and each tab owns a `Viewport` anchored by record identity. +`Renderer` composes framed process navigation, a log pane with a scrollbar, and a +shortcut bar. Its shared log-height calculation keeps paging consistent with the +responsive layout. `Text` measures graphemes through `unicode-display_width` and +clips rows safely. `Theme` uses the terminal's ANSI palette, default foreground and +background, and reverse-video selection, with a monochrome fallback. It does not +read OS theme files or override palette entries; child SGR resets restore terminal +defaults. The header uses the engine's `procfile_path` to identify the loaded file. +`LogFormatter` aligns timestamps, +process names, stream markers, and content. Complete frames reset styles at each row. `Application` connects input and lifecycle +commands to the engine and limits drawing to 30 FPS. Resize handling reads current +terminal dimensions each loop; it does not replace an application's WINCH handler. + +`Plain` prints completed records and runs to natural completion. `Diagnostics` +keeps internal exceptions separate from process logs, using a private temporary +file in interactive mode and stderr otherwise. diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md new file mode 100644 index 00000000..0a6d66c8 --- /dev/null +++ b/docs/ASSUMPTIONS.md @@ -0,0 +1,23 @@ +# Inputs and implementation defaults + +The implementation workspace was empty. The RFC referenced by the supplied plan, +its requested file list, and earlier preference selections were not present. The +supplied Foreman-based MVP plan is the implementation contract available here. +The missing RFC was requested during implementation; these choices fill the gaps: + +- Default command `start`; also `start PROCESS`, `check`, `version`, `help`. +- Foreman's `-f`, `-d`, `-e`, `-p` aliases; `--log-lines`, `--no-tui`, `--no-dotenv`. +- Default capacity 10,000 records per ring. +- Process tabs in entry order, then `all`; select `all` initially. +- `all` reserved as a process name to avoid an ambiguous aggregate tab. +- Vim-style and arrow navigation, digits, `f`, Space, `r`/`R`, `s`/`S`, `?`, `q`. +- Generated `PS=name.1`, as in Foreman; no other generated variables. +- Relative file paths resolved against invocation directory or explicit `-d`. +- Header whitespace after a Procfile colon is a separator; command-internal and + trailing whitespace is preserved. +- 30 FPS maximum; 16 KiB records; 64 KiB total read budget per event-loop iteration. +- No public repository URL is invented for the unpublished Foruiman project. + +See README for the actual public interface. These defaults can be reconciled with +the original RFC when it becomes available; missing requirements are not claimed +as verified. diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md new file mode 100644 index 00000000..66dcafac --- /dev/null +++ b/docs/COMPATIBILITY.md @@ -0,0 +1,27 @@ +# Intentional differences from Foreman + +Foruiman is a fork-derived MVP, not a drop-in replacement for every Foreman feature. + +| Area | Foruiman behavior | +| --- | --- | +| Identity | `foruiman` gem/executable, `Foruiman` namespace, version 0.1.2 | +| Runtime | Ruby 3.2+, POSIX process groups; Linux CI | +| CLI | Thor-based `start [PROCESS]`, `check`, `version`, and `help` | +| Excluded features | No export, scaling/formation, `run`, `.foreman` YAML, custom shutdown timeout, forced color, or timestamp toggle | +| Procfile validation | Reject malformed lines, duplicates, empty commands, and reserved `all`; report line numbers | +| Working directory | Invocation directory unless `-d`; moving a Procfile does not change child cwd | +| Environment | Optional `.env` then explicit env file; parent `ENV` stays untouched | +| Ports | 5000 or `-p`, plus 100 per original entry; `PORT` in the environment is overridden | +| Expansion | `/bin/sh -c` performs shell expansion; no Ruby string substitution | +| Instances | Exactly one instance per entry; `PS=name.1` | +| Failures | Independent process failures; peers keep running | +| Restart | Stop only the affected group, wait for descendants and output, then replace | +| Shutdown | TERM, five-second grace, KILL; track groups after leader exit; restore prior signal handlers | +| Output | Separate stdout/stderr metadata; bounded logs and live partial records | +| Terminal | Tabs, independent scroll/follow, restart and stop controls; no child stdin | +| Plain exit | Wait for all processes; status 0/1; explicit orderly shutdown returns 0 | +| Interactive exit | Remain open after all processes exit; quit explicitly | + +Commands needing a PTY, interactive child input, or background daemonization are +outside this release. Remote process control, persistence across Foruiman sessions, +search, horizontal scrolling, and log export are not provided. diff --git a/docs/RAILS.md b/docs/RAILS.md new file mode 100644 index 00000000..f0b3ff94 --- /dev/null +++ b/docs/RAILS.md @@ -0,0 +1,54 @@ +# Using Foruiman with Rails + +Install the locally built Foruiman gem as a development tool using the README's +instructions. Keep it outside the Rails application's Gemfile when using a global +development-tool installation. The Rails processes can still run under `bundle exec`. + +A typical `Procfile.dev`: + +```procfile +web: bin/rails server -p "$PORT" +worker: bundle exec sidekiq +css: yarn build:css --watch +``` + +Include only entries used by your app. For a Vite application, replace the CSS entry +with your project's foreground Vite command, for example `vite: bin/vite dev`. +Use your app's existing port configuration for tools that do not read `PORT`. + +An optional `.env` in the Rails project root: + +```dotenv +RAILS_ENV=development +REDIS_URL=redis://localhost:6379/0 +``` + +Keep secrets out of version control. Foruiman reads this file as assignments; it +does not source it as a shell script. + +From the Rails root: + +```sh +foruiman start -f Procfile.dev +foruiman start -f Procfile.dev -p 3000 +``` + +The second example assigns 3000 to `web`, 3100 to `worker`, and 3200 to `css`. +Only programs that consume their generated `PORT` use those values. The base port +is set with `-p`; a `PORT` assignment in `.env` does not set it. + +An optional `bin/dev`: + +```sh +#!/bin/sh +exec foruiman start -f Procfile.dev "$@" +``` + +Select the web tab and press `r` to restart Rails without interrupting the worker +or asset watcher. On the `all` tab, `r` restarts all entries; `R` does so from any +tab. The header shows the active Procfile. `q` or Ctrl-C stops all owned process +groups, including grandchildren, before returning to the shell. + +Redirect output with `foruiman start -f Procfile.dev > development.log` to use plain +mode. A failed worker will not stop Rails; plain mode finishes only after every +entry exits or Foruiman receives a shutdown signal. diff --git a/docs/UPSTREAM.md b/docs/UPSTREAM.md new file mode 100644 index 00000000..170d704a --- /dev/null +++ b/docs/UPSTREAM.md @@ -0,0 +1,25 @@ +# Foreman provenance + +- Repository: https://github.com/ddollar/foreman +- Revision: `f65ddba83932bd4670e014389d6e27ea1e20b469` (`update docs`) +- Source archive: https://codeload.github.com/ddollar/foreman/tar.gz/f65ddba83932bd4670e014389d6e27ea1e20b469 +- License: MIT, Copyright (c) 2012 David Dollar; preserved verbatim in `LICENSE`. + +The initial local import copied `lib/foreman/{procfile,env,process,engine,cli}.rb` +into the renamed namespace before applying the MVP changes. The Procfile +reader/writer, environment assignment/quoting parser, process execution wrapper, +ordered engine registration and lookup, pipe/signal approach, and Thor command +foundation derive from that source. The supervisor loop and terminal components +were refactored or written for Foruiman's independent process and log semantics. + +Relevant upstream test files are retained verbatim as review references in +`docs/upstream/*_spec.rb.txt` (not part of the packaged gem). Active tests in +`spec/foruiman/procfile_spec.rb`, `env_spec.rb`, and `process_spec.rb` adapt the +applicable upstream examples to real temporary files and managed Ruby fixtures. +The CLI and engine tests cover the new contract rather than upstream concurrency, +export, command substitution, or stop-on-first-exit behavior. + +`docs/upstream/SHA256SUMS` records the original imported source/test checksums. +Exporters, distribution code, scaling, and obsolete runtime compatibility code are +not included in the distributed implementation. There is no runtime dependency +on the Foreman gem and no claim of complete Foreman compatibility. diff --git a/docs/terminal-preview.png b/docs/terminal-preview.png new file mode 100644 index 00000000..1bad6f17 Binary files /dev/null and b/docs/terminal-preview.png differ diff --git a/docs/upstream/SHA256SUMS b/docs/upstream/SHA256SUMS new file mode 100644 index 00000000..06ed8aa8 --- /dev/null +++ b/docs/upstream/SHA256SUMS @@ -0,0 +1,10 @@ +2ea6256739b0f021fc38053d3c9ce7103a404033b946c0d7f660b34097044d2e LICENSE +97301d9ab09b4765d8c74c36b4a910b32452f85e4afca5707e3b63c9efb0e311 lib/foreman/cli.rb +0fd046bab9a1c30de191126a5961b0b88d32c8b56b368f050783f266ee40012c lib/foreman/engine.rb +5a9713f8cf661cefbe03e9d7b23d59a690eb1bf5ebe4df740a4b22e604c1516b lib/foreman/env.rb +84b32a72789bf48f01907702904fead7360fec7e9378364c39786cc7b2c197b5 lib/foreman/process.rb +f6c68ad45d14b401109c58f2d20a47f418bec97b228a420eba625364325d4fa7 lib/foreman/procfile.rb +b70ab30beae9bc62704171ac175d14ca0487ce7282772195d0d6e9e081235273 spec/foreman/cli_spec.rb +0e1013987eaabe332ea6cf1727300dc0d3c4b455890355d58fa55b3f75e08b42 spec/foreman/engine_spec.rb +2b0e7ef533a17ad20a7d2c571a5a3a4f97be1e5f8755642ca3b5f98651cf1c74 spec/foreman/process_spec.rb +6d135bd5e0d3948c1efa2f88d2a94d1318c53ba0e2a3399210345770b08e0fe5 spec/foreman/procfile_spec.rb diff --git a/spec/foreman/cli_spec.rb b/docs/upstream/cli_spec.rb.txt similarity index 100% rename from spec/foreman/cli_spec.rb rename to docs/upstream/cli_spec.rb.txt diff --git a/spec/foreman/engine_spec.rb b/docs/upstream/engine_spec.rb.txt similarity index 100% rename from spec/foreman/engine_spec.rb rename to docs/upstream/engine_spec.rb.txt diff --git a/spec/foreman/process_spec.rb b/docs/upstream/process_spec.rb.txt similarity index 100% rename from spec/foreman/process_spec.rb rename to docs/upstream/process_spec.rb.txt diff --git a/spec/foreman/procfile_spec.rb b/docs/upstream/procfile_spec.rb.txt similarity index 100% rename from spec/foreman/procfile_spec.rb rename to docs/upstream/procfile_spec.rb.txt diff --git a/foreman.gemspec b/foreman.gemspec deleted file mode 100644 index 42ff9c8a..00000000 --- a/foreman.gemspec +++ /dev/null @@ -1,21 +0,0 @@ -$:.unshift File.expand_path("../lib", __FILE__) -require "foreman/version" - -Gem::Specification.new do |gem| - gem.name = "foreman" - gem.license = "MIT" - gem.version = Foreman::VERSION - - gem.author = "David Dollar" - gem.email = "ddollar@gmail.com" - gem.homepage = "https://github.com/ddollar/foreman" - gem.summary = "Process manager for applications with multiple components" - - gem.description = gem.summary - - gem.executables = "foreman" - gem.files = Dir["**/*"].select { |d| d =~ %r{^(README|bin/|data/|ext/|lib/|spec/|test/)} } - gem.files << "man/foreman.1" - - gem.add_runtime_dependency "thor", "~> 1.4" -end diff --git a/foruiman.gemspec b/foruiman.gemspec new file mode 100644 index 00000000..330201aa --- /dev/null +++ b/foruiman.gemspec @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +require_relative "lib/foruiman/version" + +Gem::Specification.new do |spec| + spec.name = "foruiman" + spec.version = Foruiman::VERSION + spec.authors = ["Foruiman contributors", "David Dollar"] + spec.summary = "A Procfile supervisor with process tabs, bounded logs, and isolated restarts" + spec.description = "Run a Procfile in a terminal interface or a plain stream. Derived from Foreman." + spec.license = "MIT" + spec.homepage = "https://github.com/Nuzair46/foruiman" + spec.required_ruby_version = ">= 3.2" + spec.files = Dir["lib/**/*.rb", "bin/foruiman", "README.md", "LICENSE", "CHANGELOG.md", "docs/*.{md,png}"] + spec.bindir = "bin" + spec.executables = ["foruiman"] + spec.require_paths = ["lib"] + spec.metadata["rubygems_mfa_required"] = "true" + spec.metadata["source_code_uri"] = "https://github.com/Nuzair46/foruiman" + spec.metadata["changelog_uri"] = "https://github.com/Nuzair46/foruiman/blob/main/CHANGELOG.md" + spec.add_dependency "thor", ">= 1.3", "< 2" + spec.add_dependency "unicode-display_width", ">= 3.1", "< 4" +end diff --git a/lib/foreman.rb b/lib/foreman.rb deleted file mode 100644 index ca3f754f..00000000 --- a/lib/foreman.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "foreman/version" - -module Foreman - - def self.runner - File.expand_path("../../bin/foreman-runner", __FILE__) - end - - def self.ruby_18? - defined?(RUBY_VERSION) and RUBY_VERSION =~ /^1\.8\.\d+/ - end - - def self.windows? - defined?(RUBY_PLATFORM) and RUBY_PLATFORM =~ /(win|w)32$/ - end - -end diff --git a/lib/foreman/cli.rb b/lib/foreman/cli.rb deleted file mode 100644 index 1d2eb812..00000000 --- a/lib/foreman/cli.rb +++ /dev/null @@ -1,171 +0,0 @@ -require "foreman" -require "foreman/helpers" -require "foreman/engine" -require "foreman/engine/cli" -require "foreman/export" -require "foreman/version" -require "shellwords" -require "thor" -require "yaml" - -class Foreman::CLI < Thor - - include Foreman::Helpers - - map ["-v", "--version"] => :version - - class_option :procfile, :type => :string, :aliases => "-f", :desc => "Default: Procfile" - class_option :root, :type => :string, :aliases => "-d", :desc => "Default: Procfile directory" - - desc "start [PROCESS]", "Start the application (or a specific PROCESS)" - - method_option :color, :type => :boolean, :aliases => "-c", :desc => "Force color to be enabled" - method_option :env, :type => :string, :aliases => "-e", :desc => "Specify an environment file to load, defaults to .env" - method_option :formation, :type => :string, :aliases => "-m", :banner => '"alpha=5,bar=3"', :desc => 'Specify what processes will run and how many. Default: "all=1"' - method_option :port, :type => :numeric, :aliases => "-p" - method_option :timeout, :type => :numeric, :aliases => "-t", :desc => "Specify the amount of time (in seconds) processes have to shutdown gracefully before receiving a SIGKILL, defaults to 5." - method_option :timestamp, :type => :boolean, :default => true, :desc => "Include timestamp in output" - - class << self - def exit_on_failure? - true - end - - # Hackery. Take the run method away from Thor so that we can redefine it. - def is_thor_reserved_word?(word, type) - return false if word == "run" - super - end - end - - def start(process=nil) - check_procfile! - load_environment! - engine.load_procfile(procfile) - engine.options[:formation] = "#{process}=1" if process - engine.start - rescue Foreman::Procfile::EmptyFileError - error "no processes defined" - end - - desc "export FORMAT LOCATION", "Export the application to another process management format" - - method_option :app, :type => :string, :aliases => "-a" - method_option :log, :type => :string, :aliases => "-l" - method_option :run, :type => :string, :aliases => "-r", :desc => "Specify the pid file directory, defaults to /var/run/" - method_option :env, :type => :string, :aliases => "-e", :desc => "Specify an environment file to load, defaults to .env" - method_option :port, :type => :numeric, :aliases => "-p" - method_option :user, :type => :string, :aliases => "-u" - method_option :template, :type => :string, :aliases => "-t" - method_option :formation, :type => :string, :aliases => "-m", :banner => '"alpha=5,bar=3"', :desc => 'Specify what processes will run and how many. Default: "all=1"' - method_option :timeout, :type => :numeric, :aliases => "-t", :desc => "Specify the amount of time (in seconds) processes have to shutdown gracefully before receiving a SIGKILL, defaults to 5." - - def export(format, location=nil) - check_procfile! - load_environment! - engine.load_procfile(procfile) - formatter = Foreman::Export.formatter(format) - formatter.new(location, engine, options).export - rescue Foreman::Export::Exception, Foreman::Procfile::EmptyFileError => ex - error ex.message - end - - desc "check", "Validate your application's Procfile" - - def check - check_procfile! - engine.load_procfile(procfile) - puts "valid procfile detected (#{engine.process_names.join(', ')})" - rescue Foreman::Procfile::EmptyFileError - error "no processes defined" - end - - desc "run COMMAND [ARGS...]", "Run a command using your application's environment" - - method_option :env, :type => :string, :aliases => "-e", :desc => "Specify an environment file to load, defaults to .env" - stop_on_unknown_option! :run - - def run(*args) - load_environment! - - if File.file?(procfile) - engine.load_procfile(procfile) - end - - pid = fork do - begin - engine.env.each { |k,v| ENV[k] = v } - if args.size == 1 && process = engine.process(args.first) - process.exec(:env => engine.env) - else - exec args.shelljoin - end - rescue Errno::EACCES - error "not executable: #{args.first}" - rescue Errno::ENOENT - error "command not found: #{args.first}" - end - end - trap("INT") do - Process.kill(:INT, pid) - end - Process.wait(pid) - exit $?.exitstatus || 0 - rescue Interrupt - rescue Foreman::Procfile::EmptyFileError - error "no processes defined" - end - - desc "version", "Display Foreman gem version" - - def version - puts Foreman::VERSION - end - - no_tasks do - def engine - @engine ||= begin - engine_class = Foreman::Engine::CLI - engine = engine_class.new(options) - engine - end - end - - def options - original_options = super - return original_options unless File.file?(".foreman") - defaults = ::YAML::load_file(".foreman") || {} - Thor::CoreExt::HashWithIndifferentAccess.new(defaults.merge(original_options)) - end - end - -private ###################################################################### - - def error(message) - puts "ERROR: #{message}" - exit 1 - end - - def check_procfile! - error("#{procfile} does not exist.") unless File.file?(procfile) - end - - def load_environment! - if options[:env] - options[:env].split(",").each do |file| - engine.load_env file - end - else - default_env = File.join(engine.root, ".env") - engine.load_env default_env if File.file?(default_env) - end - end - - def procfile - case - when options[:procfile] then options[:procfile] - when options[:root] then File.expand_path(File.join(options[:root], "Procfile")) - else "Procfile" - end - end -end diff --git a/lib/foreman/distribution.rb b/lib/foreman/distribution.rb deleted file mode 100644 index 2d5650e7..00000000 --- a/lib/foreman/distribution.rb +++ /dev/null @@ -1,9 +0,0 @@ -module Foreman - module Distribution - def self.files - Dir[File.expand_path("../../../{bin,data,lib}/**/*", __FILE__)].select do |file| - File.file?(file) - end - end - end -end diff --git a/lib/foreman/engine.rb b/lib/foreman/engine.rb deleted file mode 100644 index a1316593..00000000 --- a/lib/foreman/engine.rb +++ /dev/null @@ -1,494 +0,0 @@ -require "foreman" -require "foreman/env" -require "foreman/process" -require "foreman/procfile" -require "tempfile" -require "fileutils" -require "thread" - -class Foreman::Engine - - # The signals that the engine cares about. - # - HANDLED_SIGNALS = [ :TERM, :INT, :HUP, :USR1, :USR2 ] - - attr_reader :env - attr_reader :options - attr_reader :processes - - # Create an +Engine+ for running processes - # - # @param [Hash] options - # - # @option options [String] :formation (all=1) The process formation to use - # @option options [Fixnum] :port (5000) The base port to assign to processes - # @option options [String] :root (Dir.pwd) The root directory from which to run processes - # - def initialize(options={}) - @options = options.dup - - @options[:formation] ||= "all=1" - @options[:timeout] ||= 5 - - @env = {} - @mutex = Mutex.new - @names = {} - @processes = [] - @running = {} - @readers = {} - @shutdown = false - - # Self-pipe for deferred signal-handling (ala djb: http://cr.yp.to/docs/selfpipe.html) - reader, writer = create_pipe - reader.close_on_exec = true if reader.respond_to?(:close_on_exec) - writer.close_on_exec = true if writer.respond_to?(:close_on_exec) - @selfpipe = { :reader => reader, :writer => writer } - - # Set up a global signal queue - # http://blog.rubybestpractices.com/posts/ewong/016-Implementing-Signal-Handlers.html - Thread.main[:signal_queue] = [] - end - - # Start the processes registered to this +Engine+ - # - def start - register_signal_handlers - startup - spawn_processes - watch_for_output - sleep 0.1 - wait_for_shutdown_or_child_termination - shutdown - exit(@exitstatus) if @exitstatus - end - - # Set up deferred signal handlers - # - def register_signal_handlers - HANDLED_SIGNALS.each do |sig| - if ::Signal.list.include? sig.to_s - trap(sig) { Thread.main[:signal_queue] << sig ; notice_signal } - end - end - end - - # Unregister deferred signal handlers - # - def restore_default_signal_handlers - HANDLED_SIGNALS.each do |sig| - trap(sig, :DEFAULT) if ::Signal.list.include? sig.to_s - end - end - - # Wake the main thread up via the selfpipe when there's a signal - # - def notice_signal - @selfpipe[:writer].write_nonblock( '.' ) - rescue Errno::EAGAIN - # Ignore writes that would block - rescue Errno::EINTR - # Retry if another signal arrived while writing - retry - end - - # Invoke the real handler for signal +sig+. This shouldn't be called directly - # by signal handlers, as it might invoke code which isn't re-entrant. - # - # @param [Symbol] sig the name of the signal to be handled - # - def handle_signal(sig) - case sig - when :TERM - handle_term_signal - when :INT - handle_interrupt - when :HUP - handle_hangup - when *HANDLED_SIGNALS - handle_signal_forward(sig) - else - system "unhandled signal #{sig}" - end - end - - # Handle a TERM signal - # - def handle_term_signal - system "SIGTERM received, starting shutdown" - @shutdown = true - end - - # Handle an INT signal - # - def handle_interrupt - system "SIGINT received, starting shutdown" - @shutdown = true - end - - # Handle a HUP signal - # - def handle_hangup - system "SIGHUP received, starting shutdown" - @shutdown = true - end - - def handle_signal_forward(signal) - system "#{signal} received, forwarding it to children" - kill_children signal - end - - # Register a process to be run by this +Engine+ - # - # @param [String] name A name for this process - # @param [String] command The command to run - # @param [Hash] options - # - # @option options [Hash] :env A custom environment for this process - # - def register(name, command, options={}) - options[:env] ||= env - options[:cwd] ||= File.dirname(command.split(" ").first) - process = Foreman::Process.new(command, options) - @names[process] = name - @processes << process - end - - # Clear the processes registered to this +Engine+ - # - def clear - @names = {} - @processes = [] - end - - # Register processes by reading a Procfile - # - # @param [String] filename A Procfile from which to read processes to register - # - def load_procfile(filename) - options[:root] ||= File.dirname(filename) - Foreman::Procfile.new(filename).entries do |name, command| - register name, command, :cwd => options[:root] - end - self - end - - # Load a .env file into the +env+ for this +Engine+ - # - # @param [String] filename A .env file to load into the environment - # - def load_env(filename) - Foreman::Env.new(filename).entries do |name, value| - @env[name] = value - end - end - - # Send a signal to all processes started by this +Engine+ - # - # @param [String] signal The signal to send to each process - # - def kill_children(signal="SIGTERM") - if Foreman.windows? - @running.each do |pid, (process, index)| - system "sending #{signal} to #{name_for(pid)} at pid #{pid}" - begin - Process.kill(signal, pid) - rescue Errno::ESRCH, Errno::EPERM - end - end - else - begin - pids = @running.keys.compact - Process.kill signal, *pids unless pids.empty? - rescue Errno::ESRCH, Errno::EPERM - end - end - end - - # Send a signal to the whole process group. - # - # @param [String] signal The signal to send - # - def killall(signal="SIGTERM") - if Foreman.windows? - kill_children(signal) - else - begin - Process.kill "-#{signal}", Process.pid - rescue Errno::ESRCH, Errno::EPERM - end - end - end - - # Get the process formation - # - # @returns [Fixnum] The formation count for the specified process - # - def formation - @formation ||= parse_formation(options[:formation]) - end - - # List the available process names - # - # @returns [Array] A list of process names - # - def process_names - @processes.map { |p| @names[p] } - end - - # Get the +Process+ for a specifid name - # - # @param [String] name The process name - # - # @returns [Foreman::Process] The +Process+ for the specified name - # - def process(name) - @names.invert[name] - end - - # Yield each +Process+ in order - # - def each_process - process_names.each do |name| - yield name, process(name) - end - end - - # Get the root directory for this +Engine+ - # - # @returns [String] The root directory - # - def root - File.expand_path(options[:root] || Dir.pwd) - end - - # Get the port for a given process and offset - # - # @param [Foreman::Process] process A +Process+ associated with this engine - # @param [Fixnum] instance The instance of the process - # - # @returns [Fixnum] port The port to use for this instance of this process - # - def port_for(process, instance, base=nil) - if base - base + (@processes.index(process.process) * 100) + (instance - 1) - else - base_port + (@processes.index(process) * 100) + (instance - 1) - end - end - - # Get the base port for this foreman instance - # - # @returns [Fixnum] port The base port - # - def base_port - (options[:port] || env["PORT"] || ENV["PORT"] || 5000).to_i - end - - # deprecated - def environment - env - end - -private - -### Engine API ###################################################### - - def startup - raise TypeError, "must use a subclass of Foreman::Engine" - end - - def output(name, data) - raise TypeError, "must use a subclass of Foreman::Engine" - end - - def shutdown - raise TypeError, "must use a subclass of Foreman::Engine" - end - -## Helpers ########################################################## - - def create_pipe - IO.method(:pipe).arity.zero? ? IO.pipe : IO.pipe("BINARY") - end - - def name_for(pid) - process, index = @running[pid] - name_for_index(process, index) - end - - def name_for_index(process, index) - [ @names[process], index.to_s ].compact.join(".") - end - - def parse_formation(formation) - pairs = formation.to_s.gsub(/\s/, "").split(",") - - pairs.inject(Hash.new(0)) do |ax, pair| - process, amount = pair.split("=") - process == "all" ? ax.default = amount.to_i : ax[process] = amount.to_i - ax - end - end - - def output_with_mutex(name, message) - @mutex.synchronize do - output name, message - end - end - - def system(message) - output_with_mutex "system", message - end - - def termination_message_for(status) - if status.exited? - "exited with code #{status.exitstatus}" - elsif status.signaled? - "terminated by SIG#{Signal.list.invert[status.termsig]}" - else - "died a mysterious death" - end - end - - def flush_reader(reader) - until reader.eof? - data = reader.gets - output_with_mutex name_for(@readers.key(reader)), data - end - end - -## Engine ########################################################### - - def spawn_processes - @processes.each do |process| - 1.upto(formation[@names[process]]) do |n| - reader, writer = create_pipe - begin - pid = process.run(:output => writer, :env => { - "PORT" => port_for(process, n).to_s, - "PS" => name_for_index(process, n) - }) - writer.puts "started with pid #{pid}" - rescue Errno::ENOENT - writer.puts "unknown command: #{process.command}" - end - @running[pid] = [process, n] - @readers[pid] = reader - end - end - end - - def read_self_pipe - @selfpipe[:reader].read_nonblock(11) - rescue Errno::EAGAIN, Errno::EINTR, Errno::EBADF, Errno::EWOULDBLOCK - # ignore - end - - def handle_signals - while sig = Thread.main[:signal_queue].shift - self.handle_signal(sig) - end - end - - def handle_io(readers) - readers.each do |reader| - next if reader == @selfpipe[:reader] - - if reader.eof? - @readers.delete_if { |key, value| value == reader } - else - data = reader.gets - output_with_mutex name_for(@readers.invert[reader]), data - end - end - end - - def watch_for_output - Thread.new do - begin - loop do - io = IO.select([@selfpipe[:reader]] + @readers.values, nil, nil, 30) - read_self_pipe - handle_signals - handle_io(io ? io.first : []) - end - rescue Exception => ex - puts ex.message - puts ex.backtrace - end - end - end - - def wait_for_shutdown_or_child_termination - loop do - # Stop if it is time to shut down (asked via a signal) - break if @shutdown - - # Stop if any of the children died - break if check_for_termination - - # Sleep for a moment and do not blow up if any signals are coming our way - begin - sleep(1) - rescue Exception - # noop - end - end - - # Ok, we have exited from the main loop, time to shut down gracefully - terminate_gracefully - end - - def check_for_termination - # Check if any of the children have died off - pid, status = begin - Process.wait2(-1, Process::WNOHANG) - rescue Errno::ECHILD - return nil - end - - # record the exit status - @exitstatus ||= status.exitstatus if status - - # If no childred have died, nothing to do here - return nil unless pid - - # Log the information about the process that exited - output_with_mutex name_for(pid), termination_message_for(status) - - # Delete it from the list of running processes and return its pid - @running.delete(pid) - return pid - end - - def terminate_gracefully - restore_default_signal_handlers - - # Tell all children to stop gracefully - if Foreman.windows? - system "sending SIGKILL to all processes" - kill_children "SIGKILL" - else - system "sending SIGTERM to all processes" - kill_children "SIGTERM" - end - - # Wait for all children to stop or until the time comes to kill them all - start_time = Time.now - while Time.now - start_time <= options[:timeout] - return if @running.empty? - check_for_termination - - # Sleep for a moment and do not blow up if more signals are coming our way - begin - sleep(0.1) - rescue Exception - # noop - end - end - - # Ok, we have no other option than to kill all of our children - system "sending SIGKILL to all processes" - kill_children "SIGKILL" - end -end diff --git a/lib/foreman/engine/cli.rb b/lib/foreman/engine/cli.rb deleted file mode 100644 index 1cbc66f4..00000000 --- a/lib/foreman/engine/cli.rb +++ /dev/null @@ -1,105 +0,0 @@ -require "foreman/engine" - -class Foreman::Engine::CLI < Foreman::Engine - - module Color - - ANSI = { - :reset => 0, - :black => 30, - :red => 31, - :green => 32, - :yellow => 33, - :blue => 34, - :magenta => 35, - :cyan => 36, - :white => 37, - :bright_black => 30, - :bright_red => 31, - :bright_green => 32, - :bright_yellow => 33, - :bright_blue => 34, - :bright_magenta => 35, - :bright_cyan => 36, - :bright_white => 37, - } - - def self.enable(io, force=false) - io.extend(self) - @@color_force = force - end - - def color? - return true if @@color_force - return false if Foreman.windows? - return false unless self.respond_to?(:isatty) - self.isatty && ENV["TERM"] - end - - def color(name) - return "" unless color? - return "" unless ansi = ANSI[name.to_sym] - "\e[#{ansi}m" - end - - end - - FOREMAN_COLORS = %w( cyan yellow green magenta red blue bright_cyan bright_yellow - bright_green bright_magenta bright_red bright_blue ) - - def startup - @colors = map_colors - proctitle "foreman: main" unless Foreman.windows? - Color.enable($stdout, options[:color]) - end - - def output(name, data) - data.to_s.lines.map(&:chomp).each do |message| - output = "" - output += $stdout.color(@colors[name.split(".").first].to_sym) - output += "#{Time.now.strftime("%H:%M:%S")} " if options[:timestamp] - output += "#{pad_process_name(name)} | " - output += $stdout.color(:reset) - output += message - $stdout.puts output - $stdout.flush - end - rescue Errno::EPIPE - terminate_gracefully - end - - def shutdown - end - -private - - def name_padding - @name_padding ||= begin - index_padding = @names.values.map { |n| formation[n] }.max.to_s.length + 1 - name_padding = @names.values.map { |n| n.length + index_padding }.sort.last - [ 6, name_padding.to_i ].max - end - end - - def pad_process_name(name) - name.ljust(name_padding, " ") - end - - def map_colors - colors = Hash.new("white") - @names.values.each_with_index do |name, index| - colors[name] = FOREMAN_COLORS[index % FOREMAN_COLORS.length] - end - colors["system"] = "bright_white" - colors - end - - def proctitle(title) - $0 = title - end - - def termtitle(title) - printf("\033]0;#{title}\007") unless Foreman.windows? - end - -end diff --git a/lib/foreman/env.rb b/lib/foreman/env.rb deleted file mode 100644 index 378d2f7b..00000000 --- a/lib/foreman/env.rb +++ /dev/null @@ -1,29 +0,0 @@ -require "foreman" - -class Foreman::Env - - attr_reader :entries - - def initialize(filename) - @entries = File.read(filename).gsub("\r\n","\n").split("\n").inject({}) do |ax, line| - if line =~ /\A([A-Za-z_0-9]+)=(.*)\z/ - key = $1 - case val = $2 - # Remove single quotes - when /\A'(.*)'\z/ then ax[key] = $1 - # Remove double quotes and unescape string preserving newline characters - when /\A"(.*)"\z/ then ax[key] = $1.gsub('\n', "\n").gsub(/\\(.)/, '\1') - else ax[key] = val - end - end - ax - end - end - - def entries - @entries.each do |key, value| - yield key, value - end - end - -end diff --git a/lib/foreman/export.rb b/lib/foreman/export.rb deleted file mode 100644 index 04bf71c3..00000000 --- a/lib/foreman/export.rb +++ /dev/null @@ -1,36 +0,0 @@ -require "foreman" -require "foreman/helpers" -require "pathname" - -module Foreman::Export - extend Foreman::Helpers - - class Exception < ::Exception; end - - def self.formatter(format) - begin - require "foreman/export/#{ format.tr('-', '_') }" - classy_format = classify(format) - formatter = constantize("Foreman::Export::#{ classy_format }") - rescue NameError => ex - error "Unknown export format: #{format} (no class Foreman::Export::#{ classy_format })." - rescue LoadError => ex - error "Unknown export format: #{format} (unable to load file 'foreman/export/#{ format.tr('-', '_') }')." - end - end - - def self.error(message) - raise Foreman::Export::Exception.new(message) - end - -end - -require "foreman/export/base" -require "foreman/export/inittab" -require "foreman/export/upstart" -require "foreman/export/daemon" -require "foreman/export/bluepill" -require "foreman/export/runit" -require "foreman/export/supervisord" -require "foreman/export/launchd" -require "foreman/export/systemd" diff --git a/lib/foreman/export/base.rb b/lib/foreman/export/base.rb deleted file mode 100644 index fc7d9af4..00000000 --- a/lib/foreman/export/base.rb +++ /dev/null @@ -1,135 +0,0 @@ -require "foreman/export" -require "pathname" -require "shellwords" - -class Foreman::Export::Base - - attr_reader :location - attr_reader :engine - attr_reader :options - attr_reader :formation - - # deprecated - attr_reader :port - - def initialize(location, engine, options={}) - @location = location - @engine = engine - @options = options.dup - @formation = engine.formation - end - - def export - error("Must specify a location") unless location - FileUtils.mkdir_p(location) rescue error("Could not create: #{location}") - chown user, log - chown user, run - end - - def app - options[:app] || "app" - end - - def log - options[:log] || "/var/log/#{app}" - end - - def run - options[:run] || "/var/run/#{app}" - end - - def user - options[:user] || app - end - -private ###################################################################### - - def chown user, dir - FileUtils.chown user, nil, dir - rescue - error("Could not chown #{dir} to #{user}") unless File.writable?(dir) || ! File.exist?(dir) - end - - def error(message) - raise Foreman::Export::Exception.new(message) - end - - def say(message) - puts "[foreman export] %s" % message - end - - def clean(filename) - return unless File.exist?(filename) - say "cleaning up: #{filename}" - FileUtils.rm(filename) - end - - def clean_dir(dirname) - return unless File.exist?(dirname) - say "cleaning up directory: #{dirname}" - FileUtils.rm_r(dirname) - end - - def shell_quote(value) - Shellwords.escape(value) - end - - # deprecated - def old_export_template(exporter, file, template_root) - if template_root && File.exist?(file_path = File.join(template_root, file)) - File.read(file_path) - elsif File.exist?(file_path = File.expand_path(File.join("~/.foreman/templates", file))) - File.read(file_path) - else - File.read(File.expand_path("../../../../data/export/#{exporter}/#{file}", __FILE__)) - end - end - - def export_template(name, file=nil, template_root=nil) - if file && template_root - old_export_template name, file, template_root - else - name_without_first = name.split("/")[1..-1].join("/") - matchers = [] - matchers << File.join(options[:template], name_without_first) if options[:template] - matchers << File.expand_path("~/.foreman/templates/#{name}") - matchers << File.expand_path("../../../../data/export/#{name}", __FILE__) - File.read(matchers.detect { |m| File.exist?(m) }) - end - end - - def write_template(name, target, binding) - compiled = if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+ - ERB.new(export_template(name), trim_mode: '-').result(binding) - else - ERB.new(export_template(name), nil, '-').result(binding) - end - write_file target, compiled - end - - def chmod(mode, file) - say "setting #{file} to mode #{mode}" - FileUtils.chmod mode, File.join(location, file) - end - - def create_directory(dir) - say "creating: #{dir}" - FileUtils.mkdir_p(File.join(location, dir)) - end - - def create_symlink(link, target) - say "symlinking: #{link} -> #{target}" - FileUtils.symlink(target, File.join(location, link)) - end - - def write_file(filename, contents) - say "writing: #{filename}" - - filename = File.join(location, filename) unless Pathname.new(filename).absolute? - - File.open(filename, "w") do |file| - file.puts contents - end - end - -end diff --git a/lib/foreman/export/bluepill.rb b/lib/foreman/export/bluepill.rb deleted file mode 100644 index 1372b5a5..00000000 --- a/lib/foreman/export/bluepill.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Bluepill < Foreman::Export::Base - - def export - super - clean "#{location}/#{app}.pill" - write_template "bluepill/master.pill.erb", "#{app}.pill", binding - end - -end diff --git a/lib/foreman/export/daemon.rb b/lib/foreman/export/daemon.rb deleted file mode 100644 index 40f623c6..00000000 --- a/lib/foreman/export/daemon.rb +++ /dev/null @@ -1,28 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Daemon < Foreman::Export::Base - - def export - super - - (Dir["#{location}/#{app}-*.conf"] << "#{location}/#{app}.conf").each do |file| - clean file - end - - write_template "daemon/master.conf.erb", "#{app}.conf", binding - - engine.each_process do |name, process| - next if engine.formation[name] < 1 - write_template "daemon/process_master.conf.erb", "#{app}-#{name}.conf", binding - - 1.upto(engine.formation[name]) do |num| - port = engine.port_for(process, num) - arguments = process.command.split(" ") - executable = arguments.slice!(0) - arguments = arguments.size > 0 ? " -- #{arguments.join(' ')}" : "" - write_template "daemon/process.conf.erb", "#{app}-#{name}-#{num}.conf", binding - end - end - end -end diff --git a/lib/foreman/export/inittab.rb b/lib/foreman/export/inittab.rb deleted file mode 100644 index d8b1f4db..00000000 --- a/lib/foreman/export/inittab.rb +++ /dev/null @@ -1,42 +0,0 @@ -require "foreman/export" - -class Foreman::Export::Inittab < Foreman::Export::Base - - def export - error("Must specify a location") unless location - - inittab = [] - inittab << "# ----- foreman #{app} processes -----" - - index = 1 - engine.each_process do |name, process| - 1.upto(engine.formation[name]) do |num| - id = app.slice(0, 2).upcase + sprintf("%02d", index) - port = engine.port_for(process, num) - - commands = [] - commands << "cd #{engine.root}" - commands << "export PORT=#{port}" - engine.env.each_pair do |var, env| - commands << "export #{var.upcase}=#{shell_quote(env)}" - end - commands << "#{process.command} >> #{log}/#{name}-#{num}.log 2>&1" - - inittab << "#{id}:4:respawn:/bin/su - #{user} -c '#{commands.join(";")}'" - index += 1 - end - end - - inittab << "# ----- end foreman #{app} processes -----" - - inittab = inittab.join("\n") + "\n" - - if location == "-" - puts inittab - else - say "writing: #{location}" - File.open(location, "w") { |file| file.puts inittab } - end - end - -end diff --git a/lib/foreman/export/launchd.rb b/lib/foreman/export/launchd.rb deleted file mode 100644 index b21a6756..00000000 --- a/lib/foreman/export/launchd.rb +++ /dev/null @@ -1,22 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Launchd < Foreman::Export::Base - - def export - super - engine.each_process do |name, process| - 1.upto(engine.formation[name]) do |num| - port = engine.port_for(process, num) - command_args = process.command.split(/\s+/).map{|arg| - case arg - when "$PORT" then port - else arg - end - } - write_template "launchd/launchd.plist.erb", "#{app}-#{name}-#{num}.plist", binding - end - end - end - -end diff --git a/lib/foreman/export/runit.rb b/lib/foreman/export/runit.rb deleted file mode 100644 index ce22d0ed..00000000 --- a/lib/foreman/export/runit.rb +++ /dev/null @@ -1,34 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Runit < Foreman::Export::Base - - ENV_VARIABLE_REGEX = /([a-zA-Z_]+[a-zA-Z0-9_]*)=(\S+)/ - - def export - super - - engine.each_process do |name, process| - 1.upto(engine.formation[name]) do |num| - process_directory = "#{app}-#{name}-#{num}" - - create_directory process_directory - create_directory "#{process_directory}/env" - create_directory "#{process_directory}/log" - - write_template "runit/run.erb", "#{process_directory}/run", binding - chmod 0755, "#{process_directory}/run" - - port = engine.port_for(process, num) - engine.env.merge("PORT" => port.to_s).each do |key, value| - write_file "#{process_directory}/env/#{key}", value - end - - write_template "runit/log/run.erb", "#{process_directory}/log/run", binding - chmod 0755, "#{process_directory}/log/run" - end - end - - end - -end diff --git a/lib/foreman/export/supervisord.rb b/lib/foreman/export/supervisord.rb deleted file mode 100644 index c6b1a872..00000000 --- a/lib/foreman/export/supervisord.rb +++ /dev/null @@ -1,16 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Supervisord < Foreman::Export::Base - - def export - super - - Dir["#{location}/#{app}.conf"].each do |file| - clean file - end - - write_template "supervisord/app.conf.erb", "#{app}.conf", binding - end - -end diff --git a/lib/foreman/export/systemd.rb b/lib/foreman/export/systemd.rb deleted file mode 100644 index 9e39f5e4..00000000 --- a/lib/foreman/export/systemd.rb +++ /dev/null @@ -1,34 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Systemd < Foreman::Export::Base - - def export - super - - Dir["#{location}/#{app}*.target"] - .concat(Dir["#{location}/#{app}*.service"]) - .concat(Dir["#{location}/#{app}*.target.wants/#{app}*.service"]) - .each do |file| - clean file - end - - Dir["#{location}/#{app}*.target.wants"].each do |file| - clean_dir file - end - - service_names = [] - - engine.each_process do |name, process| - 1.upto(engine.formation[name]) do |num| - port = engine.port_for(process, num) - process_name = "#{name}.#{num}" - service_filename = "#{app}-#{process_name}.service" - write_template "systemd/process.service.erb", service_filename, binding - service_names << service_filename - end - end - - write_template "systemd/master.target.erb", "#{app}.target", binding - end -end diff --git a/lib/foreman/export/upstart.rb b/lib/foreman/export/upstart.rb deleted file mode 100644 index 20daf392..00000000 --- a/lib/foreman/export/upstart.rb +++ /dev/null @@ -1,46 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Upstart < Foreman::Export::Base - - def export - super - - master_file = "#{app}.conf" - - clean File.join(location, master_file) - write_template master_template, master_file, binding - - engine.each_process do |name, process| - process_master_file = "#{app}-#{name}.conf" - process_file = "#{app}-#{name}-%s.conf" - - Dir[ - File.join(location, process_master_file), - File.join(location, process_file % "*") - ].each { |f| clean(f) } - - next if engine.formation[name] < 1 - write_template process_master_template, process_master_file, binding - - 1.upto(engine.formation[name]) do |num| - port = engine.port_for(process, num) - write_template process_template, process_file % num, binding - end - end - end - - private - - def master_template - "upstart/master.conf.erb" - end - - def process_master_template - "upstart/process_master.conf.erb" - end - - def process_template - "upstart/process.conf.erb" - end -end diff --git a/lib/foreman/helpers.rb b/lib/foreman/helpers.rb deleted file mode 100644 index 95b6e171..00000000 --- a/lib/foreman/helpers.rb +++ /dev/null @@ -1,45 +0,0 @@ -module Foreman::Helpers - # Copied whole sale from, https://github.com/defunkt/resque/ - - # Given a word with dashes, returns a camel cased version of it. - # - # classify('job-name') # => 'JobName' - def classify(dashed_word) - dashed_word.split('-').each { |part| part[0] = part[0].chr.upcase }.join - end # Tries to find a constant with the name specified in the argument string: - - # - # constantize("Module") # => Module - # constantize("Test::Unit") # => Test::Unit - # - # The name is assumed to be the one of a top-level constant, no matter - # whether it starts with "::" or not. No lexical context is taken into - # account: - # - # C = 'outside' - # module M - # C = 'inside' - # C # => 'inside' - # constantize("C") # => 'outside', same as ::C - # end - # - # NameError is raised when the constant is unknown. - def constantize(camel_cased_word) - camel_cased_word = camel_cased_word.to_s - - names = camel_cased_word.split('::') - names.shift if names.empty? || names.first.empty? - - constant = Object - names.each do |name| - args = Module.method(:const_get).arity != 1 ? [false] : [] - - if constant.const_defined?(name, *args) - constant = constant.const_get(name) - else - constant = constant.const_missing(name) - end - end - constant - end -end diff --git a/lib/foreman/process.rb b/lib/foreman/process.rb deleted file mode 100644 index ee3de948..00000000 --- a/lib/foreman/process.rb +++ /dev/null @@ -1,80 +0,0 @@ -require "foreman" -require "shellwords" - -class Foreman::Process - - attr_reader :command - attr_reader :env - - # Create a Process - # - # @param [String] command The command to run - # @param [Hash] options - # - # @option options [String] :cwd (./) Change to this working directory before executing the process - # @option options [Hash] :env ({}) Environment variables to set for this process - # - def initialize(command, options={}) - @command = command - @options = options.dup - - @options[:env] ||= {} - end - - # Get environment-expanded command for a +Process+ - # - # @param [Hash] custom_env ({}) Environment variables to merge with defaults - # - # @return [String] The expanded command - # - def expanded_command(custom_env={}) - env = @options[:env].merge(custom_env) - expanded_command = command.dup - env.each do |key, val| - expanded_command.gsub!("$#{key}", val) - end - expanded_command - end - - # Run a +Process+ - # - # @param [Hash] options - # - # @option options :env ({}) Environment variables to set for this execution - # @option options :output ($stdout) The output stream - # - # @returns [Fixnum] pid The +pid+ of the process - # - def run(options={}) - env = @options[:env].merge(options[:env] || {}) - output = options[:output] || $stdout - runner = "#{Foreman.runner}".shellescape - - Dir.chdir(cwd) do - Process.spawn env, expanded_command(env), :out => output, :err => output - end - end - - # Exec a +Process+ - # - # @param [Hash] options - # - # @option options :env ({}) Environment variables to set for this execution - # - # @return Does not return - def exec(options={}) - env = @options[:env].merge(options[:env] || {}) - env.each { |k, v| ENV[k] = v } - Dir.chdir(cwd) - Kernel.exec expanded_command(env) - end - - # Returns the working directory for this +Process+ - # - # @returns [String] - # - def cwd - File.expand_path(@options[:cwd] || ".") - end - -end diff --git a/lib/foreman/procfile.rb b/lib/foreman/procfile.rb deleted file mode 100644 index 74887212..00000000 --- a/lib/foreman/procfile.rb +++ /dev/null @@ -1,100 +0,0 @@ -require "foreman" - -# Reads and writes Procfiles -# -# A valid Procfile entry is captured by this regex: -# -# /^([A-Za-z0-9_-]+):\s*(.+)$/ -# -# All other lines are ignored. -# -class Foreman::Procfile - - EmptyFileError = Class.new(StandardError) - - # Initialize a Procfile - # - # @param [String] filename (nil) An optional filename to read from - # - def initialize(filename=nil) - @entries = [] - load(filename) if filename - end - - # Yield each +Procfile+ entry in order - # - def entries - @entries.each do |(name, command)| - yield name, command - end - end - - # Retrieve a +Procfile+ command by name - # - # @param [String] name The name of the Procfile entry to retrieve - # - def [](name) - if entry = @entries.detect { |n,c| name == n } - entry.last - end - end - - # Create a +Procfile+ entry - # - # @param [String] name The name of the +Procfile+ entry to create - # @param [String] command The command of the +Procfile+ entry to create - # - def []=(name, command) - delete name - @entries << [name, command] - end - - # Remove a +Procfile+ entry - # - # @param [String] name The name of the +Procfile+ entry to remove - # - def delete(name) - @entries.reject! { |n,c| name == n } - end - - # Load a Procfile from a file - # - # @param [String] filename The filename of the +Procfile+ to load - # - def load(filename) - parse_data = parse(filename) - - raise EmptyFileError if parse_data.empty? - - @entries.replace parse_data - end - - # Save a Procfile to a file - # - # @param [String] filename Save the +Procfile+ to this file - # - def save(filename) - File.open(filename, 'w') do |file| - file.puts self.to_s - end - end - - # Get the +Procfile+ as a +String+ - # - def to_s - @entries.map do |name, command| - [ name, command ].join(": ") - end.join("\n") - end - -private - - def parse(filename) - File.read(filename).gsub("\r\n","\n").split("\n").map do |line| - if line =~ /^([A-Za-z0-9_-]+):\s*(.+)$/ - [$1, $2] - end - end.compact - end - -end diff --git a/lib/foreman/version.rb b/lib/foreman/version.rb deleted file mode 100644 index f1a326b4..00000000 --- a/lib/foreman/version.rb +++ /dev/null @@ -1,5 +0,0 @@ -module Foreman - - VERSION = "0.90.0" - -end diff --git a/lib/foruiman.rb b/lib/foruiman.rb new file mode 100644 index 00000000..7d2fd3b7 --- /dev/null +++ b/lib/foruiman.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +module Foruiman + class Error < StandardError + end +end + +require_relative "foruiman/version" +require_relative "foruiman/procfile" +require_relative "foruiman/env" +require_relative "foruiman/engine" diff --git a/lib/foruiman/ansi.rb b/lib/foruiman/ansi.rb new file mode 100644 index 00000000..bffc2ada --- /dev/null +++ b/lib/foruiman/ansi.rb @@ -0,0 +1,147 @@ +# frozen_string_literal: true + +module Foruiman::ANSI + SGR = /\e\[[0-9;:]*m/ + RESET = "\e[0m" + + # A bounded style snapshot makes each retained row independently renderable. + class Styles + def initialize + @values = {} + end + + def apply(sequence) + values = sequence.delete_prefix("\e[").delete_suffix("m").split(";") + values = ["0"] if values.empty? + until values.empty? + value = values.shift + code = value.to_i + case code + when 0 then @values.clear + when 1, 2 then @values[:intensity] = value + when 3 then @values[:italic] = value + when 4, 21 then @values[:underline] = value + when 5, 6 then @values[:blink] = value + when 7 then @values[:inverse] = value + when 8 then @values[:conceal] = value + when 9 then @values[:strike] = value + when 22 then @values.delete(:intensity) + when 23 then @values.delete(:italic) + when 24 then @values.delete(:underline) + when 25 then @values.delete(:blink) + when 27 then @values.delete(:inverse) + when 28 then @values.delete(:conceal) + when 29 then @values.delete(:strike) + when 30..37, 90..97 then @values[:foreground] = value + when 40..47, 100..107 then @values[:background] = value + when 38, 48 then color(code, value, values) + when 39 then @values.delete(:foreground) + when 49 then @values.delete(:background) + end + end + end + + def prefix + @values.empty? ? "" : "\e[#{@values.values.join(';')}m" + end + + private + + def color(code, value, values) + if value.include?(":") + color = value + else + mode = values.shift + return unless %w[2 5].include?(mode) + + count = mode == "2" ? 3 : 1 + return if values.size < count + + color = [value, mode, *values.shift(count)].join(";") + end + @values[code == 38 ? :foreground : :background] = color + end + end + + # Incremental byte parser: only text, newlines, and SGR can leave this class. + # OSC (including clipboard), DCS, cursor controls, and other escapes are dropped. + class Decoder + def initialize + @state = :text + @escape = +"" + @pending = +"".b + end + + def feed(bytes, eof: false) + output = +"".b + bytes.each_byte { |byte| consume(byte, output) } + output = @pending + output + @pending = +"".b + unless eof + length = incomplete_suffix(output) + @pending = output.slice!(-length, length) if length.positive? + end + output.force_encoding(Encoding::UTF_8).scrub.delete("\u0080-\u009f") + end + + private + + def consume(byte, output) + case @state + when :text + case byte + when 27 then @state = :escape + when 9 then output << " " + when 10, 32..126, 128..255 then output << byte + end + when :escape + @state = case byte + when 91 then :csi + when 93 then :osc + when 80, 88, 94, 95 then :string + when 32..47 then :intermediate + else :text + end + @escape.clear + when :intermediate + @state = :text if byte >= 48 + when :csi + if byte.between?(64, 126) + output << "\e[#{@escape}m" if byte == 109 && @escape.match?(/\A[0-9;:]*\z/) + @state = :text + elsif @escape.bytesize < 96 + @escape << byte + else + @state = :discard_csi + end + when :discard_csi + @state = :text if byte.between?(64, 126) + when :osc, :string + if byte == 27 + @string_state = @state + @state = :string_escape + elsif byte == 7 && @state == :osc + @state = :text + end + when :string_escape + @state = byte == 92 ? :text : @string_state + end + end + + def incomplete_suffix(bytes) + index = bytes.bytesize - 1 + index -= 1 while index >= 0 && bytes.getbyte(index).between?(128, 191) + return 0 if index.negative? + + lead = bytes.getbyte(index) + expected = case lead + when 194..223 then 2 + when 224..239 then 3 + when 240..244 then 4 + else 1 + end + actual = bytes.bytesize - index + actual < expected ? actual : 0 + end + end +end diff --git a/lib/foruiman/cli.rb b/lib/foruiman/cli.rb new file mode 100644 index 00000000..def1e179 --- /dev/null +++ b/lib/foruiman/cli.rb @@ -0,0 +1,83 @@ +# frozen_string_literal: true + +require "thor" +require "foruiman" +require_relative "plain" +require_relative "diagnostics" + +# Foreman's Thor command structure, reduced to the MVP surface. +class Foruiman::CLI < Thor + map ["-v", "--version"] => :version + default_task :start + check_unknown_options! + remove_command :tree + + class_option :procfile, type: :string, aliases: "-f", default: "Procfile", desc: "Procfile to read" + class_option :root, type: :string, aliases: "-d", desc: "Working directory (default: invocation directory)" + class_option :env, type: :string, aliases: "-e", desc: "Environment file layered after .env" + class_option :dotenv, type: :boolean, default: true, desc: "Load optional .env from working directory" + class_option :port, type: :string, aliases: "-p", default: "5000", desc: "Base port (increments by 100)" + class_option :log_lines, type: :string, default: "10000", desc: "Maximum records per process and in all" + + def self.exit_on_failure? + true + end + + desc "start [PROCESS]", "Run the Procfile with process tabs, or stream logs without a TTY" + method_option :tui, type: :boolean, default: true, desc: "Use the terminal interface when stdin and stdout are TTYs" + def start(process = nil) + engine = build_engine + engine.select(process) if process + interactive = options[:tui] && $stdin.tty? && $stdout.tty? + diagnostics = Foruiman::Diagnostics.new(interactive: interactive) + code = if interactive + require_relative "tui/application" + Foruiman::TUI::Application.new(engine).run + else + Foruiman::Plain.new(engine).run + end + exit(code) + rescue Foruiman::Error, SystemCallError => e + raise Thor::Error, e.message + rescue StandardError => e + diagnostics&.error(e) + warn "foruiman: #{e.message}#{" (details: #{diagnostics.path})" if diagnostics&.path}" + exit(1) + ensure + engine&.close + diagnostics&.close + end + + desc "check", "Validate the Procfile, environment files, ports, and log capacity without starting processes" + def check + engine = build_engine + puts "valid Procfile (#{engine.process_names.join(', ')})" + rescue Foruiman::Error, SystemCallError => e + raise Thor::Error, e.message + ensure + engine&.close + end + + desc "version", "Display Foruiman gem version" + def version + puts Foruiman::VERSION + end + + private + + def integer_option(name) + text = options.fetch(name).to_s + raise Foruiman::Error, "#{name.to_s.tr('_', '-')} must be a positive integer" unless text.match?(/\A[0-9]+\z/) + + text.to_i + end + + def build_engine + root = File.expand_path(options[:root] || Dir.pwd) + procfile = File.expand_path(options[:procfile], root) + file = File.expand_path(options[:env], root) if options[:env] + env = Foruiman::Env.load(root: root, file: file, dotenv: options[:dotenv]) + Foruiman::Engine.new(procfile: procfile, root: root, env: env, + port: integer_option(:port), log_lines: integer_option(:log_lines)) + end +end diff --git a/lib/foruiman/diagnostics.rb b/lib/foruiman/diagnostics.rb new file mode 100644 index 00000000..4363f7bf --- /dev/null +++ b/lib/foruiman/diagnostics.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +class Foruiman::Diagnostics + attr_reader :path + + def initialize(interactive:, stderr: $stderr) + @interactive = interactive + @temporary = nil + @output = stderr + end + + def error(exception) + if @interactive && !@temporary + require "tempfile" + @temporary = Tempfile.create(["foruiman-", ".log"]) + @temporary.chmod(0o600) + @output = @temporary + @path = @temporary.path + end + @output.puts(exception.full_message(highlight: false)) + @output.flush + end + + def close + @temporary&.close + end +end diff --git a/lib/foruiman/engine.rb b/lib/foruiman/engine.rb new file mode 100644 index 00000000..d3bd73b6 --- /dev/null +++ b/lib/foruiman/engine.rb @@ -0,0 +1,403 @@ +# frozen_string_literal: true + +require_relative "process" +require_relative "log_store" +require_relative "output" + +# Derived from Foreman's registration, process lookup, pipes and self-pipe signal +# handling. All process state and output now belong to the caller's event loop. +class Foruiman::Engine + HANDLED_SIGNALS = %i[INT TERM HUP].freeze + TERM_TIMEOUT = 5.0 + READ_CHUNK = 4096 + READ_BUDGET = 64 * 1024 + State = Struct.new(:name, :process, :port, :pid, :pgid, :status, :exit_status, + :generation, :restart_pending, :deadline, :reaped, :group_gone, + keyword_init: true) + Event = Data.define(:type, :name, :pid, :status, :record, :message) + + attr_reader :logs, :env, :processes, :root, :procfile_path + + def initialize(procfile: nil, root: Dir.pwd, env: ENV.to_h, port: 5000, log_lines: 10_000, + term_timeout: TERM_TIMEOUT) + raise Foruiman::Error, "port must be an integer in 1..65535" unless port.is_a?(Integer) && (1..65_535).cover?(port) + raise Foruiman::Error, "log-lines must be a positive integer" unless log_lines.is_a?(Integer) && log_lines.positive? + + @root = File.expand_path(root) + raise Foruiman::Error, "working directory does not exist: #{@root}" unless File.directory?(@root) + + @env = env.dup.freeze + @base_port = port + @log_lines = log_lines + @term_timeout = term_timeout + @processes = [] + @names = {} + @running = {} + @readers = {} + @listeners = [] + @shutdown = false + @explicit_shutdown = false + @failed = false + @closed = false + @started = false + @signal_requested = false + @self_reader, @self_writer = create_pipe + load_procfile(procfile) if procfile + rescue StandardError + @self_reader&.close + @self_writer&.close + raise + end + + def register(name, command) + raise Foruiman::Error, "cannot register after startup" if @started + raise Foruiman::Error, "duplicate process: #{name}" if @names.key?(name) + raise Foruiman::Error, "allocated port exceeds 65535 for #{name}" if @base_port + (processes.size * 100) > 65_535 + + Foruiman::Procfile.new[name] = command + process = Foruiman::Process.new(command, cwd: root, env: env) + state = State.new(name: name.freeze, process: process, port: @base_port + (processes.size * 100), + status: :pending, generation: 0, restart_pending: false, reaped: true, group_gone: true) + @names[name] = state + processes << state + state + end + + def load_procfile(filename) + parsed = Foruiman::Procfile.new(filename) + entries = parsed.entries.to_a + last_port = @base_port + ((processes.size + entries.size - 1) * 100) + raise Foruiman::Error, "allocated port #{last_port} exceeds 65535" if last_port > 65_535 + + entries.each { |name, command| register(name, command) } + @procfile_path = File.expand_path(filename).freeze + self + end + + def process_names + @names.keys + end + + def process(name) + @names[name]&.process + end + + def state(name) + @names.fetch(name) + end + + def select(name) + raise Foruiman::Error, "cannot select after startup" if @started + raise Foruiman::Error, "unknown process: #{name}" unless @names.key?(name) + + @names.select! { |key, _entry| key == name } + processes.select! { |entry| entry.name == name } + self + end + + def on_event(&listener) + @listeners << listener + self + end + + def start(name = nil) + raise Foruiman::Error, "supervisor is closed" if @closed + return if @shutdown + + targets = name ? [state(name)] : processes + unless @started + @logs = Foruiman::LogStore.new(process_names, capacity: @log_lines) do |record| + emit(:output, state(record.name), record: record) + end + @started = true + end + targets.each { |entry| spawn_process(entry) unless entry.pgid } + self + end + + alias start_all start + + def restart(name) + return if @shutdown || @closed + + return start(name) unless @started + + entry = state(name) + return if entry.restart_pending + + entry.restart_pending = true + entry.status = :restarting + lifecycle(entry, :restarting, "restarting") + if entry.pgid + terminate(entry) + else + spawn_process(entry) + end + end + + def stop(name) + entry = state(name) + entry.restart_pending = false + return unless entry.pgid + + entry.status = :stopping + lifecycle(entry, :stopping, "stopping") + terminate(entry) + end + + def shutdown(explicit: true) + @explicit_shutdown ||= explicit + return if @shutdown + + @shutdown = true + processes.each do |entry| + entry.restart_pending = false + stop(entry.name) + end + end + + def shutting_down? + @shutdown + end + + def finished? + @started && processes.all? { |entry| !entry.pgid && !entry.restart_pending } && @readers.empty? + end + + def exit_code + @explicit_shutdown || !@failed ? 0 : 1 + end + + def run(keep_open: false) + register_signal_handlers + start_all + loop do + tick(timeout: keep_open ? 1.0 / 30 : 0.05) + yield self if block_given? + break if finished? && (!keep_open || shutting_down?) + end + exit_code + ensure + close + end + + # Embedders may drive this method directly; start/restart/stop are called on + # that same thread. A bounded round-robin read prevents output starving input. + def tick(timeout: 0.03) + return if @closed + + shutdown if @signal_requested + reap_children + advance_groups + ready = IO.select([@self_reader, *@readers.keys], nil, nil, timeout)&.first || [] + drain_signal_pipe if ready.delete(@self_reader) + shutdown if @signal_requested + read_output(ready) + reap_children + advance_groups + rescue Errno::EINTR + # The next tick handles the deferred signal. + end + + def close + return if @closed + + # Observers can fail (e.g. a closed stdout). Cleanup must still own the loop. + @listeners.clear + shutdown(explicit: false) + tick(timeout: 0.01) until !@started || finished? + ensure + restore_signal_handlers + @self_reader.close unless @self_reader.closed? + @self_writer.close unless @self_writer.closed? + @closed = true + end + + private + + def create_pipe + IO.pipe("BINARY").each { |io| io.close_on_exec = true } + end + + def spawn_process(entry) + return if @shutdown + + stdout_reader, stdout_writer = create_pipe + stderr_reader, stderr_writer = create_pipe + begin + pid = entry.process.run(output: stdout_writer, error: stderr_writer, + env: { "PORT" => entry.port.to_s, "PS" => "#{entry.name}.1" }) + rescue SystemCallError => e + stdout_reader.close + stderr_reader.close + entry.status = :failed + entry.restart_pending = false + @failed = true + lifecycle(entry, :failed, "failed to start: #{e.message}") + return + end + entry.pid = entry.pgid = pid + entry.status = :running + entry.exit_status = nil + entry.generation += 1 + entry.restart_pending = false + entry.deadline = nil + entry.reaped = entry.group_gone = false + @running[pid] = entry + [[stdout_reader, :stdout], [stderr_reader, :stderr]].each do |reader, stream| + @readers[reader] = [entry, Foruiman::Output.new(logs, name: entry.name, stream: stream, pid: pid)] + end + lifecycle(entry, :started, "started with pid #{pid} (generation #{entry.generation})") + ensure + stdout_writer&.close + stderr_writer&.close + [stdout_reader, stderr_reader].compact.each do |reader| + reader.close unless reader.closed? || @readers.key?(reader) + end + end + + def terminate(entry) + return if entry.deadline || entry.group_gone + + signal_group(entry, :TERM) + entry.deadline = monotonic + @term_timeout + end + + def signal_group(entry, signal) + ::Process.kill(signal, -entry.pgid) if entry.pgid + rescue Errno::ESRCH + entry.group_gone = true + end + + def reap_children + @running.keys.each do |pid| # rubocop:disable Style/HashEachMethods -- observers can add processes + result = ::Process.waitpid2(pid, ::Process::WNOHANG) + next unless result + + entry = @running.delete(pid) + entry.reaped = true + entry.exit_status = result.last + success = entry.exit_status.success? + @failed ||= !success && !%i[stopping restarting].include?(entry.status) + entry.status = success ? :exited : :failed unless %i[stopping restarting].include?(entry.status) + lifecycle(entry, :exited, termination_message_for(entry.exit_status)) + terminate(entry) + end + end + + def advance_groups + processes.each do |entry| + next unless entry.pgid + next unless entry.reaped || entry.deadline + + entry.group_gone ||= !group_alive?(entry.pgid) + if !entry.group_gone && entry.deadline && monotonic >= entry.deadline + signal_group(entry, :KILL) + lifecycle(entry, :killed, "sent SIGKILL after TERM timeout") + entry.deadline = nil + end + next unless entry.reaped && entry.group_gone + next if @readers.any? { |_reader, (owner, _output)| owner.equal?(entry) } + + entry.pgid = nil + entry.deadline = nil + entry.status = :stopped if entry.status == :stopping + spawn_process(entry) if entry.restart_pending && !@shutdown + end + end + + def group_alive?(pgid) + ::Process.kill(0, -pgid) + return true unless RUBY_PLATFORM.include?("linux") + + # Linux containers may leave orphan zombies unreaped under PID 1. They + # cannot run or receive signals, and must not hold shutdown open forever. + Dir.glob("/proc/[0-9]*/stat").any? do |filename| + fields = File.read(filename).rpartition(") ").last.split + fields[2].to_i == pgid && !%w[Z X].include?(fields[0]) + rescue Errno::ENOENT, Errno::ESRCH, Errno::EACCES + false + end + rescue Errno::ESRCH + false + end + + def read_output(ready) + budget = READ_BUDGET + ready.each do |reader| + break if budget <= 0 + + entry, output = @readers.fetch(reader) + bytes = reader.read_nonblock(READ_CHUNK, exception: false) + if bytes.nil? || (bytes == :wait_readable && entry.group_gone) + @readers.delete(reader) + reader.close + output.feed("", eof: true) + elsif bytes != :wait_readable + budget -= bytes.bytesize + output.feed(bytes) + # Rotate serviced readers to the back for the next select. + @readers[reader] = @readers.delete(reader) + end + end + # A daemon that escaped the group may still hold a pipe open. Drain available + # bytes, but do not wait on it once every owned group member has finished. + @readers.keys.each do |reader| # rubocop:disable Style/HashEachMethods -- observers can add readers + entry, output = @readers.fetch(reader) + next unless entry.group_gone && !ready.include?(reader) + + @readers.delete(reader) + reader.close + output.feed("", eof: true) + end + end + + def lifecycle(entry, type, message) + logs&.write(name: entry.name, stream: :lifecycle, pid: entry.pid, + text: "--- #{message} ---", complete: true) + emit(type, entry, message: message) + end + + def emit(type, entry, record: nil, message: nil) + event = Event.new(type: type, name: entry.name, pid: entry.pid, status: entry.status, + record: record, message: message&.freeze) + @listeners.each { |listener| listener.call(event) } + end + + def termination_message_for(status) + if status.exited? + "exited with code #{status.exitstatus}" + else + "terminated by SIG#{Signal.list.key(status.termsig)}" + end + end + + def register_signal_handlers + @old_handlers = {} + HANDLED_SIGNALS.each do |signal| + @old_handlers[signal] = Signal.trap(signal) do + @signal_requested = true + notice_signal + end + end + end + + def restore_signal_handlers + @old_handlers&.each { |signal, handler| Signal.trap(signal, handler) } + @old_handlers = nil + end + + def notice_signal + @self_writer.write_nonblock(".", exception: false) + rescue Errno::EINTR + retry + end + + def drain_signal_pipe + @self_reader.read_nonblock(4096, exception: false) + end + + def monotonic + ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + end +end diff --git a/lib/foruiman/env.rb b/lib/foruiman/env.rb new file mode 100644 index 00000000..ca797e1e --- /dev/null +++ b/lib/foruiman/env.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +# Foreman's assignment and quoting rules, with a non-mutating merge API. +class Foruiman::Env + def initialize(filename) + @entries = File.read(filename).gsub("\r\n", "\n").split("\n").each_with_object({}) do |line, result| + next unless (match = line.match(/\A([A-Za-z_0-9]+)=(.*)\z/)) + + key, value = match.captures + result[key] = case value + when /\A'(.*)'\z/ then Regexp.last_match(1) + when /\A"(.*)"\z/ then Regexp.last_match(1).gsub('\\n', "\n").gsub(/\\(.)/, '\1') + else value + end + end + end + + def entries(&block) + return @entries.each unless block + + @entries.each(&block) + end + + def to_h + @entries.dup + end + + def self.load(root: Dir.pwd, file: nil, dotenv: true, inherited: ENV.to_h) + env = inherited.dup + default = File.join(root, ".env") + env.merge!(new(default).to_h) if dotenv && File.file?(default) + env.merge!(new(file).to_h) if file + env.transform_values { |value| value.dup.freeze }.freeze + end +end diff --git a/lib/foruiman/log_store.rb b/lib/foruiman/log_store.rb new file mode 100644 index 00000000..29a282ad --- /dev/null +++ b/lib/foruiman/log_store.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require_relative "ring" + +class Foruiman::LogStore + Record = Data.define(:sequence, :name, :stream, :pid, :time, :text, :complete) + attr_reader :all + + def initialize(names, capacity: 10_000, &listener) + @all = Foruiman::Ring.new(capacity) + @buffers = names.to_h { |name| [name, Foruiman::Ring.new(capacity)] } + @sequence = 0 + @listener = listener + end + + def [](name) + name == "all" ? all : @buffers.fetch(name) + end + + def write(name:, stream:, pid:, text:, complete:, previous: nil) + @sequence += 1 unless previous + record = Record.new(sequence: previous ? previous.sequence : @sequence, name: name, + stream: stream, pid: pid, time: previous ? previous.time : Time.now.freeze, + text: text.dup.freeze, complete: complete) + method = previous ? :replace : :append + @buffers.fetch(name).public_send(method, record) + all.public_send(method, record) + @listener&.call(record) + record + end +end diff --git a/lib/foruiman/output.rb b/lib/foruiman/output.rb new file mode 100644 index 00000000..6f598eb2 --- /dev/null +++ b/lib/foruiman/output.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +require_relative "ansi" + +class Foruiman::Output + MAX_BYTES = 16 * 1024 + + def initialize(logs, name:, stream:, pid:) + @logs = logs + @metadata = { name: name, stream: stream, pid: pid } + @decoder = Foruiman::ANSI::Decoder.new + @styles = Foruiman::ANSI::Styles.new + @text = +"" + @previous = nil + @dirty = false + @split_boundary = false + end + + def feed(bytes, eof: false) + decoded = @decoder.feed(bytes, eof: eof) + decoded.scan(/\e\[[0-9;:]*m|\n|[^\e\n]+/).each do |token| + if token == "\n" + if @split_boundary && !@dirty && !@previous + @split_boundary = false + else + publish(true) + end + elsif token.start_with?("\e[") + split_record if @text.bytesize + token.bytesize > MAX_BYTES + @text << token + @styles.apply(token) + @dirty = true + else + append_text(token) + end + end + if eof + publish(true) if @dirty || @previous + elsif @dirty + publish(false) + end + end + + private + + def append_text(text) + until text.empty? + available = MAX_BYTES - @text.bytesize + piece = text.byteslice(0, available) + piece = piece.byteslice(0, piece.bytesize - 1) until piece.valid_encoding? + if piece.empty? + split_record + next + end + @text << piece + @dirty = true + text = text.byteslice(piece.bytesize..) + split_record if @text.bytesize == MAX_BYTES + end + end + + def split_record + publish(true) + @split_boundary = true + end + + def publish(complete) + @split_boundary = false + @previous = @logs.write(**@metadata, text: @text, complete: complete, previous: @previous) + @dirty = false + return unless complete + + @text = +@styles.prefix + @previous = nil + end +end diff --git a/lib/foruiman/plain.rb b/lib/foruiman/plain.rb new file mode 100644 index 00000000..4cb460db --- /dev/null +++ b/lib/foruiman/plain.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +class Foruiman::Plain + def initialize(engine, output: $stdout) + @engine = engine + @output = output + end + + def run + @engine.on_event do |event| + record = event.record + next unless record&.complete + + text = record.text.gsub(Foruiman::ANSI::SGR, "") + @output.puts "#{record.time.strftime('%H:%M:%S')} #{record.name} [#{record.stream}] | #{text}" + @output.flush + end + @engine.run + rescue Errno::EPIPE + 0 + end +end diff --git a/lib/foruiman/process.rb b/lib/foruiman/process.rb new file mode 100644 index 00000000..0cfb3a7a --- /dev/null +++ b/lib/foruiman/process.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +# Adapted from Foreman::Process. Expansion belongs to the shell, not Ruby. +class Foruiman::Process + attr_reader :command, :env, :cwd + + def initialize(command, options = {}) + @command = command.dup.freeze + @env = (options[:env] || ENV.to_h).dup.freeze + @cwd = File.expand_path(options[:cwd] || Dir.pwd) + end + + def run(options = {}) + ::Process.spawn(env.merge(options.fetch(:env, {})), "/bin/sh", "-c", command, + chdir: cwd, in: File::NULL, out: options.fetch(:output, $stdout), + err: options.fetch(:error, $stderr), pgroup: true, unsetenv_others: true, + close_others: true) + end +end diff --git a/lib/foruiman/procfile.rb b/lib/foruiman/procfile.rb new file mode 100644 index 00000000..672ac59c --- /dev/null +++ b/lib/foruiman/procfile.rb @@ -0,0 +1,81 @@ +# frozen_string_literal: true + +# Derived from Foreman's ordered Procfile reader/writer; see docs/UPSTREAM.md. +class Foruiman::Procfile + class ParseError < Foruiman::Error + end + + class EmptyFileError < ParseError + end + + def initialize(filename = nil) + @entries = [] + load(filename) if filename + end + + def entries(&block) + return @entries.each unless block + + @entries.each(&block) + end + + def [](name) + @entries.find { |key, _command| key == name }&.last + end + + def []=(name, command) + validate_entry!(name, command, "Procfile entry") + delete(name) + @entries << [name.freeze, command.freeze].freeze + end + + def delete(name) + @entries.reject! { |key, _command| key == name } + end + + def load(filename) + parsed = parse(filename) + raise EmptyFileError, "#{filename}: no processes defined" if parsed.empty? + + @entries.replace(parsed) + self + end + + def save(filename) + File.write(filename, "#{self}\n") + end + + def to_s + @entries.map { |name, command| "#{name}: #{command}" }.join("\n") + end + + private + + def validate_entry!(name, command, location) + unless name.match?(/\A[A-Za-z0-9_-]+\z/) && !command.strip.empty? && !command.include?("\0") + raise ParseError, "#{location}: expected NAME: command" + end + raise ParseError, "#{location}: 'all' is reserved for the aggregate tab" if name == "all" + end + + def parse(filename) + seen = {} + File.read(filename, encoding: "UTF-8").lines.filter_map.with_index(1) do |line, number| + line = line.delete_suffix("\n").delete_suffix("\r") + next if line.strip.empty? || line.lstrip.start_with?("#") + + location = "#{filename}:#{number}" + match = line.match(/\A([A-Za-z0-9_-]+):[ \t]*(.*)\z/) + raise ParseError, "#{location}: expected NAME: command" unless match + + name, command = match.captures + validate_entry!(name, command, location) + raise ParseError, "#{location}: duplicate '#{name}' (first defined on line #{seen[name]})" if seen[name] + + seen[name] = number + [name.freeze, command.freeze].freeze + end + rescue ArgumentError => e + raise ParseError, "#{filename}: #{e.message}" + end +end diff --git a/lib/foruiman/ring.rb b/lib/foruiman/ring.rb new file mode 100644 index 00000000..2f718aa9 --- /dev/null +++ b/lib/foruiman/ring.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +class Foruiman::Ring + include Enumerable + + attr_reader :capacity, :size + + def initialize(capacity) + raise Foruiman::Error, "log-lines must be a positive integer" unless capacity.is_a?(Integer) && capacity.positive? + + @capacity = capacity + @slots = [] + @positions = {} + @head = 0 + @size = 0 + end + + def append(record) + index = (@head + @size) % capacity + if size == capacity + @positions.delete(@slots[index].sequence) + @head = (@head + 1) % capacity + else + @size += 1 + end + @slots[index] = record + @positions[record.sequence] = index + record + end + + def replace(record) + index = @positions[record.sequence] + @slots[index] = record if index + record + end + + def [](index) + return unless index >= 0 && index < size + + @slots[(@head + index) % capacity] + end + + def index_of(sequence) + position = @positions[sequence] + (position - @head) % capacity if position + end + + def each + return enum_for(:each) unless block_given? + + size.times { |index| yield self[index] } + end +end diff --git a/lib/foruiman/tui/application.rb b/lib/foruiman/tui/application.rb new file mode 100644 index 00000000..b55ba66b --- /dev/null +++ b/lib/foruiman/tui/application.rb @@ -0,0 +1,105 @@ +# frozen_string_literal: true + +require_relative "terminal" +require_relative "state" +require_relative "keyboard" +require_relative "renderer" + +module Foruiman::TUI + class Application + attr_reader :state + + def initialize(engine, terminal: Terminal.new, renderer: Renderer.new) + @engine = engine + @terminal = terminal + @renderer = renderer + @keyboard = Keyboard.new + @state = State.new(engine.processes.map(&:name)) + @last_frame = nil + @next_frame_at = 0 + @was_shutting_down = false + @feedback_until = 0 + end + + def run + @terminal.session do + @engine.run(keep_open: true) do + rows, columns = @terminal.size + input = @terminal.read + @engine.shutdown if input.nil? + height = [Renderer.log_height(rows: rows, columns: columns), 1].max + @keyboard.feed(input.is_a?(String) ? input : "").each { |key| handle(key, height) } + state.feedback = nil if monotonic >= @feedback_until + next if monotonic < @next_frame_at && @was_shutting_down == @engine.shutting_down? + + @was_shutting_down = @engine.shutting_down? + + @next_frame_at = monotonic + (1.0 / 30) + frame = @renderer.render(state, @engine, rows: rows, columns: columns) + if frame != @last_frame + @terminal.draw(frame) + @last_frame = frame + end + end + end + ensure + @engine.close + end + + def handle(key, height) + return if @engine.shutting_down? + + if key.is_a?(Integer) + state.select(key.zero? ? state.tabs.size - 1 : key - 1) + return + end + buffer = @engine.logs[state.name] + case key + when :next then state.move(1) + when :previous then state.move(-1) + when :up then state.viewport.scroll(-1, buffer, height) + when :down then state.viewport.scroll(1, buffer, height) + when :page_up then state.viewport.scroll(-height, buffer, height) + when :page_down then state.viewport.scroll(height, buffer, height) + when :home then state.viewport.home(buffer) + when :end, :follow then state.viewport.follow + when :toggle_follow then state.viewport.toggle(buffer, height) + when :help then state.help = !state.help + when :escape then state.help = false + when :restart, :stop then control(key) + when :restart_all, :stop_all + control_all(key == :restart_all ? :restart : :stop) + when :quit then @engine.shutdown + end + end + + private + + def control(action) + if state.name == "all" + if action == :restart + control_all(action) + else + feedback("Select a process first; S stops all processes") + end + else + @engine.public_send(action, state.name) + feedback("#{action == :restart ? 'Restarting' : 'Stopping'} #{state.name}") + end + end + + def control_all(action) + @engine.processes.each { |entry| @engine.public_send(action, entry.name) } + feedback("#{action == :restart ? 'Restarting' : 'Stopping'} all processes") + end + + def feedback(message) + state.feedback = message + @feedback_until = monotonic + 2 + end + + def monotonic + ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + end + end +end diff --git a/lib/foruiman/tui/keyboard.rb b/lib/foruiman/tui/keyboard.rb new file mode 100644 index 00000000..ae408d9a --- /dev/null +++ b/lib/foruiman/tui/keyboard.rb @@ -0,0 +1,66 @@ +# frozen_string_literal: true + +module Foruiman::TUI + class Keyboard + SEQUENCES = { + "\e[A" => :up, "\e[B" => :down, "\e[C" => :next, "\e[D" => :previous, + "\e[5~" => :page_up, "\e[6~" => :page_down, "\e[H" => :home, "\e[F" => :end, + "\e[1~" => :home, "\e[4~" => :end, "\eOH" => :home, "\eOF" => :end, + "\e[Z" => :previous + }.freeze + KEYS = { + "\t" => :next, "h" => :previous, "l" => :next, "k" => :up, "j" => :down, + "g" => :home, "G" => :end, "f" => :follow, " " => :toggle_follow, + "r" => :restart, "R" => :restart_all, "s" => :stop, "S" => :stop_all, + "?" => :help, "q" => :quit, "\x03" => :quit, + "\x15" => :page_up, "\x04" => :page_down + }.freeze + + def initialize + @buffer = +"".b + @escape_at = nil + end + + def feed(bytes, now: monotonic) + @buffer << bytes + actions = [] + until @buffer.empty? + if @buffer.start_with?("\e") + sequence = SEQUENCES.keys.find { |key| @buffer.start_with?(key) } + if sequence + actions << SEQUENCES.fetch(sequence) + @buffer.slice!(0, sequence.bytesize) + elsif incomplete_escape? + @escape_at ||= now + break if now - @escape_at < 0.1 && @buffer.bytesize < 64 + + actions << :escape if @buffer == "\e" + @buffer.clear + else + # Ignore an unknown complete escape as a unit; its final byte must + # never accidentally become a destructive shortcut such as R. + match = @buffer.match(%r{\A\e(?:\[[0-?]*[ -/]*[@-~]|O.|.)}m) + @buffer.slice!(0, match ? match[0].bytesize : 1) + end + else + key = @buffer.slice!(0, 1) + actions << (key.match?(/[0-9]/) ? key.to_i : KEYS[key]) + end + @escape_at = nil + end + actions.compact + end + + private + + def incomplete_escape? + return true if @buffer == "\e" || @buffer == "\eO" + + @buffer.start_with?("\e[") && !@buffer.match?(%r{\A\e\[[0-?]*[ -/]*[@-~]}) + end + + def monotonic + ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + end + end +end diff --git a/lib/foruiman/tui/log_formatter.rb b/lib/foruiman/tui/log_formatter.rb new file mode 100644 index 00000000..432bbb5d --- /dev/null +++ b/lib/foruiman/tui/log_formatter.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require_relative "text" +require_relative "theme" + +module Foruiman::TUI + class LogFormatter + def initialize(theme, names) + @theme = theme + @colors = names.each_with_index.to_h { |name, index| [name, theme.process(index)] } + @name_width = names.map { |name| Text.width(name) }.max.to_i.clamp(3, 14) + end + + def row(record, aggregate:, width:) + prefix = +"" + prefix << @theme.paint("#{record.time.strftime('%H:%M:%S')} ", :faint) if width >= 55 + if aggregate + name_width = [@name_width, width / 5].min + name = Text.pad(Text.clip(record.name, name_width, ellipsis: true), name_width) + prefix << @theme.paint(name, @colors.fetch(record.name, :cyan)) << " " + end + marker, color = stream_style(record.stream) + prefix << @theme.paint(marker, color) << @theme.paint(" │ ", :border) + content = record.stream == :lifecycle ? record.text.delete_prefix("--- ").delete_suffix(" ---") : record.text + content = Text.clip(content, [width - Text.width(prefix), 0].max, ellipsis: true) + prefix + @theme.log(content, color: body_color(record.stream)) + end + + private + + def stream_style(stream) + case stream + when :stderr then ["err", :red] + when :lifecycle then ["sys", :amber] + else ["out", :faint] + end + end + + def body_color(stream) + case stream + when :stderr then :red + when :lifecycle then :muted + else :text + end + end + end +end diff --git a/lib/foruiman/tui/renderer.rb b/lib/foruiman/tui/renderer.rb new file mode 100644 index 00000000..da9b78a8 --- /dev/null +++ b/lib/foruiman/tui/renderer.rb @@ -0,0 +1,306 @@ +# frozen_string_literal: true + +require_relative "text" +require_relative "theme" +require_relative "log_formatter" +require "pathname" + +module Foruiman::TUI + class Renderer + HELP = [ + ["↔ NAVIGATE", "Tab / Shift-Tab", "Change tab", "← → or h l"], + [nil, "1–9 / 0", "Select a process / all logs", nil], + ["≡ READ LOGS", "↑ ↓ or k j", "Scroll a line", nil], + [nil, "PgUp / PgDn", "Scroll a page", "Ctrl-U / Ctrl-D"], + [nil, "g / Home", "Oldest retained line", nil], + [nil, "f / G / End", "Follow newest output", nil], + [nil, "Space", "Pause / resume following", nil], + ["⚙ PROCESSES", "r / R", "Restart selected / all", "r on all restarts all"], + [nil, "s / S", "Stop selected / all", nil], + ["◇ SESSION", "? / Escape", "Close help", nil], + [nil, "q / Ctrl-C", "Stop processes and quit", nil] + ].freeze + + def initialize(theme: Theme.new) + @theme = theme + @first_tab = 0 + end + + def self.expanded?(rows:, columns:) + rows >= 14 && columns >= 60 + end + + def self.log_height(rows:, columns:) + return 0 if rows < 6 || columns < 24 + + rows - (expanded?(rows: rows, columns: columns) ? 7 : 5) + end + + def render(state, engine, rows:, columns:) + @width = [columns - 1, 1].max + @inside = [@width - 4, 0].max + @height = self.class.log_height(rows: rows, columns: columns) + return tiny_frame(state, engine, rows) if @height.zero? + + lines = [header(engine)] + if self.class.expanded?(rows: rows, columns: columns) + hint = @inside >= 70 ? " Tab switch · 1–9 / 0 select " : "" + lines << border(@theme.paint(" processes ", :muted, bold: true), @theme.paint(hint, :faint)) + lines << panel(tab_row(state, engine, @inside - 2)) + lines << border("", "", bottom: true) + else + lines << " #{@theme.paint('│', :border)} #{tab_row(state, engine, @inside - 2)}" + end + lines << log_header(state, engine) + lines.concat(state.help ? help_rows : log_rows(state, engine)) + lines << log_footer(state, engine) + lines << controls(state, engine) + frame(lines, rows) + end + + def self.width(text) + Text.width(text) + end + + def self.truncate(text, columns) + Text.clip(text, columns) + Foruiman::ANSI::RESET + end + + private + + def header(engine) + brand = @width >= 45 ? "▰ FORUIMAN" : "▰" + left = " #{@theme.paint(brand, :accent, bold: true)}" + right = if engine.shutting_down? + @theme.paint("◌ shutting down", :amber) + elsif @width >= 60 + summary(engine) + else + "" + end + source = if engine.procfile_path + Text.clean(Pathname.new(engine.procfile_path).relative_path_from(Pathname.new(engine.root)).to_s) + end + project = @theme.paint(" / #{Text.clean(File.basename(engine.root))}", :muted) + left += project if @width >= 70 && Text.width(left + project + source.to_s + right) + 5 <= @width + if source + available = [@width - Text.width(left + right) - 4, 0].max + source = "…/#{File.basename(source)}" if Text.width(source) > available && source.include?("/") + left += @theme.paint(" #{Text.clip(source, available, ellipsis: true)}") + end + distribute(left, "#{right} ", @width) + end + + def summary(engine) + running = engine.processes.count { |entry| entry.status == :running } + failed = engine.processes.count { |entry| entry.status == :failed } + summary = @theme.paint("● #{running} running", running.positive? ? :green : :muted) + summary += @theme.paint(" × #{failed} failed", :red) if failed.positive? && @width >= 55 + summary + end + + def tab_row(state, engine, width) + @first_tab = state.selected if state.selected < @first_tab + labels = state.tabs.each_with_index.map { |name, index| tab(name, index, state, engine, width) } + @first_tab += 1 while @first_tab < state.selected && tab_span(labels, @first_tab, state.selected) > width + output = +(@first_tab.positive? ? @theme.paint("‹ ", :muted) : "") + index = @first_tab + while index < labels.size + separator = index == @first_tab ? "" : " " + more = index < labels.size - 1 ? 2 : 0 + available = width - Text.width(output) - more - separator.size + break if Text.width(labels[index]) > available && index > @first_tab + + output << separator << Text.clip(labels[index], [available, 0].max) << @theme.reset + index += 1 + end + output << @theme.paint(" ›", :muted) if index < labels.size + Text.clip(output, width) + end + + def tab_span(labels, first, last) + Text.width(labels[first..last].join(" ")) + (first.positive? ? 2 : 0) + (last < labels.size - 1 ? 2 : 0) + end + + def tab(name, index, state, engine, width) + selected = index == state.selected + entry = name == "all" ? nil : engine.processes.find { |process| process.name == name } + mark = name == "all" ? "≡" : Theme::STATUS_MARKS.fetch(entry&.status, "○") + number = if name == "all" + "0" + else + (index < 9 ? (index + 1).to_s : "·") + end + name = Text.clip(name, [width - 12, 6].max.clamp(6, 22), ellipsis: true) + color = name == "all" ? :accent : @theme.process(index) + mark_color = entry ? Theme::STATUS_COLORS.fetch(entry.status, :muted) : :muted + @theme.paint(" #{number} ", selected ? :muted : :faint, selected: selected) + + @theme.paint("#{mark} ", mark_color, selected: selected) + + @theme.paint("#{name} ", color, selected: selected, bold: selected) + end + + def log_header(state, engine) + if state.help + return border(@theme.paint(" ⌨ keyboard shortcuts ", :text, bold: true), + @theme.paint(" ? / Escape close help ", :muted)) + end + + title = state.name == "all" ? " ≡ all logs " : " › #{state.name} " + detail = if state.name == "all" + "#{engine.processes.size} processes" + else + entry = engine.state(state.name) + process_detail(entry) + end + active = if state.name == "all" + engine.processes.any? { |entry| entry.status == :running } + else + engine.state(state.name).status == :running + end + mode = if !state.viewport.following + @theme.paint(" Ⅱ PAUSED ", :amber) + elsif active + @theme.paint(" ● LIVE ", :green) + else + @theme.paint(" ↓ FOLLOW ", :muted) + end + title = @theme.paint(title, :text, bold: true) + if @inside >= 45 + title += @theme.paint(" #{detail} ", :muted) + elsif state.name != "all" && @inside >= 28 + entry = engine.state(state.name) + title += @theme.paint(" #{entry.status} ", Theme::STATUS_COLORS.fetch(entry.status, :muted)) + end + border(title, mode) + end + + def process_detail(entry) + detail = "#{entry.status} · PID #{entry.pid || '-'}" + if entry.exit_status + code = entry.exit_status.exitstatus || "signal #{entry.exit_status.termsig}" + detail += " · exit #{code}" + elsif entry.port && @inside >= 75 + detail += " · PORT #{entry.port}" + end + detail + end + + def log_rows(state, engine) + @formatter ||= LogFormatter.new(@theme, engine.process_names) + buffer = engine.logs[state.name] + records = state.viewport.rows(buffer, @height) + @visible = records + first = records.empty? ? 0 : buffer.index_of(records.first.sequence).to_i + thumb_size = buffer.none? ? @height : [(@height * @height / buffer.size), 1].max.clamp(1, @height) + travel = @height - thumb_size + thumb_start = buffer.size <= @height ? 0 : (first * travel / (buffer.size - @height)) + Array.new(@height) do |index| + content = if records[index] + @formatter.row(records[index], aggregate: state.name == "all", width: @inside - 2) + elsif records.empty? && index == @height / 2 + @theme.paint("Waiting for output…", :faint) + else + "" + end + thumb = buffer.size > @height && index.between?(thumb_start, thumb_start + thumb_size - 1) + panel(content, scroll: if thumb + state.viewport.following ? :green : :amber + end) + end + end + + def log_footer(state, engine) + return border("", "", bottom: true) if state.help + + buffer = engine.logs[state.name] + first = @visible&.first + last = @visible&.last + range = first ? "#{buffer.index_of(first.sequence) + 1}–#{buffer.index_of(last.sequence) + 1}" : "0" + count = " #{range} / #{buffer.size} lines " + location = if state.viewport.following + " following " + else + " f resume " + end + location = " PID #{engine.state(state.name).pid || '-'} " if state.name != "all" && @inside < 45 + border(@theme.paint(count, :faint), @theme.paint(location, state.viewport.following ? :faint : :amber), + bottom: true) + end + + def help_rows + rows = [] + HELP.each do |section, key, description, alias_keys| + if section && @height >= 15 + rows << panel("") if !rows.empty? && @height >= 18 + rows << panel(@theme.paint(section, :accent, bold: true)) + end + line = @theme.paint(Text.pad(key, 18), :amber, bold: true) + @theme.paint(description) + line += @theme.paint(" #{alias_keys}", :faint) if alias_keys && @inside >= 75 + rows << panel(line) + end + rows = rows.first(@height) + rows << panel("") while rows.size < @height + rows + end + + def controls(state, engine) + quit = @theme.paint(" q ", :accent, bold: true) + @theme.paint(" × quit ", :muted) + left = if engine.shutting_down? + @theme.paint(" ◌ Stopping process groups · TERM → KILL after 5s", :amber) + elsif state.feedback + @theme.paint(" #{state.feedback}", :amber) + elsif state.help + @theme.paint(" ? / Escape close help", :muted) + else + shortcuts(state) + end + distribute(left, quit, @width) + end + + def shortcuts(state) + restart = ["r", state.name == "all" ? "↻ restart all" : "↻ restart"] + pairs = [%w[Tab switch], ["↑↓", "scroll"], %w[f follow], restart, ["?", "help"]] + pairs = [restart, ["?", "help"]] if @width < 65 + pairs.map do |key, label| + @theme.paint(" #{key} ", :accent, bold: true) + @theme.paint(" #{label} ", :muted) + end.join + end + + def border(left, right = "", bottom: false) + corners = bottom ? %w[╰ ╯] : %w[╭ ╮] + middle = distribute(left, right, @inside, fill: "─") + " #{@theme.paint(corners.first, :border)}#{@theme.paint(middle, :border)}#{@theme.paint(corners.last, :border)} " + end + + def panel(content, scroll: nil) + inside = Text.pad(Text.clip(content, @inside - 2), @inside - 2) + edge = @theme.paint(scroll ? "┃" : "│", scroll || :border) + " #{@theme.paint('│', :border)} #{inside}#{@theme.reset} #{edge} " + end + + def distribute(left, right, width, fill: " ") + right = Text.clip(right, [width / 2, Text.width(right)].min) + available = [width - Text.width(right), 0].max + left = Text.clip(left, available, ellipsis: true) + gap = [width - Text.width(left) - Text.width(right), 0].max + left + @theme.reset + @theme.paint(fill * gap, :border) + right + @theme.reset + end + + def tiny_frame(state, engine, rows) + title = @theme.paint(" FORUIMAN", :accent, bold: true) + message = engine.shutting_down? ? " Stopping…" : " #{state.name} · enlarge terminal" + lines = [title, @theme.paint(message, :muted)] + lines[rows - 1] = @theme.paint(" q quit", :accent) if rows > 2 + frame(lines, rows) + end + + def frame(lines, rows) + rendered = Array.new(rows) do |index| + # Erase before drawing, then restore the theme defaults. Reserve the last + # cell to avoid terminal autowrap. + "\e[2K#{@theme.base}#{self.class.truncate(lines[index].to_s, @width)}" + end.join("\r\n") + "\e[H#{rendered}" + end + end +end diff --git a/lib/foruiman/tui/state.rb b/lib/foruiman/tui/state.rb new file mode 100644 index 00000000..3ca249d4 --- /dev/null +++ b/lib/foruiman/tui/state.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require_relative "viewport" + +module Foruiman::TUI + class State + attr_reader :tabs, :selected, :viewports + attr_accessor :help, :feedback + + def initialize(names) + @tabs = [*names, "all"].freeze + @selected = tabs.size - 1 + @viewports = tabs.to_h { |name| [name, Viewport.new] } + @help = false + @feedback = nil + end + + def name + tabs[selected] + end + + def viewport + viewports.fetch(name) + end + + def select(index) + @selected = index if index.between?(0, tabs.size - 1) + end + + def move(delta) + @selected = (selected + delta) % tabs.size + end + end +end diff --git a/lib/foruiman/tui/terminal.rb b/lib/foruiman/tui/terminal.rb new file mode 100644 index 00000000..f44c94c2 --- /dev/null +++ b/lib/foruiman/tui/terminal.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +require "io/console" + +module Foruiman::TUI + class Terminal + ENTER = "\e[?1049h\e[?25l\e[0m" + LEAVE = "\e[0m\e[?25h\e[?1049l" + + def initialize(input: $stdin, output: $stdout) + @input = input + @output = output + end + + def session(&) + @output.write(ENTER) + @output.flush + @input.raw(intr: false, &) + ensure + begin + @output.write(LEAVE) + @output.flush + rescue IOError, SystemCallError + # Input's raw block has already restored its exact prior terminal mode. + end + end + + def size + rows, columns = @output.winsize + [[rows, 1].max, [columns, 1].max] + rescue IOError, SystemCallError + [24, 80] + end + + def read + @input.read_nonblock(4096, exception: false) + end + + def draw(frame) + @output.write(frame) + @output.flush + end + end +end diff --git a/lib/foruiman/tui/text.rb b/lib/foruiman/tui/text.rb new file mode 100644 index 00000000..9e1ead34 --- /dev/null +++ b/lib/foruiman/tui/text.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +require "unicode/display_width" +require_relative "../ansi" + +module Foruiman::TUI + module Text + module_function + + def width(text) + Unicode::DisplayWidth.of(text.gsub(Foruiman::ANSI::SGR, ""), emoji: :all) + end + + def clip(text, columns, ellipsis: false) + return "" unless columns.positive? + return text if width(text) <= columns + + limit = ellipsis ? columns - 1 : columns + used = 0 + output = +"" + text.scan(/\e\[[0-9;:]*m|\X/).each do |token| + if token.start_with?("\e[") + output << token + next + end + cells = Unicode::DisplayWidth.of(token, emoji: :all) + break if used + cells > limit + + output << token + used += cells + end + output << "…" if ellipsis + output + end + + def pad(text, columns) + clipped = clip(text, columns) + clipped + (" " * [columns - width(clipped), 0].max) + end + + def clean(text) + Foruiman::ANSI::Decoder.new.feed(text, eof: true).gsub(Foruiman::ANSI::SGR, "").tr("\n", " ") + end + end +end diff --git a/lib/foruiman/tui/theme.rb b/lib/foruiman/tui/theme.rb new file mode 100644 index 00000000..7caed234 --- /dev/null +++ b/lib/foruiman/tui/theme.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +require_relative "../ansi" + +module Foruiman::TUI + # Use the terminal's palette and default background, so its theme owns the + # actual colors (and can change them while Foruiman is running). + class Theme + COLORS = { + text: 39, muted: 90, faint: 90, border: 90, accent: 36, + green: 32, red: 31, amber: 33, cyan: 36, blue: 34, mauve: 35 + }.freeze + PROCESS_COLORS = %i[cyan amber mauve green blue red].freeze + STATUS_COLORS = { + pending: :faint, running: :green, restarting: :amber, stopping: :amber, + stopped: :muted, exited: :muted, failed: :red + }.freeze + STATUS_MARKS = { + pending: "○", running: "●", restarting: "↻", stopping: "◌", + stopped: "■", exited: "✓", failed: "×" + }.freeze + + attr_reader :enabled + + def initialize(env: ENV) + @enabled = env.fetch("NO_COLOR", "").empty? && env["TERM"] != "dumb" + end + + def base + enabled ? "\e[39m\e[49m" : "" + end + + def paint(text, color = :text, selected: false, bold: false) + emphasis = "#{"\e[7m" if selected}#{"\e[1m" if bold}" + return emphasis.empty? ? text : "#{emphasis}#{text}#{reset}" unless enabled + + defaults = selected ? base : "#{code(color)}\e[49m" + "#{defaults}#{emphasis}#{text}#{reset}" + end + + def reset + enabled ? Foruiman::ANSI::RESET + base : Foruiman::ANSI::RESET + end + + def process(index) + PROCESS_COLORS[index % PROCESS_COLORS.size] + end + + # A child reset restores the UI's defaults. Explicit child colors, including + # background colors, still win; they cannot bleed into borders or later rows. + def log(text, color: :text) + return text.gsub(Foruiman::ANSI::SGR, "") unless enabled + + defaults = "#{code(color)}\e[49m" + styles = Foruiman::ANSI::Styles.new + content = text.gsub(Foruiman::ANSI::SGR) do |sequence| + styles.apply(sequence) + Foruiman::ANSI::RESET + defaults + styles.prefix + end + defaults + content + reset + end + + private + + def code(color) + return "" unless enabled + + "\e[#{COLORS.fetch(color)}m" + end + end +end diff --git a/lib/foruiman/tui/viewport.rb b/lib/foruiman/tui/viewport.rb new file mode 100644 index 00000000..cf9b1a01 --- /dev/null +++ b/lib/foruiman/tui/viewport.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +module Foruiman::TUI + class Viewport + attr_reader :following, :anchor + + def initialize + @following = true + @anchor = nil + end + + def rows(buffer, height) + height = [height, 0].max + start = top(buffer, height) + Array.new([height, buffer.size - start].min) { |offset| buffer[start + offset] } + end + + def scroll(delta, buffer, height) + index = top(buffer, height) + @following = false + set_anchor(index + delta, buffer, height) + end + + def home(buffer) + @following = false + @anchor = buffer[0]&.sequence + end + + def follow + @following = true + @anchor = nil + end + + def toggle(buffer, height) + following ? scroll(0, buffer, height) : follow + end + + private + + def top(buffer, height) + last = [buffer.size - height, 0].max + return last if following + + index = buffer.index_of(anchor) || 0 + index = [index, last].min + @anchor = buffer[index]&.sequence + index + end + + def set_anchor(index, buffer, height) + last = [buffer.size - height, 0].max + index = index.clamp(0, last) + @anchor = buffer[index]&.sequence + end + end +end diff --git a/lib/foruiman/version.rb b/lib/foruiman/version.rb new file mode 100644 index 00000000..8fb15aba --- /dev/null +++ b/lib/foruiman/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module Foruiman + VERSION = "0.1.2" +end diff --git a/man/foreman.1 b/man/foreman.1 deleted file mode 100644 index 12f93a8b..00000000 --- a/man/foreman.1 +++ /dev/null @@ -1,181 +0,0 @@ -.\" generated with Ronn-NG/v0.10.1 -.\" http://github.com/apjanke/ronn-ng/tree/0.10.1 -.TH "FOREMAN" "1" "July 2025" "Foreman 0.90.0" "Foreman Manual" -.SH "NAME" -\fBforeman\fR \- manage Procfile\-based applications -.SH "SYNOPSIS" -\fBforeman start [process]\fR -.br -\fBforeman run \fR -.br -\fBforeman export [location]\fR -.SH "DESCRIPTION" -Foreman is a manager for Procfile\-based applications\. Its aim is to abstract away the details of the Procfile format, and allow you to either run your application directly or export it to some other process management format\. -.SH "RUNNING" -\fBforeman start\fR is used to run your application directly from the command line\. -.P -If no additional parameters are passed, foreman will run one instance of each type of process defined in your Procfile\. -.P -If a parameter is passed, foreman will run one instance of the specified application type\. -.P -The following options control how the application is run: -.TP -\fB\-m\fR, \fB\-\-formation\fR -Specify the number of each process type to run\. The value passed in should be in the format \fBprocess=num,process=num\fR -.TP -\fB\-e\fR, \fB\-\-env\fR -Specify one or more \.env files to load -.TP -\fB\-f\fR, \fB\-\-procfile\fR -Specify an alternate Procfile to load, implies \fB\-d\fR at the Procfile root\. -.TP -\fB\-p\fR, \fB\-\-port\fR -Specify which port to use as the base for this application\. Should be a multiple of 1000\. -.TP -\fB\-t\fR, \fB\-\-timeout\fR -Specify the amount of time (in seconds) processes have to shutdown gracefully before receiving a SIGKILL, defaults to 5\. -.P -\fBforeman run\fR is used to run one\-off commands using the same environment as your defined processes\. -.SH "EXPORTING" -\fBforeman export\fR is used to export your application to another process management format\. -.P -A location to export can be passed as an argument\. This argument may be either required or optional depending on the export format\. -.P -The following options control how the application is run: -.TP -\fB\-a\fR, \fB\-\-app\fR -Use this name rather than the application's root directory name as the name of the application when exporting\. -.TP -\fB\-m\fR, \fB\-\-formation\fR -Specify the number of each process type to run\. The value passed in should be in the format \fBprocess=num,process=num\fR -.TP -\fB\-l\fR, \fB\-\-log\fR -Specify the directory to place process logs in\. -.TP -\fB\-p\fR, \fB\-\-port\fR -Specify which port to use as the base for this application\. Should be a multiple of 1000\. -.TP -\fB\-t\fR, \fB\-\-template\fR -Specify an alternate template to use for creating export files\. See \fIhttps://github\.com/ddollar/foreman/tree/master/data/export\fR for examples\. -.TP -\fB\-u\fR, \fB\-\-user\fR -Specify the user the application should be run as\. Defaults to the app name -.SH "GLOBAL OPTIONS" -These options control all modes of foreman's operation\. -.TP -\fB\-d\fR, \fB\-\-root\fR -Specify an alternate application root\. This defaults to the directory containing the Procfile\. -.TP -\fB\-e\fR, \fB\-\-env\fR -Specify an alternate environment file\. You can specify more than one file by using: \fB\-\-env file1,file2\fR\. -.TP -\fB\-f\fR, \fB\-\-procfile\fR -Specify an alternate location for the application's Procfile\. This file's containing directory will be assumed to be the root directory of the application\. -.SH "EXPORT FORMATS" -foreman currently supports the following output formats: -.IP "\(bu" 4 -bluepill -.IP "\(bu" 4 -inittab -.IP "\(bu" 4 -launchd -.IP "\(bu" 4 -runit -.IP "\(bu" 4 -supervisord -.IP "\(bu" 4 -systemd -.IP "\(bu" 4 -upstart -.IP "" 0 -.SH "INITTAB EXPORT" -Will export a chunk of inittab\-compatible configuration: -.IP "" 4 -.nf -# \-\-\-\-\- foreman example processes \-\-\-\-\- -EX01:4:respawn:/bin/su \- example \-c 'PORT=5000 bundle exec thin start >> /var/log/web\-1\.log 2>&1' -EX02:4:respawn:/bin/su \- example \-c 'PORT=5100 bundle exec rake jobs:work >> /var/log/job\-1\.log 2>&1' -# \-\-\-\-\- end foreman example processes \-\-\-\-\- -.fi -.IP "" 0 -.SH "SYSTEMD EXPORT" -Will create a series of systemd scripts in the location you specify\. Scripts will be structured to make the following commands valid: -.P -\fBsystemctl start appname\.target\fR -.P -\fBsystemctl stop appname\-processname\.target\fR -.P -\fBsystemctl restart appname\-processname\-3\.service\fR -.SH "UPSTART EXPORT" -Will create a series of upstart scripts in the location you specify\. Scripts will be structured to make the following commands valid: -.P -\fBstart appname\fR -.P -\fBstop appname\-processname\fR -.P -\fBrestart appname\-processname\-3\fR -.SH "PROCFILE" -A Procfile should contain both a name for the process and the command used to run it\. -.IP "" 4 -.nf -web: bundle exec thin start -job: bundle exec rake jobs:work -.fi -.IP "" 0 -.P -A process name may contain letters, numbers and the underscore character\. You can validate your Procfile format using the \fBcheck\fR command: -.IP "" 4 -.nf -$ foreman check -.fi -.IP "" 0 -.P -The special environment variables \fB$PORT\fR and \fB$PS\fR are available within the Procfile\. \fB$PORT\fR is the port selected for that process\. \fB$PS\fR is the name of the process for the line\. -.P -The \fB$PORT\fR value starts as the base port as specified by \fB\-p\fR, then increments by 100 for each new process line\. Multiple instances of the same process are assigned \fB$PORT\fR values that increment by 1\. -.SH "ENVIRONMENT" -If a \fB\.env\fR file exists in the current directory, the default environment will be read from it\. This file should contain key/value pairs, separated by \fB=\fR, with one key/value pair per line\. -.IP "" 4 -.nf -FOO=bar -BAZ=qux -.fi -.IP "" 0 -.SH "DEFAULT OPTIONS" -If a \fB\.foreman\fR file exists in the current directory, default options will be read from it\. This file should be in YAML format with the long option name as keys\. Example: -.IP "" 4 -.nf -formation: alpha=0,bravo=1 -port: 15000 -.fi -.IP "" 0 -.SH "EXAMPLES" -Start one instance of each process type, interleave the output on stdout: -.IP "" 4 -.nf -$ foreman start -.fi -.IP "" 0 -.P -Export the application in upstart format: -.IP "" 4 -.nf -$ foreman export upstart /etc/init -.fi -.IP "" 0 -.P -Run one process type from the application defined in a specific Procfile: -.IP "" 4 -.nf -$ foreman start alpha \-f ~/myapp/Procfile -.fi -.IP "" 0 -.P -Start all processes except the one named worker: -.IP "" 4 -.nf -$ foreman start \-m all=1,worker=0 -.fi -.IP "" 0 -.SH "COPYRIGHT" -Foreman is Copyright (C) 2010 David Dollar \fIhttp://daviddollar\.org\fR diff --git a/man/foreman.1.ronn b/man/foreman.1.ronn deleted file mode 100644 index 78e07350..00000000 --- a/man/foreman.1.ronn +++ /dev/null @@ -1,208 +0,0 @@ -foreman(1) -- manage Procfile-based applications -================================================ - -## SYNOPSIS - -`foreman start [process]`
-`foreman run `
-`foreman export [location]` - -## DESCRIPTION - -Foreman is a manager for Procfile-based applications. Its aim is to -abstract away the details of the Procfile format, and allow you to either run -your application directly or export it to some other process management -format. - -## RUNNING - -`foreman start` is used to run your application directly from the command line. - -If no additional parameters are passed, foreman will run one instance of each -type of process defined in your Procfile. - -If a parameter is passed, foreman will run one instance of the specified -application type. - -The following options control how the application is run: - - * `-m`, `--formation`: - Specify the number of each process type to run. The value passed in - should be in the format `process=num,process=num` - - * `-e`, `--env`: - Specify one or more .env files to load - - * `-f`, `--procfile`: - Specify an alternate Procfile to load, implies `-d` at the Procfile root. - - * `-p`, `--port`: - Specify which port to use as the base for this application. Should be - a multiple of 1000. - - * `-t`, `--timeout`: - Specify the amount of time (in seconds) processes have to shutdown - gracefully before receiving a SIGKILL, defaults to 5. - -`foreman run` is used to run one-off commands using the same environment -as your defined processes. - -## EXPORTING - -`foreman export` is used to export your application to another process -management format. - -A location to export can be passed as an argument. This argument may be -either required or optional depending on the export format. - -The following options control how the application is run: - - * `-a`, `--app`: - Use this name rather than the application's root directory name as the - name of the application when exporting. - - * `-m`, `--formation`: - Specify the number of each process type to run. The value passed in - should be in the format `process=num,process=num` - - * `-l`, `--log`: - Specify the directory to place process logs in. - - * `-p`, `--port`: - Specify which port to use as the base for this application. Should be - a multiple of 1000. - - * `-t`, `--template`: - Specify an alternate template to use for creating export files. - See for examples. - - * `-u`, `--user`: - Specify the user the application should be run as. Defaults to the - app name - -## GLOBAL OPTIONS - -These options control all modes of foreman's operation. - - * `-d`, `--root`: - Specify an alternate application root. This defaults to the directory - containing the Procfile. - - * `-e`, `--env`: - Specify an alternate environment file. You can specify more than one - file by using: `--env file1,file2`. - - * `-f`, `--procfile`: - Specify an alternate location for the application's Procfile. This file's - containing directory will be assumed to be the root directory of the - application. - -## EXPORT FORMATS - -foreman currently supports the following output formats: - - * bluepill - - * inittab - - * launchd - - * runit - - * supervisord - - * systemd - - * upstart - -## INITTAB EXPORT - -Will export a chunk of inittab-compatible configuration: - - # ----- foreman example processes ----- - EX01:4:respawn:/bin/su - example -c 'PORT=5000 bundle exec thin start >> /var/log/web-1.log 2>&1' - EX02:4:respawn:/bin/su - example -c 'PORT=5100 bundle exec rake jobs:work >> /var/log/job-1.log 2>&1' - # ----- end foreman example processes ----- - -## SYSTEMD EXPORT - -Will create a series of systemd scripts in the location you specify. Scripts -will be structured to make the following commands valid: - - `systemctl start appname.target` - - `systemctl stop appname-processname.target` - - `systemctl restart appname-processname-3.service` - -## UPSTART EXPORT - -Will create a series of upstart scripts in the location you specify. Scripts -will be structured to make the following commands valid: - - `start appname` - - `stop appname-processname` - - `restart appname-processname-3` - -## PROCFILE - -A Procfile should contain both a name for the process and the command used -to run it. - - web: bundle exec thin start - job: bundle exec rake jobs:work - -A process name may contain letters, numbers and the underscore character. -You can validate your Procfile format using the `check` command: - - $ foreman check - -The special environment variables `$PORT` and `$PS` are available within the -Procfile. `$PORT` is the port selected for that process. `$PS` is the name of -the process for the line. - -The `$PORT` value starts as the base port as specified by `-p`, then increments -by 100 for each new process line. Multiple instances of the same process are -assigned `$PORT` values that increment by 1. - -## ENVIRONMENT - -If a `.env` file exists in the current directory, the default environment will -be read from it. This file should contain key/value pairs, separated by `=`, with -one key/value pair per line. - - FOO=bar - BAZ=qux - -## DEFAULT OPTIONS - -If a `.foreman` file exists in the current directory, default options will -be read from it. This file should be in YAML format with the long option -name as keys. Example: - - formation: alpha=0,bravo=1 - port: 15000 - -## EXAMPLES - -Start one instance of each process type, interleave the output on stdout: - - $ foreman start - -Export the application in upstart format: - - $ foreman export upstart /etc/init - -Run one process type from the application defined in a specific Procfile: - - $ foreman start alpha -f ~/myapp/Procfile - -Start all processes except the one named worker: - - $ foreman start -m all=1,worker=0 - -## COPYRIGHT - -Foreman is Copyright (C) 2010 David Dollar diff --git a/pkg/.gitignore b/pkg/.gitignore deleted file mode 100644 index e69de29b..00000000 diff --git a/script/preview.rb b/script/preview.rb new file mode 100644 index 00000000..4fd9ff7e --- /dev/null +++ b/script/preview.rb @@ -0,0 +1,73 @@ +# frozen_string_literal: true + +# A static design fixture. No child processes are started. +# ruby -Ilib script/preview.rb [columns] [rows] [all|web|worker|assets|jobs|help] +require "foruiman" +require "foruiman/tui/renderer" +require "foruiman/tui/state" + +PreviewEngine = Struct.new(:root, :procfile_path, :processes, :logs, keyword_init: true) do + def process_names + processes.map(&:name) + end + + def state(name) + processes.find { |entry| entry.name == name } + end + + def shutting_down? + false + end +end + +columns = Integer(ARGV.fetch(0, "116")) +rows = Integer(ARGV.fetch(1, "30")) +selection = ARGV.fetch(2, "all") +names = %w[web worker assets jobs] +processes = names.each_with_index.map do |name, index| + Foruiman::Engine::State.new(name: name, pid: 28_410 + index, port: 3000 + (index * 100), + generation: 1, status: name == "jobs" ? :failed : :running) +end +logs = Foruiman::LogStore.new(names, capacity: 10_000) +entries = [ + ["web", :lifecycle, "--- started with pid 28410 (generation 1) ---"], + ["worker", :lifecycle, "--- started with pid 28411 (generation 1) ---"], + ["assets", :lifecycle, "--- started with pid 28412 (generation 1) ---"], + ["web", :stdout, "Puma starting in single mode…"], + ["web", :stdout, "* Listening on http://127.0.0.1:3000"], + ["worker", :stdout, "Connected to Redis at redis://localhost:6379/0"], + ["assets", :stdout, "\e[1mVITE\e[0m v6.2.0 ready in \e[32m182 ms\e[0m"], + ["assets", :stdout, "➜ Local: http://localhost:3200/"], + ["web", :stdout, 'Started GET "/dashboard" for 127.0.0.1'], + ["web", :stdout, "Processing by DashboardController#index as HTML"], + ["web", :stdout, " User Load (0.4ms) SELECT users.* FROM users WHERE id = 1"], + ["worker", :stdout, "DailyDigestJob started jid=9b8a2c queue=default"], + ["web", :stdout, " Rendered dashboard/index.html.erb (Duration: 12.8ms)"], + ["web", :stdout, "Completed \e[32m200 OK\e[0m in 34ms (Views: 18.2ms | ActiveRecord: 1.4ms)"], + ["worker", :stdout, "DailyDigestJob done elapsed=0.126s"], + ["jobs", :stderr, "Connection refused — connect(2) for 127.0.0.1:5433"], + ["jobs", :stderr, "PG::ConnectionBad: could not connect to the background database"], + ["jobs", :lifecycle, "--- exited with code 1 ---"], + ["assets", :stdout, "[vite] hmr update /app/frontend/components/dashboard.tsx"], + ["web", :stdout, 'Started GET "/api/projects" for 127.0.0.1'], + ["web", :stdout, " Project Load (0.8ms) SELECT projects.* ORDER BY updated_at DESC"], + ["web", :stdout, "Completed \e[32m200 OK\e[0m in 8ms (ActiveRecord: 0.8ms)"], + ["worker", :stdout, "SyncProjectJob started jid=31d8f0 queue=default"], + ["worker", :stdout, "Synced 24 projects elapsed=0.842s"], + ["assets", :stdout, "[vite] page reload app/views/layouts/application.html.erb"], + ["web", :stdout, "Completed \e[32m200 OK\e[0m in 21ms (Views: 12.1ms | ActiveRecord: 2.3ms)"], + ["worker", :stdout, "Waiting for jobs…"] +] +entries.each_with_index do |(name, stream, text), index| + record = logs.write(name: name, stream: stream, pid: processes.find { |entry| entry.name == name }.pid, + text: text, complete: true) + record = record.with(time: Time.utc(2026, 9, 9, 14, 32, index).freeze) + logs[name].replace(record) + logs.all.replace(record) +end +engine = PreviewEngine.new(root: "/work/atlas", procfile_path: "/work/atlas/Procfile.dev", processes: processes, + logs: logs) +state = Foruiman::TUI::State.new(names) +state.select(names.index(selection)) if names.include?(selection) +state.help = selection == "help" +print Foruiman::TUI::Renderer.new.render(state, engine, rows: rows, columns: columns) diff --git a/script/smoke_gem.rb b/script/smoke_gem.rb new file mode 100644 index 00000000..b1f100ce --- /dev/null +++ b/script/smoke_gem.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +require "tmpdir" +require "open3" +require "rbconfig" +require "shellwords" +require_relative "../lib/foruiman/version" + +archive = File.expand_path(ARGV.fetch(0, "foruiman-#{Foruiman::VERSION}.gem")) +Dir.mktmpdir("foruiman-gem-smoke-") do |directory| + install = File.join(directory, "gems") + # Dependencies are supplied by bundle install; install only the built artifact. + success = system(RbConfig.ruby, "-S", "gem", "install", "--local", archive, + "--install-dir", install, "--no-document", "--ignore-dependencies") + abort "gem installation failed" unless success + + env = { "GEM_HOME" => install, "GEM_PATH" => [install, *Gem.path].join(File::PATH_SEPARATOR), + "RUBYOPT" => nil, "BUNDLE_GEMFILE" => nil } + executable = File.join(install, "bin", "foruiman") + ruby_command = [RbConfig.ruby, "-e", 'puts "packaged gem works"'].shelljoin + File.write(File.join(directory, "Procfile"), "web: #{ruby_command}\n") + stdout, stderr, status = Open3.capture3(env, executable, "start", "--no-tui", chdir: directory) + abort "installed gem failed: #{stdout}\n#{stderr}" unless status.success? && stdout.include?("packaged gem works") + + puts "Installed gem smoke test passed" +end diff --git a/spec/fixtures/child.rb b/spec/fixtures/child.rb new file mode 100644 index 00000000..15b9117f --- /dev/null +++ b/spec/fixtures/child.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +# All subprocess behavior is Ruby-only; no shell utilities or Rails required. +require "json" +$stdout.sync = $stderr.sync = true + +mode = ARGV.shift +case mode +when "streams" + $stdout.puts "stdout message" + warn "stderr message" +when "env" + puts JSON.generate(ENV.to_h.slice(*ARGV).merge("cwd" => Dir.pwd, "stdin_eof" => $stdin.read.empty?)) +when "exit" + puts "before exit" + exit Integer(ARGV.fetch(0)) +when "partial" + print "partial" + sleep 0.15 + print " line\nlast" +when "burst" + count = Integer(ARGV.fetch(0, "20000")) + count.times { |index| puts "line #{index}" } +when "long" + print "x" * ((16_384 * 20) + 1) +when "ticker", "ignore_term" + Signal.trap("TERM", "IGNORE") if mode == "ignore_term" + File.write(ARGV[0], Process.pid.to_s) if ARGV[0] + puts "ready #{Process.pid}" + loop do + puts "tick #{Process.pid}" + sleep 0.03 + end +when "tree", "orphan" + file = ARGV.fetch(0) + child = fork do + Signal.trap("TERM", "IGNORE") + grandchild = fork do + Signal.trap("TERM", "IGNORE") + loop { sleep 1 } + end + File.write(file, [Process.ppid, Process.pid, grandchild].join("\n")) + loop { sleep 1 } + end + sleep 0.01 until File.exist?(file) + puts "tree ready #{child}" + exit 0 if mode == "orphan" + + loop { sleep 1 } +when "crash_tui" + require "foruiman" + require "foruiman/tui/application" + terminal = Foruiman::TUI::Terminal.new + engine = Foruiman::Engine.new(term_timeout: 0.1) + engine.register("tree", ARGV.fetch(0)) + renderer = Foruiman::TUI::Renderer.new + renderer.define_singleton_method(:render) do |*args, **options| + raise "injected renderer failure" if File.exist?(ARGV.fetch(1)) + + super(*args, **options) + end + begin + Foruiman::TUI::Application.new(engine, terminal: terminal, renderer: renderer).run + rescue RuntimeError + exit 17 + end +end diff --git a/spec/foreman/export/base_spec.rb b/spec/foreman/export/base_spec.rb deleted file mode 100644 index 3add2964..00000000 --- a/spec/foreman/export/base_spec.rb +++ /dev/null @@ -1,19 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export" - -describe "Foreman::Export::Base", :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") } - let(:location) { "/tmp/init" } - let(:engine) { Foreman::Engine.new().load_procfile(procfile) } - let(:subject) { Foreman::Export::Base.new(location, engine) } - - it "has a say method for displaying info" do - expect(subject).to receive(:puts).with("[foreman export] foo") - subject.send(:say, "foo") - end - - it "raises errors as a Foreman::Export::Exception" do - expect { subject.send(:error, "foo") }.to raise_error(Foreman::Export::Exception, "foo") - end -end diff --git a/spec/foreman/export/bluepill_spec.rb b/spec/foreman/export/bluepill_spec.rb deleted file mode 100644 index 284226ad..00000000 --- a/spec/foreman/export/bluepill_spec.rb +++ /dev/null @@ -1,37 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/bluepill" -require "tmpdir" - -describe Foreman::Export::Bluepill, :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:bluepill) { Foreman::Export::Bluepill.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("bluepill") } - before(:each) { allow(bluepill).to receive(:say) } - - it "exports to the filesystem" do - bluepill.export - expect(normalize_space(File.read("/tmp/init/app.pill"))).to eq(normalize_space(example_export_file("bluepill/app.pill"))) - end - - it "cleans up if exporting into an existing dir" do - expect(FileUtils).to receive(:rm).with("/tmp/init/app.pill") - - bluepill.export - bluepill.export - end - - context "with a process formation" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - bluepill.export - expect(normalize_space(File.read("/tmp/init/app.pill"))).to eq(normalize_space(example_export_file("bluepill/app-concurrency.pill"))) - end - end - -end diff --git a/spec/foreman/export/daemon_spec.rb b/spec/foreman/export/daemon_spec.rb deleted file mode 100644 index 112784a0..00000000 --- a/spec/foreman/export/daemon_spec.rb +++ /dev/null @@ -1,97 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/daemon" -require "tmpdir" - -describe Foreman::Export::Daemon, :fakefs do - let(:procfile) { write_procfile("/tmp/app/Procfile") } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:daemon) { Foreman::Export::Daemon.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("daemon") } - before(:each) { allow(daemon).to receive(:say) } - - it "exports to the filesystem" do - daemon.export - - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("daemon/app.conf")) - expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("daemon/app-alpha.conf")) - expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("daemon/app-alpha-1.conf")) - expect(File.read("/tmp/init/app-bravo.conf")).to eq(example_export_file("daemon/app-bravo.conf")) - expect(File.read("/tmp/init/app-bravo-1.conf")).to eq(example_export_file("daemon/app-bravo-1.conf")) - end - - it "cleans up if exporting into an existing dir" do - expect(FileUtils).to receive(:rm).with("/tmp/init/app.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha-1.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo-1.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar-1.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar-1.conf") - - daemon.export - daemon.export - end - - it "does not delete exported files for similarly named applications" do - FileUtils.mkdir_p "/tmp/init" - - ["app2", "app2-alpha", "app2-alpha-1"].each do |name| - path = "/tmp/init/#{name}.conf" - FileUtils.touch(path) - expect(FileUtils).to_not receive(:rm).with(path) - end - - daemon.export - end - - context "with a formation" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - daemon.export - - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("daemon/app.conf")) - expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("daemon/app-alpha.conf")) - expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("daemon/app-alpha-1.conf")) - expect(File.read("/tmp/init/app-alpha-2.conf")).to eq(example_export_file("daemon/app-alpha-2.conf")) - expect(File.exist?("/tmp/init/app-bravo-1.conf")).to eq(false) - end - end - - context "with alternate templates" do - let(:template) { "/tmp/alternate" } - let(:options) { { :app => "app", :template => template } } - - before do - FileUtils.mkdir_p template - File.open("#{template}/master.conf.erb", "w") { |f| f.puts "alternate_template" } - end - - it "can export with alternate template files" do - daemon.export - expect(File.read("/tmp/init/app.conf")).to eq("alternate_template\n") - end - end - - context "with alternate templates from home dir" do - - before do - FileUtils.mkdir_p File.expand_path("~/.foreman/templates/daemon") - File.open(File.expand_path("~/.foreman/templates/daemon/master.conf.erb"), "w") do |file| - file.puts "default_alternate_template" - end - end - - it "can export with alternate template files" do - daemon.export - expect(File.read("/tmp/init/app.conf")).to eq("default_alternate_template\n") - end - end - -end diff --git a/spec/foreman/export/inittab_spec.rb b/spec/foreman/export/inittab_spec.rb deleted file mode 100644 index c097550e..00000000 --- a/spec/foreman/export/inittab_spec.rb +++ /dev/null @@ -1,40 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/inittab" -require "tmpdir" - -describe Foreman::Export::Inittab, :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") } - let(:location) { "/tmp/inittab" } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:inittab) { Foreman::Export::Inittab.new(location, engine, options) } - - before(:each) { load_export_templates_into_fakefs("inittab") } - before(:each) { allow(inittab).to receive(:say) } - - it "exports to the filesystem" do - inittab.export - expect(File.read("/tmp/inittab")).to eq(example_export_file("inittab/inittab.default")) - end - - context "to stdout" do - let(:location) { "-" } - - it "exports to stdout" do - expect(inittab).to receive(:puts).with(example_export_file("inittab/inittab.default")) - inittab.export - end - end - - context "with concurrency" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - inittab.export - expect(File.read("/tmp/inittab")).to eq(example_export_file("inittab/inittab.concurrency")) - end - end - -end diff --git a/spec/foreman/export/launchd_spec.rb b/spec/foreman/export/launchd_spec.rb deleted file mode 100644 index ee6c6638..00000000 --- a/spec/foreman/export/launchd_spec.rb +++ /dev/null @@ -1,31 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/launchd" -require "tmpdir" - -describe Foreman::Export::Launchd, :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") } - let(:options) { Hash.new } - let(:engine) { Foreman::Engine.new().load_procfile(procfile) } - let(:launchd) { Foreman::Export::Launchd.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("launchd") } - before(:each) { allow(launchd).to receive(:say) } - - it "exports to the filesystem" do - launchd.export - expect(File.read("/tmp/init/app-alpha-1.plist")).to eq(example_export_file("launchd/launchd-a.default")) - expect(File.read("/tmp/init/app-bravo-1.plist")).to eq(example_export_file("launchd/launchd-b.default")) - end - - context "with multiple command arguments" do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile", "charlie") } - - it "splits each command argument" do - launchd.export - expect(File.read("/tmp/init/app-alpha-1.plist")).to eq(example_export_file("launchd/launchd-c.default")) - end - - end - -end diff --git a/spec/foreman/export/runit_spec.rb b/spec/foreman/export/runit_spec.rb deleted file mode 100644 index 5fa12fa6..00000000 --- a/spec/foreman/export/runit_spec.rb +++ /dev/null @@ -1,36 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/runit" -require "tmpdir" - -describe Foreman::Export::Runit, :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile", 'bar=baz') } - let(:engine) { Foreman::Engine.new(:formation => "alpha=2,bravo=1").load_procfile(procfile) } - let(:options) { Hash.new } - let(:runit) { Foreman::Export::Runit.new('/tmp/init', engine, options) } - - before(:each) { load_export_templates_into_fakefs("runit") } - before(:each) { allow(runit).to receive(:say) } - before(:each) { allow(FakeFS::FileUtils).to receive(:chmod) } - - it "exports to the filesystem" do - engine.env["BAR"] = "baz" - runit.export - - expect(File.read("/tmp/init/app-alpha-1/run")).to eq(example_export_file('runit/app-alpha-1/run')) - expect(File.read("/tmp/init/app-alpha-1/log/run")).to eq(example_export_file('runit/app-alpha-1/log/run')) - expect(File.read("/tmp/init/app-alpha-1/env/PORT")).to eq("5000\n") - expect(File.read("/tmp/init/app-alpha-1/env/BAR")).to eq("baz\n") - expect(File.read("/tmp/init/app-alpha-2/run")).to eq(example_export_file('runit/app-alpha-2/run')) - expect(File.read("/tmp/init/app-alpha-2/log/run")).to eq(example_export_file('runit/app-alpha-2/log/run')) - expect(File.read("/tmp/init/app-alpha-2/env/PORT")).to eq("5001\n") - expect(File.read("/tmp/init/app-alpha-2/env/BAR")).to eq("baz\n") - expect(File.read("/tmp/init/app-bravo-1/run")).to eq(example_export_file('runit/app-bravo-1/run')) - expect(File.read("/tmp/init/app-bravo-1/log/run")).to eq(example_export_file('runit/app-bravo-1/log/run')) - expect(File.read("/tmp/init/app-bravo-1/env/PORT")).to eq("5100\n") - end - - it "creates a full path to the export directory" do - expect { runit.export }.to_not raise_error - end -end diff --git a/spec/foreman/export/supervisord_spec.rb b/spec/foreman/export/supervisord_spec.rb deleted file mode 100644 index 33355080..00000000 --- a/spec/foreman/export/supervisord_spec.rb +++ /dev/null @@ -1,38 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/supervisord" -require "tmpdir" - -describe Foreman::Export::Supervisord, :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:supervisord) { Foreman::Export::Supervisord.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("supervisord") } - before(:each) { allow(supervisord).to receive(:say) } - - it "exports to the filesystem" do - write_env(".env", "FOO"=>"bar", "URL"=>"http://example.com/api?foo=bar&baz=1") - supervisord.engine.load_env('.env') - supervisord.export - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("supervisord/app-alpha-1.conf")) - end - - it "cleans up if exporting into an existing dir" do - expect(FileUtils).to receive(:rm).with("/tmp/init/app.conf") - supervisord.export - supervisord.export - end - - context "with concurrency" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - supervisord.export - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("supervisord/app-alpha-2.conf")) - end - end - -end diff --git a/spec/foreman/export/systemd_spec.rb b/spec/foreman/export/systemd_spec.rb deleted file mode 100644 index b8ee190e..00000000 --- a/spec/foreman/export/systemd_spec.rb +++ /dev/null @@ -1,155 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/systemd" -require "tmpdir" - -describe Foreman::Export::Systemd, :fakefs, :aggregate_failures do - let(:procfile) { write_procfile("/tmp/app/Procfile") } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:systemd) { Foreman::Export::Systemd.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("systemd") } - before(:each) { allow(systemd).to receive(:say) } - - it "exports to the filesystem" do - systemd.export - - expect(File.read("/tmp/init/app.target")).to eq(example_export_file("systemd/app.target")) - expect(File.read("/tmp/init/app-alpha.1.service")).to eq(example_export_file("systemd/app-alpha.1.service")) - expect(File.read("/tmp/init/app-bravo.1.service")).to eq(example_export_file("systemd/app-bravo.1.service")) - end - - context "when systemd export was run using the previous version of systemd export" do - before do - write_file("/tmp/init/app.target") - - write_file("/tmp/init/app-alpha@.service") - write_file("/tmp/init/app-alpha.target") - write_file("/tmp/init/app-alpha.target.wants/app-alpha@5000.service") - - write_file("/tmp/init/app-bravo.target") - write_file("/tmp/init/app-bravo@.service") - write_file("/tmp/init/app-bravo.target.wants/app-bravo@5100.service") - - write_file("/tmp/init/app-foo_bar.target") - write_file("/tmp/init/app-foo_bar@.service") - write_file("/tmp/init/app-foo_bar.target.wants/app-foo_bar@5200.service") - - write_file("/tmp/init/app-foo-bar.target") - write_file("/tmp/init/app-foo-bar@.service") - write_file("/tmp/init/app-foo-bar.target.wants/app-foo-bar@5300.service") - end - - it "cleans up service files created by systemd export" do - expect(FileUtils).to receive(:rm).with("/tmp/init/app.target") - - expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha@.service") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha.target") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha.target.wants/app-alpha@5000.service") - expect(FileUtils).to receive(:rm_r).with("/tmp/init/app-alpha.target.wants") - - expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo.target") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo@.service") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo.target.wants/app-bravo@5100.service") - expect(FileUtils).to receive(:rm_r).with("/tmp/init/app-bravo.target.wants") - - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar.target") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar@.service") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar.target.wants/app-foo_bar@5200.service") - expect(FileUtils).to receive(:rm_r).with("/tmp/init/app-foo_bar.target.wants") - - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar.target") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar@.service") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar.target.wants/app-foo-bar@5300.service") - expect(FileUtils).to receive(:rm_r).with("/tmp/init/app-foo-bar.target.wants") - - systemd.export - end - end - - context "when systemd export was run using the current version of systemd export" do - before do - systemd.export - end - - it "cleans up service files created by systemd export" do - expect(FileUtils).to receive(:rm).with("/tmp/init/app.target") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha.1.service") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo.1.service") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar.1.service") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar.1.service") - - systemd.export - end - end - - it "includes environment variables" do - engine.env['KEY'] = 'some "value"' - systemd.export - expect(File.read("/tmp/init/app-alpha.1.service")).to match(/KEY=some "value"/) - end - - it "includes ExecStart line" do - engine.env['KEY'] = 'some "value"' - systemd.export - expect(File.read("/tmp/init/app-alpha.1.service")).to match(/^ExecStart=/) - end - - context "with a custom formation specified" do - let(:formation) { "alpha=2" } - - it "exports only those services that are specified in the formation" do - systemd.export - - expect(File.read("/tmp/init/app.target")).to include("Wants=app-alpha.1.service app-alpha.2.service\n") - expect(File.read("/tmp/init/app-alpha.1.service")).to eq(example_export_file("systemd/app-alpha.1.service")) - expect(File.read("/tmp/init/app-alpha.2.service")).to eq(example_export_file("systemd/app-alpha.2.service")) - expect(File.exist?("/tmp/init/app-bravo.1.service")).to be_falsey - end - end - - context "with alternate template directory specified" do - let(:template) { "/tmp/alternate" } - let(:options) { { :app => "app", :template => template } } - - before do - FileUtils.mkdir_p template - File.open("#{template}/master.target.erb", "w") { |f| f.puts "alternate_template" } - end - - it "uses template files found in the alternate directory" do - systemd.export - expect(File.read("/tmp/init/app.target")).to eq("alternate_template\n") - end - - context "with alternate templates in the user home directory" do - before do - FileUtils.mkdir_p File.expand_path("~/.foreman/templates/systemd") - File.open(File.expand_path("~/.foreman/templates/systemd/master.target.erb"), "w") do |file| - file.puts "home_dir_template" - end - end - - it "uses template files found in the alternate directory" do - systemd.export - expect(File.read("/tmp/init/app.target")).to eq("alternate_template\n") - end - end - end - - context "with alternate templates in the user home directory" do - before do - FileUtils.mkdir_p File.expand_path("~/.foreman/templates/systemd") - File.open(File.expand_path("~/.foreman/templates/systemd/master.target.erb"), "w") do |file| - file.puts "home_dir_template" - end - end - - it "uses template files found in the user home directory" do - systemd.export - expect(File.read("/tmp/init/app.target")).to eq("home_dir_template\n") - end - end -end diff --git a/spec/foreman/export/upstart_spec.rb b/spec/foreman/export/upstart_spec.rb deleted file mode 100644 index 5c734978..00000000 --- a/spec/foreman/export/upstart_spec.rb +++ /dev/null @@ -1,118 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/upstart" -require "tmpdir" - -describe Foreman::Export::Upstart, :fakefs do - let(:procfile) { write_procfile("/tmp/app/Procfile") } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:upstart) { Foreman::Export::Upstart.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("upstart") } - before(:each) { allow(upstart).to receive(:say) } - - it "exports to the filesystem" do - upstart.export - - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("upstart/app.conf")) - expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("upstart/app-alpha.conf")) - expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("upstart/app-alpha-1.conf")) - expect(File.read("/tmp/init/app-bravo.conf")).to eq(example_export_file("upstart/app-bravo.conf")) - expect(File.read("/tmp/init/app-bravo-1.conf")).to eq(example_export_file("upstart/app-bravo-1.conf")) - end - - it "cleans up if exporting into an existing dir" do - expect(FileUtils).to receive(:rm).with("/tmp/init/app.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-alpha-1.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-bravo-1.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo-bar-1.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar.conf") - expect(FileUtils).to receive(:rm).with("/tmp/init/app-foo_bar-1.conf") - - upstart.export - upstart.export - end - - it "does not delete exported files for similarly named applications" do - FileUtils.mkdir_p "/tmp/init" - - ["app2", "app2-alpha", "app2-alpha-1"].each do |name| - path = "/tmp/init/#{name}.conf" - FileUtils.touch(path) - expect(FileUtils).to_not receive(:rm).with(path) - end - - upstart.export - end - - it 'does not delete exported files for app which share name prefix' do - FileUtils.mkdir_p "/tmp/init" - - ["app-worker", "app-worker-worker", "app-worker-worker-1"].each do |name| - path = "/tmp/init/#{name}.conf" - FileUtils.touch(path) - expect(FileUtils).to_not receive(:rm).with(path) - end - - upstart.export - expect(File.exist?('/tmp/init/app.conf')).to be true - expect(File.exist?('/tmp/init/app-worker.conf')).to be true - end - - it "quotes and escapes environment variables" do - engine.env['KEY'] = 'd"\|d' - upstart.export - expect("foobarfoo").to include "bar" - expect(File.read("/tmp/init/app-alpha-1.conf")).to match(/KEY='d"\\\|d'/) - end - - context "with a formation" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - upstart.export - - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("upstart/app.conf")) - expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("upstart/app-alpha.conf")) - expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("upstart/app-alpha-1.conf")) - expect(File.read("/tmp/init/app-alpha-2.conf")).to eq(example_export_file("upstart/app-alpha-2.conf")) - expect(File.exist?("/tmp/init/app-bravo-1.conf")).to eq(false) - end - end - - context "with alternate templates" do - let(:template) { "/tmp/alternate" } - let(:options) { { :app => "app", :template => template } } - - before do - FileUtils.mkdir_p template - File.open("#{template}/master.conf.erb", "w") { |f| f.puts "alternate_template" } - end - - it "can export with alternate template files" do - upstart.export - expect(File.read("/tmp/init/app.conf")).to eq("alternate_template\n") - end - end - - context "with alternate templates from home dir" do - - before do - FileUtils.mkdir_p File.expand_path("~/.foreman/templates/upstart") - File.open(File.expand_path("~/.foreman/templates/upstart/master.conf.erb"), "w") do |file| - file.puts "default_alternate_template" - end - end - - it "can export with alternate template files" do - upstart.export - expect(File.read("/tmp/init/app.conf")).to eq("default_alternate_template\n") - end - end - -end diff --git a/spec/foreman/export_spec.rb b/spec/foreman/export_spec.rb deleted file mode 100644 index f98d40e7..00000000 --- a/spec/foreman/export_spec.rb +++ /dev/null @@ -1,24 +0,0 @@ -require "spec_helper" -require "foreman/export" - -describe "Foreman::Export" do - subject { Foreman::Export } - - describe "with a formatter that doesn't declare the appropriate class" do - it "prints an error" do - expect(subject).to receive(:require).with("foreman/export/invalidformatter") - mock_export_error("Unknown export format: invalidformatter (no class Foreman::Export::Invalidformatter).") do - subject.formatter("invalidformatter") - end - end - end - - describe "with an invalid formatter" do - - it "prints an error" do - mock_export_error("Unknown export format: invalidformatter (unable to load file 'foreman/export/invalidformatter').") do - subject.formatter("invalidformatter") - end - end - end -end diff --git a/spec/foreman/helpers_spec.rb b/spec/foreman/helpers_spec.rb deleted file mode 100644 index 72d64f27..00000000 --- a/spec/foreman/helpers_spec.rb +++ /dev/null @@ -1,26 +0,0 @@ -require "spec_helper" -require "foreman/helpers" - -describe "Foreman::Helpers" do - before do - module Foo - class Bar; end - end - end - - after do - Object.send(:remove_const, :Foo) - end - - subject { o = Object.new; o.extend(Foreman::Helpers); o } - - it "should classify words" do - expect(subject.classify("foo")).to eq("Foo") - expect(subject.classify("foo-bar")).to eq("FooBar") - end - - it "should constantize words" do - expect(subject.constantize("Object")).to eq(Object) - expect(subject.constantize("Foo::Bar")).to eq(Foo::Bar) - end -end diff --git a/spec/foreman_spec.rb b/spec/foreman_spec.rb deleted file mode 100644 index bb349ceb..00000000 --- a/spec/foreman_spec.rb +++ /dev/null @@ -1,16 +0,0 @@ -require "spec_helper" -require "foreman" - -describe Foreman do - - describe "VERSION" do - subject { Foreman::VERSION } - it { is_expected.to be_a String } - end - - describe "runner" do - it "should exist" do - expect(File.exist?(Foreman.runner)).to eq(true) - end - end -end diff --git a/spec/foruiman/cli_spec.rb b/spec/foruiman/cli_spec.rb new file mode 100644 index 00000000..c6953092 --- /dev/null +++ b/spec/foruiman/cli_spec.rb @@ -0,0 +1,87 @@ +# frozen_string_literal: true + +RSpec.describe "CLI" do + it "prints its version and limits commands to the MVP" do + output, error, status = cli("--version") + expect(output).to eq("#{Foruiman::VERSION}\n") + expect(error).to be_empty + expect(status).to be_success + %w[export run tree].each do |command| + _output, _error, status = cli(command) + expect(status).not_to be_success + end + end + + it "checks without spawning and rejects malformed entries atomically" do + marker = File.join(@directory, "spawned") + write_file("Procfile", "web: #{fixture('ticker', marker)}\nbroken\n") + _output, error, status = cli("start", "--no-tui") + expect(status.exitstatus).to eq(1) + expect(error).to include("Procfile:2:") + expect(File).not_to exist(marker) + write_file("Procfile", "web: #{fixture('ticker', marker)}\n") + output, _error, status = cli("check") + expect(status).to be_success + expect(output).to include("web") + expect(File).not_to exist(marker) + end + + ["0", "-1", "1.5", "nope"].each do |capacity| + it "rejects log capacity #{capacity}" do + write_file("Procfile", "web: #{fixture('streams')}\n") + _output, error, status = cli("start", "--log-lines", capacity) + expect(status.exitstatus).to eq(1) + expect(error).to include("log-lines") + end + end + + %w[0 -1 65536 12.3 nope].each do |port| + it "rejects port #{port}" do + write_file("Procfile", "web: #{fixture('streams')}\n") + _output, error, status = cli("check", "-p", port) + expect(status.exitstatus).to eq(1) + expect(error).to include("port") + end + end + + it "validates the last allocation and rejects unknown options" do + write_file("Procfile", "web: echo web\nworker: echo worker\n") + _output, error, status = cli("start", "-p", "65500") + expect(status.exitstatus).to eq(1) + expect(error).to include("65600") + _output, error, status = cli("start", "--formation", "web=2") + expect(status.exitstatus).to eq(1) + expect(error).to include("Unknown switches") + end + + it "layers environments with generated variables last and defaults to invocation cwd" do + write_file("nested/Procfile", "web: #{fixture('env', 'FOO', 'BAR', 'PORT', 'PS')}\n") + write_file(".env", "FOO=dotenv\nBAR=dotenv\nPORT=9000\nPS=wrong\n") + write_file("custom.env", "FOO=explicit\n") + output, error, status = cli("-f", "nested/Procfile", "-e", "custom.env", env: { "FOO" => "inherited" }) + expect(status).to be_success + expect(error).to be_empty + expect(output).to include('"FOO":"explicit"', '"BAR":"dotenv"', '"PORT":"5000"', '"PS":"web.1"') + expect(output).to include(%("cwd":"#{@directory}")) + expect(output).not_to include("\e[") + end + + it "supports a custom root and a selected process with its original port" do + write_file("app/Procfile", "web: #{fixture('streams')}\nworker: #{fixture('env', 'PORT')}\n") + output, _error, status = cli("start", "worker", "-d", "app", "-p", "6000") + expect(status).to be_success + expect(output).to include('"PORT":"6100"', %("cwd":"#{@directory}/app")) + expect(output).not_to include("stdout message") + _output, error, status = cli("start", "unknown", "-d", "app") + expect(status.exitstatus).to eq(1) + expect(error).to include("unknown process") + end + + it "does not load terminal libraries in plain mode" do + command = [RbConfig.ruby, "-I", File.expand_path("../../lib", __dir__), "-rforuiman/cli", "-e", + 'puts $LOADED_FEATURES.grep(/io\/console|tui\/|unicode\/display_width/)'] + output, _error, status = Open3.capture3(*command) + expect(status).to be_success + expect(output).to be_empty + end +end diff --git a/spec/foruiman/env_spec.rb b/spec/foruiman/env_spec.rb new file mode 100644 index 00000000..05bea9c3 --- /dev/null +++ b/spec/foruiman/env_spec.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +# Quoting cases retained from Foreman's engine_spec.rb environment examples. +RSpec.describe Foruiman::Env do + it "reads unquoted, single-quoted, double-quoted and escaped values" do + file = write_file("env", <<~'ENV') + FOO=bar + BAZ="qux" + FRED='barney' + OTHER="escaped\"quote" + URL="http://example.com/api?foo=bar&baz=1" + MULTI="bar\nbaz" + LITERAL='bar\nbaz' + EMPTY= + # comment + invalid assignment + ENV + expect(described_class.new(file).to_h).to eq( + "FOO" => "bar", "BAZ" => "qux", "FRED" => "barney", "OTHER" => 'escaped"quote', + "URL" => "http://example.com/api?foo=bar&baz=1", "MULTI" => "bar\nbaz", "LITERAL" => 'bar\nbaz', "EMPTY" => "" + ) + end + + it "layers inherited, .env, and explicit values without mutating ENV or its input" do + before = ENV.to_h + inherited = { "A" => "inherited", "B" => "inherited", "C" => "inherited" }.freeze + write_file(".env", "A=dotenv\nB=dotenv\n") + explicit = write_file("custom.env", "A=explicit\n") + result = described_class.load(root: @directory, file: explicit, inherited: inherited) + expect(result).to eq("A" => "explicit", "B" => "dotenv", "C" => "inherited") + expect(ENV.to_h).to eq(before) + expect(inherited["A"]).to eq("inherited") + end + + it "allows disabling .env while still loading the explicit file" do + write_file(".env", "A=default\n") + file = write_file("custom.env", "B=custom\n") + expect(described_class.load(root: @directory, file: file, dotenv: false, inherited: {})).to eq("B" => "custom") + end + + it "fails for a missing explicit file but allows absent .env" do + expect(described_class.load(root: @directory, inherited: {})).to eq({}) + expect { described_class.load(root: @directory, file: "#{@directory}/missing") }.to raise_error(Errno::ENOENT) + end +end diff --git a/spec/foruiman/log_store_spec.rb b/spec/foruiman/log_store_spec.rb new file mode 100644 index 00000000..48760982 --- /dev/null +++ b/spec/foruiman/log_store_spec.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +RSpec.describe Foruiman::LogStore do + def write(logs, name = "web", text = "line", **options) + logs.write(name: name, text: text, stream: :stdout, pid: 1, complete: true, **options) + end + + it "bounds both rings independently and shares frozen records" do + logs = described_class.new(%w[web worker], capacity: 3) + first = write(logs) + expect(logs["web"][0]).to equal(logs.all[0]) + expect(first).to be_frozen + expect(first.text).to be_frozen + 9.times { write(logs, "worker") } + expect(logs["web"].size).to eq(1) + expect(logs["worker"].size).to eq(3) + expect(logs.all.map(&:sequence)).to eq([8, 9, 10]) + expect(logs.all.index_of(1)).to be_nil + expect(logs.all.index_of(9)).to eq(1) + end + + it "updates partial identity in O(1) without resurrecting an aggregate eviction" do + logs = described_class.new(%w[web worker], capacity: 2) + partial = logs.write(name: "web", stream: :stdout, pid: 1, text: "par", complete: false) + 3.times { write(logs, "worker") } + complete = write(logs, "web", "partial", previous: partial) + expect(complete.sequence).to eq(partial.sequence) + expect(logs["web"][0]).to equal(complete) + expect(logs.all.map(&:sequence)).to eq([3, 4]) + expect(partial.text).to eq("par") + end + + [0, -1, 1.5, "10"].each do |capacity| + it "rejects capacity #{capacity.inspect}" do + expect { described_class.new(["web"], capacity: capacity) }.to raise_error(Foruiman::Error) + end + end +end diff --git a/spec/foruiman/output_spec.rb b/spec/foruiman/output_spec.rb new file mode 100644 index 00000000..169098cf --- /dev/null +++ b/spec/foruiman/output_spec.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true + +RSpec.describe Foruiman::Output do + let(:events) { [] } + let(:logs) { Foruiman::LogStore.new(["web"], capacity: 10) { |record| events << record } } + subject(:output) { described_class.new(logs, name: "web", stream: :stdout, pid: 123) } + + it "publishes partial lines live and completes the same record on newline and EOF" do + output.feed("par") + sequence = logs.all[0].sequence + expect(logs.all[0].complete).to be(false) + output.feed("tial\nlast") + expect(logs.all[0].sequence).to eq(sequence) + expect(logs.all[0].text).to eq("partial") + expect(logs.all[0].complete).to be(true) + output.feed("", eof: true) + expect(logs.all.map(&:text)).to eq(%w[partial last]) + expect(events.select(&:complete).map(&:text)).to eq(%w[partial last]) + end + + it "handles fragmented UTF-8 and ANSI, preserving only styles" do + bytes = "\e[31m赤😀\e[2J\e]52;c;clipboard\a\ePpayload\e\\\n" + bytes.bytes.each { |byte| output.feed(byte.chr) } + expect(logs.all.size).to eq(1) + expect(logs.all[0].text).to eq("\e[31m赤😀") + output.feed("next\n") + expect(logs.all[1].text).to eq("\e[31mnext") + end + + it "replaces invalid bytes and flushes an incomplete UTF-8 character on EOF" do + output.feed("a\xffb\xe3".b) + output.feed("", eof: true) + expect(logs.all[0].text).to eq("a�b�") + end + + it "bounds unterminated escape payloads and newline-free output" do + output.feed("\e]52;c;#{'x' * 100_000}") + output.feed("\a#{'界' * 30_000}") + output.feed("", eof: true) + expect(logs.all.size).to be <= 10 + expect(events.map { |record| record.text.bytesize }.max).to be <= described_class::MAX_BYTES + expect(events.all? { |record| record.text.valid_encoding? }).to be(true) + expect(events.select(&:complete).sum { |record| record.text.count("界") }).to eq(30_000) + end + + it "keeps styles bounded over repeated changes and resets at a reset sequence" do + output.feed("#{"\e[31m" * 1000}x\n\e[0mreset\nplain\n") + expect(logs.all.to_a.last.text).to eq("plain") + expect(logs.all.to_a[-2].text).to eq("\e[31m\e[0mreset") + end + it "does not invent a blank line when a newline follows the size boundary" do + output.feed("x" * described_class::MAX_BYTES) + output.feed("\n\nlast\n") + expect(events.select(&:complete).map(&:text)).to eq(["x" * described_class::MAX_BYTES, "", "last"]) + end + + it "suppresses UTF-8 C1 controls, including CSI and OSC introducers" do + output.feed("safe\u009b2J\u009d52;clipboard\n") + expect(logs.all[0].text).not_to match(/[\u0080-\u009f\e]/) + end + + it "produces the same complete text under different byte fragmentation" do + source = "\e[38;2;10;20;30m界👩‍💻 combining é\n" * 15 + reference = [] + [1, 2, 3, 17, 1024].each do |chunk_size| + records = [] + store = Foruiman::LogStore.new(["web"], capacity: 3) { |record| records << record.text if record.complete } + stream = described_class.new(store, name: "web", stream: :stdout, pid: 1) + source.b.bytes.each_slice(chunk_size) { |bytes| stream.feed(bytes.pack("C*")) } + stream.feed("", eof: true) + reference = records if reference.empty? + expect(records).to eq(reference) + end + end +end diff --git a/spec/foruiman/process_spec.rb b/spec/foruiman/process_spec.rb new file mode 100644 index 00000000..df823399 --- /dev/null +++ b/spec/foruiman/process_spec.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +# Adapted execution/environment cases from Foreman's process_spec.rb. +RSpec.describe Foruiman::Process do + def capture(command, env: ENV.to_h, custom_env: {}) + process = described_class.new(command, env: env, cwd: @directory) + reader, writer = IO.pipe + error_reader, error_writer = IO.pipe + pid = process.run(output: writer, error: error_writer, env: custom_env) + writer.close + error_writer.close + result = [reader.read, error_reader.read] + Process.waitpid(pid) + result + ensure + [reader, writer, error_reader, error_writer].compact.each { |io| io.close unless io.closed? } + begin + Process.kill(:KILL, -pid) if pid + Process.waitpid(pid) if pid + rescue Errno::ESRCH, Errno::ECHILD + nil + end + end + + it "runs processes with distinct streams and UTF-8 output" do + stdout, stderr = capture(fixture("streams")) + expect(stdout).to eq("stdout message\n") + expect(stderr).to eq("stderr message\n") + expect(capture("printf '日本語\\n'").first).to eq("日本語\n") + end + + it "lets the shell expand variable names, braces, quoting and pipelines" do + command = %q(printf '%s\n' "$FOO" "${FOOBAR}" '$FOO' | /bin/cat) + stdout, = capture(command, env: ENV.to_h.merge("FOO" => "first", "FOOBAR" => "second"), + custom_env: { "FOO" => "per run" }) + expect(stdout).to eq("per run\nsecond\n$FOO\n") + end + + it "does not mutate the parent environment or working directory" do + before = ENV.to_h + cwd = Dir.pwd + stdout, = capture(fixture("env", "FOO"), custom_env: { "FOO" => "bar" }) + expect(stdout).to include('"FOO":"bar"', '"stdin_eof":true', @directory) + expect(ENV.to_h).to eq(before) + expect(Dir.pwd).to eq(cwd) + end +end diff --git a/spec/foruiman/procfile_spec.rb b/spec/foruiman/procfile_spec.rb new file mode 100644 index 00000000..06e9b9b0 --- /dev/null +++ b/spec/foruiman/procfile_spec.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true + +# Adapted from upstream spec/foreman/procfile_spec.rb; see docs/UPSTREAM.md. +RSpec.describe Foruiman::Procfile do + subject(:procfile) { described_class.new } + + it "loads a passed-in file and preserves ordered names" do + file = write_file("Procfile", "alpha: ./alpha\nbravo: ./bravo\nfoo-bar: ./foo-bar\nfoo_bar: ./foo_bar\n") + loaded = described_class.new(file) + expect(loaded.entries.map(&:first)).to eq(%w[alpha bravo foo-bar foo_bar]) + expect(loaded["alpha"]).to eq("./alpha") + expect(loaded["unicorn"]).to be_nil + procfile.load(file) + expect(procfile["bravo"]).to eq("./bravo") + end + + it "can append, replace, delete, and serialize entries" do + procfile["foo"] = "./foo" + procfile["bar"] = "./bar" + expect(procfile.to_s).to eq("foo: ./foo\nbar: ./bar") + procfile["foo"] = "./new" + expect(procfile.entries.map(&:first)).to eq(%w[bar foo]) + filename = File.join(@directory, "Procfile") + procfile.save(filename) + expect(File.read(filename)).to eq("bar: ./bar\nfoo: ./new\n") + procfile.delete("bar") + expect(procfile["bar"]).to be_nil + end + + it "ignores blank lines and comments and supports CRLF" do + file = write_file("Procfile", "# comment\r\n # comment\r\n\r\nweb: echo hi\r\n") + expect(described_class.new(file)["web"]).to eq("echo hi") + end + + it "preserves internal and trailing command whitespace" do + file = write_file("Procfile", "web:\t printf 'a b' && echo done \n") + expect(described_class.new(file)["web"]).to eq("printf 'a b' && echo done ") + end + + it "rejects empty files" do + file = write_file("Procfile", "\n# only a comment\n") + expect { described_class.new(file) }.to raise_error(described_class::EmptyFileError, /no processes/) + end + + ["web echo hi", "bad.name: echo hi", "web: ", "all: echo hi", "web: echo\0"].each do |line| + it "rejects #{line.inspect} with a line number" do + file = write_file("Procfile", "# line 1\n#{line}\n") + expect { described_class.new(file) }.to raise_error(described_class::ParseError, /Procfile:2:/) + end + end + + it "rejects duplicates before replacing any previously loaded entries" do + procfile["existing"] = "echo old" + file = write_file("Procfile", "web: echo first\nweb: echo second\n") + expect { procfile.load(file) }.to raise_error(described_class::ParseError, /:2: duplicate 'web'.*line 1/) + expect(procfile["existing"]).to eq("echo old") + end +end diff --git a/spec/foruiman/tui_spec.rb b/spec/foruiman/tui_spec.rb new file mode 100644 index 00000000..fd7695d9 --- /dev/null +++ b/spec/foruiman/tui_spec.rb @@ -0,0 +1,317 @@ +# frozen_string_literal: true + +require "foruiman/tui/application" +require "foruiman/diagnostics" +require "stringio" + +RSpec.describe Foruiman::TUI::Viewport do + let(:logs) { Foruiman::LogStore.new(["web"], capacity: 5) } + let(:buffer) { logs["web"] } + subject(:viewport) { described_class.new } + + def append(text) + logs.write(name: "web", stream: :stdout, pid: 1, text: text, complete: true) + end + + before { 5.times { |index| append(index.to_s) } } + + it "follows new output until scrolled and anchors to identity across eviction" do + expect(viewport.rows(buffer, 2).map(&:text)).to eq(%w[3 4]) + viewport.scroll(-1, buffer, 2) + anchor = viewport.anchor + append("5") + expect(viewport.following).to be(false) + expect(viewport.anchor).to eq(anchor) + expect(viewport.rows(buffer, 2).map(&:text)).to eq(%w[2 3]) + 3.times { |index| append((index + 6).to_s) } + expect(viewport.rows(buffer, 2).map(&:text)).to eq(%w[4 5]) + end + + it "clamps on resize and resumes following with End" do + viewport.scroll(0, buffer, 2) + expect(viewport.rows(buffer, 4).map(&:text)).to eq(%w[1 2 3 4]) + viewport.home(buffer) + expect(viewport.rows(buffer, 2).map(&:text)).to eq(%w[0 1]) + viewport.follow + expect(viewport.rows(buffer, 2).map(&:text)).to eq(%w[3 4]) + end +end + +RSpec.describe Foruiman::TUI::State do + it "preserves ordered tabs and independent follow/scroll state" do + state = described_class.new(%w[web worker]) + expect(state.tabs).to eq(%w[web worker all]) + expect(state.name).to eq("all") + state.select(0) + state.viewport.home(Foruiman::Ring.new(3)) + state.move(1) + expect(state.viewport.following).to be(true) + state.move(-1) + expect(state.viewport.following).to be(false) + state.move(-1) + expect(state.name).to eq("all") + end +end + +RSpec.describe Foruiman::TUI::Keyboard do + it "decodes fragmented sequences, numbers and shortcuts" do + keyboard = described_class.new + expect(keyboard.feed("\e[", now: 0)).to eq([]) + expect(keyboard.feed("A\t1rR0q", now: 0.01)).to eq([:up, :next, 1, :restart, :restart_all, 0, :quit]) + expect(keyboard.feed("\e[5~\e[6~\e[Z\x03")).to eq(%i[page_up page_down previous quit]) + end + + it "expires standalone Escape and ignores unknown escapes atomically" do + keyboard = described_class.new + expect(keyboard.feed("\e", now: 1)).to eq([]) + expect(keyboard.feed("", now: 1.2)).to eq([:escape]) + expect(keyboard.feed("\e[99Rq")).to eq([:quit]) + expect(keyboard.feed("\e[99", now: 2)).to eq([]) + expect(keyboard.feed("Rq", now: 2.01)).to eq([:quit]) + end +end + +RSpec.describe Foruiman::TUI::Renderer do + it "measures Unicode graphemes, wide characters, combining marks, and styles" do + expect(described_class.width("\e[31m界é👩‍💻\e[0m")).to eq(5) + text = described_class.truncate("\e[31m界é👩‍💻 tail", 3) + expect(text).to eq("\e[31m界é\e[0m") + expect(described_class.truncate("界", 1)).to eq("\e[0m") + end + + it "keeps selected tabs visible and renders statuses, PID, help and tiny terminals" do + names = Array.new(20) { |index| "process_#{index}" } + engine = build_engine(names.to_h { |name| [name, fixture("exit", "0")] }) + engine.select("process_19") + engine.start_all + state = Foruiman::TUI::State.new(names) + state.select(19) + renderer = described_class.new + frame = renderer.render(state, engine, rows: 10, columns: 45) + expect(frame).to include("process_19", "PID #{engine.state('process_19').pid}") + expect(frame.split("\r\n").size).to eq(10) + state.help = true + expect(renderer.render(state, engine, rows: 15, columns: 100)).to include("Restart selected") + expect(renderer.render(state, engine, rows: 1, columns: 1)).to include("\e[H") + engine.shutdown + expect(renderer.render(state, engine, rows: 10, columns: 80)).to include("Stopping process groups") + end + + it "resets styles on every row and truncates without wrapping" do + engine = build_engine({ "web" => fixture("exit", "0") }) + engine.start_all + engine.logs.write(name: "web", stream: :stdout, pid: 1, text: "\e[31m#{'界' * 100}", complete: false) + state = Foruiman::TUI::State.new(["web"]) + frame = described_class.new.render(state, engine, rows: 8, columns: 40) + frame.delete_prefix("\e[H").split("\r\n").each do |line| + expect(line).to end_with("\e[0m") + expect(described_class.width(line.delete_prefix("\e[2K"))).to be <= 39 + end + end +end + +RSpec.describe Foruiman::TUI::Application do + it "restarts running and exited entries on all without losing retained logs" do + engine = build_engine({ "web" => fixture("ticker"), "job" => fixture("exit", "0") }) + engine.start_all + eventually(engine) { engine.state("job").status == :exited && engine.logs["web"].any? } + retained = engine.logs.all.map(&:sequence) + application = described_class.new(engine) + application.handle(:restart, 10) + eventually(engine) { engine.processes.all? { |entry| entry.generation == 2 } } + expect(application.state.feedback).to eq("Restarting all processes") + expect(engine.logs.all.map(&:sequence)).to include(*retained) + end + + it "stays open after children exit and processes restart, tab and quit input" do + engine = build_engine({ "web" => fixture("exit", "0") }) + terminal = double("terminal", size: [12, 80], draw: nil) + allow(terminal).to receive(:session).and_yield + phase = 0 + allow(terminal).to receive(:read) do + if phase.zero? && engine.finished? + phase = 1 + "1r" + elsif phase == 1 && engine.state("web").generation == 2 && engine.finished? + phase = 2 + "q" + else + :wait_readable + end + end + expect(Timeout.timeout(5) { described_class.new(engine, terminal: terminal).run }).to eq(0) + expect(phase).to eq(2) + expect(engine.state("web").generation).to eq(2) + end + + it "restores terminal and cleans up when drawing raises" do + engine = build_engine({ "web" => fixture("ticker") }) + terminal = double("terminal", size: [12, 80], read: :wait_readable) + restored = false + allow(terminal).to receive(:session) do |&block| + block.call + ensure + restored = true + end + allow(terminal).to receive(:draw).and_raise("drawing failed") + expect { described_class.new(engine, terminal: terminal).run }.to raise_error("drawing failed") + expect(restored).to be(true) + expect(alive?(engine.state("web").pid)).to be(false) + end +end + +RSpec.describe Foruiman::Diagnostics do + it "writes interactive errors to a private persistent temporary file" do + stderr = StringIO.new + diagnostics = described_class.new(interactive: true, stderr: stderr) + diagnostics.error(RuntimeError.new("debug detail")) + diagnostics.close + expect(stderr.string).to be_empty + expect(File.stat(diagnostics.path).mode & 0o777).to eq(0o600) + expect(File.read(diagnostics.path)).to include("debug detail") + ensure + File.unlink(diagnostics.path) if diagnostics&.path && File.exist?(diagnostics.path) + end + + it "writes plain-mode errors to stderr" do + stderr = StringIO.new + described_class.new(interactive: false, stderr: stderr).error(RuntimeError.new("plain detail")) + expect(stderr.string).to include("plain detail") + end +end + +RSpec.describe "Terminal theme and layout" do + def preview(names = %w[web worker assets jobs]) + states = names.each_with_index.map do |name, index| + Foruiman::Engine::State.new(name: name, pid: 42_000 + index, port: 5000 + (index * 100), + status: index == 3 ? :failed : :running, generation: 1) + end + logs = Foruiman::LogStore.new(names, capacity: 100) + 50.times do |index| + logs.write(name: names[index % names.size], stream: :stdout, pid: 1, + text: "line #{index} with \e[31mcolored output\e[0m and wide text 界", complete: true) + end + engine = double("engine", root: @directory, procfile_path: File.join(@directory, "Procfile"), + processes: states, process_names: names, + logs: logs, shutting_down?: false) + allow(engine).to receive(:state) { |name| states.find { |entry| entry.name == name } } + [Foruiman::TUI::State.new(names), engine] + end + + def plain_rows(frame) + frame.gsub(/\e\[[0-9;:]*[A-Za-z]/, "").split("\r\n", -1) + end + + it "uses theme-controlled ANSI colors and default backgrounds regardless of truecolor support" do + [{ "COLORTERM" => "truecolor" }, { "TERM" => "xterm-256color" }].each do |env| + theme = Foruiman::TUI::Theme.new(env: env) + expect(theme.paint("hello")).to include("\e[39m", "\e[49m", "hello") + expect(theme.paint("failed", :red)).to include("\e[31m") + expect(theme.paint("selected", selected: true)).to include("\e[39m\e[49m\e[7mselected") + state, engine = preview + frame = Foruiman::TUI::Renderer.new(theme: theme).render(state, engine, rows: 24, columns: 100) + expect(frame).not_to match(/\e\[(?:38|48)[;:]/) + end + end + + it "keeps a visible selection without colors and strips child colors for NO_COLOR" do + disabled = Foruiman::TUI::Theme.new(env: { "COLORTERM" => "truecolor", "NO_COLOR" => "1" }) + expect(disabled.paint("hello")).to eq("hello") + expect(disabled.paint("selected", selected: true)).to eq("\e[7mselected\e[0m") + expect(disabled.log("\e[31mred\e[0m plain")).to eq("red plain") + expect(Foruiman::TUI::Theme.new(env: { "TERM" => "dumb" }).enabled).to be(false) + end + + it "restores the theme after child resets while preserving explicit child backgrounds" do + theme = Foruiman::TUI::Theme.new(env: { "COLORTERM" => "truecolor" }) + output = theme.log("\e[41mchild\e[0mnormal\e[38;2;10;20;30m custom") + expect(output).to include("\e[41mchild", "\e[0m#{theme.base}normal", "\e[38;2;10;20;30m custom") + expect(output).to end_with(theme.reset) + end + + it "fits every row and retains a visible selected tab across narrow and wide layouts" do + state, engine = preview(%w[web worker assets jobs scheduler mailer notifications]) + renderer = Foruiman::TUI::Renderer.new(theme: Foruiman::TUI::Theme.new(env: { "COLORTERM" => "truecolor" })) + [[24, 10], [45, 12], [59, 13], [60, 14], [80, 24], [120, 30]].each do |columns, rows| + state.tabs.each_index do |selection| + state.select(selection) + frame = renderer.render(state, engine, rows: rows, columns: columns) + rendered = plain_rows(frame) + expect(rendered.size).to eq(rows) + expect(rendered.map { |row| Foruiman::TUI::Text.width(row) }.max).to be <= columns - 1 + tab_row = rendered[Foruiman::TUI::Renderer.expanded?(rows: rows, columns: columns) ? 2 : 1] + expect(tab_row).to include(state.name[0, 3]) + end + end + end + + it "uses the same viewport height for rendering and keyboard paging, including after resize" do + state, engine = preview + renderer = Foruiman::TUI::Renderer.new + [[120, 30], [45, 12], [80, 24]].each do |columns, rows| + frame = renderer.render(state, engine, rows: rows, columns: columns) + height = Foruiman::TUI::Renderer.log_height(rows: rows, columns: columns) + expect(plain_rows(frame).count { |line| line.include?("out │") }).to eq(height) + expect(state.viewport.rows(engine.logs.all, height).last.text).to include("line 49") + end + end + + it "shows failure details and highlights paused scroll position" do + state, engine = preview + status = instance_double(Process::Status, exitstatus: 7) + engine.state("jobs").exit_status = status + state.select(3) + state.viewport.home(engine.logs["jobs"]) + renderer = Foruiman::TUI::Renderer.new + rendered = plain_rows(renderer.render(state, engine, rows: 20, columns: 110)).join("\n") + expect(rendered).to include("failed", "PID 42003", "exit 7", "PAUSED", "f resume") + end + + it "treats terminal controls in project directory names as text, never screen commands" do + state, engine = preview + root = "/work/hello\e[2J\e]52;c;test\a" + allow(engine).to receive(:root).and_return(root) + allow(engine).to receive(:procfile_path).and_return(File.join(root, "Procfile")) + frame = Foruiman::TUI::Renderer.new.render(state, engine, rows: 24, columns: 100) + expect(frame).not_to include("\e[2J", "\e]52;") + expect(frame).to include("hello") + end + + it "prioritizes the active Procfile in the title across terminal sizes" do + state, engine = preview + allow(engine).to receive(:root).and_return("/work/atlas") + allow(engine).to receive(:procfile_path).and_return("/work/atlas/config/Procfile.dev") + renderer = Foruiman::TUI::Renderer.new + [24, 45, 60, 80, 120].each do |columns| + title = plain_rows(renderer.render(state, engine, rows: 24, columns: columns)).first + expect(title).to include("Procfile.dev") + expect(Foruiman::TUI::Text.width(title)).to be <= columns - 1 + end + title = plain_rows(renderer.render(state, engine, rows: 24, columns: 120)).first + expect(title).to include("/ atlas", "config/Procfile.dev") + allow(engine).to receive(:procfile_path).and_return("/work/shared/Procfile.dev") + title = plain_rows(renderer.render(state, engine, rows: 24, columns: 120)).first + expect(title).to include("../shared/Procfile.dev") + end + + it "sanitizes terminal controls in Procfile names and clips long Unicode paths" do + state, engine = preview + name = "#{'界' * 80}é\e[2J\e]52;c;test\a.dev" + allow(engine).to receive(:procfile_path).and_return(File.join(@directory, name)) + frame = Foruiman::TUI::Renderer.new.render(state, engine, rows: 24, columns: 80) + expect(frame).not_to include("\e[2J", "\e]52;") + title = plain_rows(frame).first + expect(title).to include("界", "…") + expect(Foruiman::TUI::Text.width(title)).to be <= 79 + end + + it "labels the restart shortcut for the current tab" do + state, engine = preview + renderer = Foruiman::TUI::Renderer.new + expect(plain_rows(renderer.render(state, engine, rows: 24, columns: 100)).last).to include("restart all") + state.select(0) + footer = plain_rows(renderer.render(state, engine, rows: 24, columns: 100)).last + expect(footer).to include("restart") + expect(footer).not_to include("restart all") + end +end diff --git a/spec/helper_spec.rb b/spec/helper_spec.rb deleted file mode 100644 index f04ff90c..00000000 --- a/spec/helper_spec.rb +++ /dev/null @@ -1,19 +0,0 @@ -require "spec_helper" - -describe "spec helpers" do - describe "#preserving_env" do - after { ENV.delete "FOO" } - - it "should remove added environment vars" do - old = ENV["FOO"] - preserving_env { ENV["FOO"] = "baz" } - expect(ENV["FOO"]).to eq(old) - end - - it "should reset modified environment vars" do - ENV["FOO"] = "bar" - preserving_env { ENV["FOO"] = "baz"} - expect(ENV["FOO"]).to eq("bar") - end - end -end diff --git a/spec/integration/plain_spec.rb b/spec/integration/plain_spec.rb new file mode 100644 index 00000000..772642ce --- /dev/null +++ b/spec/integration/plain_spec.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +RSpec.describe "Plain mode" do + it "waits for newline or EOF to print partial output" do + write_file("Procfile", "web: #{fixture('partial')}\n") + output, error, status = cli("start", "--no-tui") + expect(status).to be_success + expect(error).to be_empty + messages = output.lines.select { |line| line.include?("[stdout]") } + expect(messages.size).to eq(2) + expect(messages.first).to end_with("partial line\n") + expect(messages.last).to end_with("last\n") + end + + it "drains a complete burst while keeping retained records bounded" do + engine = build_engine({ "web" => fixture("burst", "25000") }, log_lines: 5) + completed = 0 + engine.on_event { |event| completed += 1 if event.record&.complete && event.record.stream == :stdout } + expect(engine.run).to eq(0) + expect(completed).to eq(25_000) + expect(engine.logs.all.size).to eq(5) + expect(engine.logs["web"].size).to eq(5) + end + + it "shuts down on SIGTERM with status 0 and no surviving child group" do + pidfile = File.join(@directory, "child.pid") + write_file("Procfile", "web: exec #{fixture('ticker', pidfile)}\n") + input, output, errors, waiter = Open3.popen3(RbConfig.ruby, "-I", File.expand_path("../../lib", __dir__), + File.expand_path("../../bin/foruiman", __dir__), + chdir: @directory) + input.close + eventually { File.exist?(pidfile) } + child = File.read(pidfile).to_i + Process.kill(:TERM, waiter.pid) + eventually { !waiter.alive? } + expect(waiter.value).to be_success + expect(alive?(child)).to be(false) + expect(output.read).not_to include("\e[") + expect(errors.read).to be_empty + ensure + if waiter&.alive? + Process.kill(:KILL, waiter.pid) + waiter.join + end + Process.kill(:KILL, -child) if child && alive?(child) + [input, output, errors].compact.each { |io| io.close unless io.closed? } + end +end diff --git a/spec/integration/supervisor_spec.rb b/spec/integration/supervisor_spec.rb new file mode 100644 index 00000000..25a2264e --- /dev/null +++ b/spec/integration/supervisor_spec.rb @@ -0,0 +1,130 @@ +# frozen_string_literal: true + +RSpec.describe Foruiman::Engine do + it "keeps peers alive when one process fails and returns failure after all finish" do + engine = build_engine({ "bad" => fixture("exit", "7"), "peer" => fixture("ticker") }) + engine.start_all + peer = engine.state("peer").pid + eventually(engine) { engine.state("bad").pgid.nil? } + expect(engine.state("bad").exit_status.exitstatus).to eq(7) + expect(alive?(peer)).to be(true) + expect(engine.finished?).to be(false) + expect(engine.exit_code).to eq(1) + engine.shutdown + eventually(engine) { engine.finished? } + expect(engine.exit_code).to eq(0) + expect(alive?(peer)).to be(false) + end + + it "returns 0 for success and 1 for failure, including shell command-not-found" do + [0, 9].each do |code| + engine = build_engine({ "web" => fixture("exit", code.to_s) }) + expect(engine.run).to eq(code.zero? ? 0 : 1) + end + expect(build_engine({ "missing" => "foruiman-command-that-does-not-exist" }).run).to eq(1) + end + + it "restarts asynchronously, drains old output, and preserves logs and peer PID" do + engine = build_engine({ "web" => fixture("ignore_term"), "peer" => fixture("ticker") }) + events = [] + engine.on_event { |event| events << event } + engine.start_all + eventually(engine) { engine.logs["web"].any? { |record| record.text.start_with?("ready") } } + old_pid = engine.state("web").pid + peer = engine.state("peer").pid + old_records = engine.logs["web"].map(&:sequence) + engine.restart("web") + expect(engine.state("web").status).to eq(:restarting) + engine.restart("web") + eventually(engine) { engine.state("web").generation == 2 } + expect(engine.state("web").pid).not_to eq(old_pid) + expect(alive?(old_pid)).to be(false) + expect(engine.state("peer").pid).to eq(peer) + expect(alive?(peer)).to be(true) + expect(engine.logs["web"].map(&:sequence)).to include(*old_records) + expect(events.count { |event| event.type == :restarting }).to eq(1) + expect(events.any? { |event| event.type == :killed }).to be(true) + started = events.index { |event| event.type == :started && event.name == "web" && event.pid != old_pid } + expect(events[(started + 1)..].none? { |event| event.record&.pid == old_pid }).to be(true) + end + + it "restarts an exited process and supports stopping independently" do + engine = build_engine({ "web" => fixture("exit", "0"), "peer" => fixture("ticker") }) + engine.start_all + eventually(engine) { engine.state("web").pgid.nil? } + engine.restart("web") + expect(engine.state("web").generation).to eq(2) + engine.stop("peer") + eventually(engine) { engine.state("peer").pgid.nil? } + expect(engine.state("peer").status).to eq(:stopped) + end + + %w[tree orphan].each do |mode| + it "cleans up #{mode} descendants even after the leader exits" do + pidfile = File.join(@directory, "pids") + engine = build_engine({ "web" => "exec #{fixture(mode, pidfile)}" }) + engine.start_all + eventually(engine) { File.exist?(pidfile) } + pids = File.read(pidfile).split.map(&:to_i) + expect(pids.size).to eq(3) + engine.shutdown if mode == "tree" + eventually(engine) { engine.finished? } + expect(pids.select { |pid| alive?(pid) }).to be_empty + end + end + + it "cancels pending restarts during shutdown and kills grandchildren" do + pidfile = File.join(@directory, "pids") + engine = build_engine({ "web" => "exec #{fixture('tree', pidfile)}" }) + engine.start_all + eventually(engine) { File.exist?(pidfile) } + pids = File.read(pidfile).split.map(&:to_i) + engine.restart("web") + engine.shutdown + eventually(engine) { engine.finished? } + expect(engine.state("web").generation).to eq(1) + expect(pids.select { |pid| alive?(pid) }).to be_empty + end + + it "does not reap unrelated children" do + unrelated = Process.spawn(RbConfig.ruby, "-e", "exit 23") + engine = build_engine({ "web" => fixture("exit", "0") }) + engine.run + _pid, status = Process.waitpid2(unrelated) + expect(status.exitstatus).to eq(23) + ensure + begin + Process.waitpid(unrelated) if unrelated + rescue Errno::ECHILD + nil + end + end + + it "restores pre-existing signal handlers even when an event consumer raises" do + previous = Signal.trap(:TERM, "IGNORE") + engine = build_engine({ "web" => fixture("ticker") }) + engine.on_event { raise "observer failed" } + expect { engine.run }.to raise_error("observer failed") + expect(alive?(engine.state("web").pid)).to be(false) + expect(Signal.trap(:TERM, "DEFAULT")).to eq("IGNORE") + ensure + Signal.trap(:TERM, previous) if previous + end + + it "retains bounded logs during bursts and continues to accept shutdown" do + engine = build_engine({ "burst" => fixture("burst", "50000"), "long" => fixture("long") }, log_lines: 8) + engine.start_all + longest = 0 + 10.times do + before = Process.clock_gettime(Process::CLOCK_MONOTONIC) + engine.tick(timeout: 0.01) + longest = [longest, Process.clock_gettime(Process::CLOCK_MONOTONIC) - before].max + end + engine.shutdown + eventually(engine) { engine.finished? } + expect(longest).to be < 0.5 + expect(engine.logs.all.size).to be <= 8 + expect(engine.logs["burst"].size).to be <= 8 + expect(engine.logs["long"].size).to be <= 8 + end +end diff --git a/spec/integration/terminal_spec.rb b/spec/integration/terminal_spec.rb new file mode 100644 index 00000000..16cf6430 --- /dev/null +++ b/spec/integration/terminal_spec.rb @@ -0,0 +1,209 @@ +# frozen_string_literal: true + +require "pty" +require "io/console" +require "foruiman/tui/terminal" + +RSpec.describe "PTY and signal integration" do + def with_terminal(*command) + master, slave = PTY.open + slave.winsize = [16, 90] + original = slave.console_mode + original_mode = IO.popen(["stty", "-g"], in: slave, &:read) + colors = { "NO_COLOR" => nil, "TERM" => "xterm-256color", "COLORTERM" => "truecolor" } + pid = Process.spawn(colors, *command, in: slave, out: slave, err: slave, chdir: @directory, pgroup: true) + output = +"" + yield master, slave, pid, output + eventually(timeout: 10) do + chunk = master.read_nonblock(65_536, exception: false) + output << chunk if chunk.is_a?(String) + !alive?(pid) && !chunk.is_a?(String) + rescue Errno::EIO + !alive?(pid) + end + _pid, status = Process.waitpid2(pid) + expect(IO.popen(["stty", "-g"], in: slave, &:read)).to eq(original_mode) + members = Dir.glob(File.join(@directory, "*.pids")).flat_map { |file| File.read(file).split.map(&:to_i) } + expect(members.select { |member| alive?(member) }).to be_empty + expect(output).to include(Foruiman::TUI::Terminal::LEAVE, "\e[39m", "\e[49m", "\e[36m", "\e[7m") + status + ensure + if pid + begin + Process.kill(:KILL, -pid) + rescue Errno::ESRCH + nil + end + begin + Process.waitpid(pid) + rescue Errno::ECHILD + nil + end + end + slave.console_mode = original if slave && !slave.closed? && original + master&.close + slave&.close + # Every fixture writes group members before announcing readiness. Tests must + # clean them even when an assertion above fails or the supervisor crashes. + Dir.glob(File.join(@directory, "*.pids")).each do |filename| + File.read(filename).split.map(&:to_i).each do |child| + Process.kill(:KILL, child) if alive?(child) + rescue Errno::ESRCH + nil + end + end + end + + def command(*args) + [RbConfig.ruby, "-I", File.expand_path("../../lib", __dir__), + File.expand_path("../../bin/foruiman", __dir__), *args] + end + + def read_until(master, output, text, timeout: 5) + eventually(timeout: timeout) do + bytes = master.read_nonblock(65_536, exception: false) + output << bytes if bytes.is_a?(String) + output.include?(text) + end + end + + it "accepts keyboard input and resizing, keeps exited logs open, and restores the terminal" do + write_file("Procfile", "web: #{fixture('partial')}\n") + status = with_terminal(*command) do |master, slave, pid, output| + read_until(master, output, "partial") + expect(output).to include("Procfile") + read_until(master, output, "exited with code 0") + expect(alive?(pid)).to be(true) + master.write("1g") + read_until(master, output, "PAUSED") + slave.winsize = [8, 38] + Process.kill(:WINCH, pid) + master.write("f?") + read_until(master, output, "close help") + master.write("?q") + end + expect(status).to be_success + end + + it "shows the selected Procfile from a custom working directory in the title" do + write_file("app/config/Procfile.dev", "web: #{fixture('partial')}\n") + status = with_terminal(*command("-d", "app", "-f", "config/Procfile.dev")) do |master, _slave, _pid, output| + read_until(master, output, "config/Procfile.dev") + expect(output).to include("/ app") + master.write("q") + end + expect(status).to be_success + end + + { "r on all" => "r", "R on all" => "R", "R on a process tab" => "1R" }.each do |label, keys| + it "restarts every process with #{label} and cleans both generations" do + pidfiles = %w[web worker].map { |name| File.join(@directory, "#{name}.pids") } + write_file("Procfile", pidfiles.map do |file| + "#{File.basename(file, '.pids')}: exec #{fixture('ticker', file)}\n" + end.join) + status = with_terminal(*command) do |master, _slave, _pid, output| + read_until(master, output, "ready") + eventually { pidfiles.all? { |file| File.exist?(file) && File.read(file).to_i.positive? } } + old_pids = pidfiles.map { |file| File.read(file).to_i } + write_file("history.pids", old_pids.join("\n")) + master.write(keys) + read_until(master, output, "Restarting all processes") + eventually do + bytes = master.read_nonblock(65_536, exception: false) + output << bytes if bytes.is_a?(String) + pidfiles.all? do |file| + current = File.read(file).to_i + current.positive? && !old_pids.include?(current) && alive?(current) + end + end + expect(old_pids.select { |pid| alive?(pid) }).to be_empty + master.write("q") + end + expect(status).to be_success + end + end + + %w[INT TERM].each do |signal| + it "cleans process groups and grandchildren after SIG#{signal}" do + pidfile = File.join(@directory, "tree.pids") + write_file("Procfile", "web: exec #{fixture('tree', pidfile)}\n") + members = [] + status = with_terminal(*command) do |master, _slave, pid, output| + read_until(master, output, "tree ready") + members = File.read(pidfile).split.map(&:to_i) + Process.kill(signal, pid) + read_until(master, output, "Stopping process groups") + end + expect(status).to be_success + expect(members.select { |member| alive?(member) }).to be_empty + end + end + + it "cleans grandchildren on normal quit during a pending restart" do + pidfile = File.join(@directory, "restart.pids") + write_file("Procfile", "web: exec #{fixture('tree', pidfile)}\n") + members = [] + status = with_terminal(*command) do |master, _slave, _pid, output| + read_until(master, output, "tree ready") + members = File.read(pidfile).split.map(&:to_i) + master.write("1r") + read_until(master, output, "Restarting web") + master.write("q") + end + expect(status).to be_success + expect(members.select { |member| alive?(member) }).to be_empty + end + + it "restores raw input and alternate screen after a renderer exception with grandchildren" do + pidfile = File.join(@directory, "exception.pids") + members = [] + status = with_terminal(RbConfig.ruby, "-I", File.expand_path("../../lib", __dir__), + File.expand_path("../fixtures/child.rb", __dir__), + "crash_tui", "exec #{fixture('tree', pidfile)}", pidfile) do |master, _slave, _pid, output| + read_until(master, output, Foruiman::TUI::Terminal::ENTER) + eventually { File.exist?(pidfile) } + members = File.read(pidfile).split.map(&:to_i) + end + expect(status.exitstatus).to eq(17) + expect(members.select { |member| alive?(member) }).to be_empty + end + + it "restores the exact input mode after an exception" do + master, slave = PTY.open + terminal = Foruiman::TUI::Terminal.new(input: slave, output: slave) + before = IO.popen(["stty", "-g"], in: slave, &:read) + expect { terminal.session { raise "boom" } }.to raise_error("boom") + after = IO.popen(["stty", "-g"], in: slave, &:read) + expect(after).to eq(before) + ensure + master&.close + slave&.close + end + + it "uses plain output when only stdout is a TTY" do + write_file("Procfile", "web: #{fixture('streams')}\n") + master, slave = PTY.open + pid = Process.spawn(*command, in: File::NULL, out: slave, err: slave, chdir: @directory) + Process.waitpid(pid) + output = master.read_nonblock(65_536) + expect(output).to include("stdout message") + expect(output).not_to include("\e[") + ensure + master&.close + slave&.close + end + it "uses plain output when only stdin is a TTY" do + write_file("Procfile", "web: #{fixture('streams')}\n") + master, slave = PTY.open + reader, writer = IO.pipe + pid = Process.spawn(*command, in: slave, out: writer, err: writer, chdir: @directory) + writer.close + output = reader.read + _pid, status = Process.waitpid2(pid) + expect(status).to be_success + expect(output).to include("stdout message") + expect(output).not_to include("\e[") + ensure + [master, slave, reader, writer].compact.each { |io| io.close unless io.closed? } + end +end diff --git a/spec/resources/.env b/spec/resources/.env deleted file mode 100644 index c075a74b..00000000 --- a/spec/resources/.env +++ /dev/null @@ -1 +0,0 @@ -FOO=bar diff --git a/spec/resources/Procfile b/spec/resources/Procfile deleted file mode 100644 index 8c7a3243..00000000 --- a/spec/resources/Procfile +++ /dev/null @@ -1,5 +0,0 @@ -echo: bin/echo echoing -env: bin/env FOO -test: bin/test -utf8: bin/utf8 -ps: bin/echo PS env var is $PS diff --git a/spec/resources/Procfile.bad b/spec/resources/Procfile.bad deleted file mode 100644 index 4dde2b14..00000000 --- a/spec/resources/Procfile.bad +++ /dev/null @@ -1,2 +0,0 @@ -good: sleep 1 -bad: false diff --git a/spec/resources/bin/echo b/spec/resources/bin/echo deleted file mode 100755 index 94704cea..00000000 --- a/spec/resources/bin/echo +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -echo $* diff --git a/spec/resources/bin/env b/spec/resources/bin/env deleted file mode 100755 index 3287f088..00000000 --- a/spec/resources/bin/env +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/bash -echo ${!1} diff --git a/spec/resources/bin/test b/spec/resources/bin/test deleted file mode 100755 index 1b3f303e..00000000 --- a/spec/resources/bin/test +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -echo "testing" diff --git a/spec/resources/bin/utf8 b/spec/resources/bin/utf8 deleted file mode 100755 index 18e158c9..00000000 --- a/spec/resources/bin/utf8 +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env ruby -puts "\xff\x03" diff --git a/spec/resources/export/bluepill/app-concurrency.pill b/spec/resources/export/bluepill/app-concurrency.pill deleted file mode 100644 index a6d88ea1..00000000 --- a/spec/resources/export/bluepill/app-concurrency.pill +++ /dev/null @@ -1,49 +0,0 @@ -Bluepill.application("app", :foreground => false, :log_file => "/var/log/bluepill.log") do |app| - - app.uid = "app" - app.gid = "app" - - - - - app.process("alpha-1") do |process| - process.start_command = %Q{./alpha} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5000"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-alpha-1.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "app-alpha" - end - - - app.process("alpha-2") do |process| - process.start_command = %Q{./alpha} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5001"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-alpha-2.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "app-alpha" - end - - - - -end diff --git a/spec/resources/export/bluepill/app.pill b/spec/resources/export/bluepill/app.pill deleted file mode 100644 index e5d91807..00000000 --- a/spec/resources/export/bluepill/app.pill +++ /dev/null @@ -1,81 +0,0 @@ -Bluepill.application("app", :foreground => false, :log_file => "/var/log/bluepill.log") do |app| - - app.uid = "app" - app.gid = "app" - - - - - app.process("alpha-1") do |process| - process.start_command = %Q{./alpha} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5000"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-alpha-1.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "app-alpha" - end - - app.process("bravo-1") do |process| - process.start_command = %Q{./bravo} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5100"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-bravo-1.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "app-bravo" - end - - app.process("foo_bar-1") do |process| - process.start_command = %Q{./foo_bar} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5200"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-foo_bar-1.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "app-foo_bar" - end - - app.process("foo-bar-1") do |process| - process.start_command = %Q{./foo-bar} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5300"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-foo-bar-1.log" - - process.monitor_children do |children| - - children.stop_command "kill {{PID}}" - end - - process.group = "app-foo-bar" - end -end diff --git a/spec/resources/export/daemon/app-alpha-1.conf b/spec/resources/export/daemon/app-alpha-1.conf deleted file mode 100644 index 347fc3ae..00000000 --- a/spec/resources/export/daemon/app-alpha-1.conf +++ /dev/null @@ -1,7 +0,0 @@ -start on starting app-alpha -stop on stopping app-alpha -respawn - -env PORT=5000 - -exec start-stop-daemon --start --chuid app --chdir /tmp/app --make-pidfile --pidfile /var/run/app/app-alpha-1.pid --exec ./alpha >> /var/log/app/app-alpha-1.log 2>&1 diff --git a/spec/resources/export/daemon/app-alpha-2.conf b/spec/resources/export/daemon/app-alpha-2.conf deleted file mode 100644 index f72fe0c0..00000000 --- a/spec/resources/export/daemon/app-alpha-2.conf +++ /dev/null @@ -1,7 +0,0 @@ -start on starting app-alpha -stop on stopping app-alpha -respawn - -env PORT=5001 - -exec start-stop-daemon --start --chuid app --chdir /tmp/app --make-pidfile --pidfile /var/run/app/app-alpha-2.pid --exec ./alpha >> /var/log/app/app-alpha-2.log 2>&1 diff --git a/spec/resources/export/daemon/app-alpha.conf b/spec/resources/export/daemon/app-alpha.conf deleted file mode 100644 index 848119ec..00000000 --- a/spec/resources/export/daemon/app-alpha.conf +++ /dev/null @@ -1,2 +0,0 @@ -start on starting app -stop on stopping app diff --git a/spec/resources/export/daemon/app-bravo-1.conf b/spec/resources/export/daemon/app-bravo-1.conf deleted file mode 100644 index 44c4c1a5..00000000 --- a/spec/resources/export/daemon/app-bravo-1.conf +++ /dev/null @@ -1,7 +0,0 @@ -start on starting app-bravo -stop on stopping app-bravo -respawn - -env PORT=5100 - -exec start-stop-daemon --start --chuid app --chdir /tmp/app --make-pidfile --pidfile /var/run/app/app-bravo-1.pid --exec ./bravo >> /var/log/app/app-bravo-1.log 2>&1 diff --git a/spec/resources/export/daemon/app-bravo.conf b/spec/resources/export/daemon/app-bravo.conf deleted file mode 100644 index 848119ec..00000000 --- a/spec/resources/export/daemon/app-bravo.conf +++ /dev/null @@ -1,2 +0,0 @@ -start on starting app -stop on stopping app diff --git a/spec/resources/export/daemon/app.conf b/spec/resources/export/daemon/app.conf deleted file mode 100644 index f213f0e1..00000000 --- a/spec/resources/export/daemon/app.conf +++ /dev/null @@ -1,14 +0,0 @@ -pre-start script - -bash << "EOF" -mkdir -p /var/log/app -chown -R app /var/log/app -mkdir -p /var/run/app -chown -R app /var/run/app -EOF - -end script - -start on runlevel [2345] - -stop on runlevel [016] diff --git a/spec/resources/export/inittab/inittab.concurrency b/spec/resources/export/inittab/inittab.concurrency deleted file mode 100644 index 1f783572..00000000 --- a/spec/resources/export/inittab/inittab.concurrency +++ /dev/null @@ -1,4 +0,0 @@ -# ----- foreman app processes ----- -AP01:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5000;./alpha >> /var/log/app/alpha-1.log 2>&1' -AP02:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5001;./alpha >> /var/log/app/alpha-2.log 2>&1' -# ----- end foreman app processes ----- diff --git a/spec/resources/export/inittab/inittab.default b/spec/resources/export/inittab/inittab.default deleted file mode 100644 index 59655c7b..00000000 --- a/spec/resources/export/inittab/inittab.default +++ /dev/null @@ -1,6 +0,0 @@ -# ----- foreman app processes ----- -AP01:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5000;./alpha >> /var/log/app/alpha-1.log 2>&1' -AP02:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5100;./bravo >> /var/log/app/bravo-1.log 2>&1' -AP03:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5200;./foo_bar >> /var/log/app/foo_bar-1.log 2>&1' -AP04:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5300;./foo-bar >> /var/log/app/foo-bar-1.log 2>&1' -# ----- end foreman app processes ----- diff --git a/spec/resources/export/launchd/launchd-a.default b/spec/resources/export/launchd/launchd-a.default deleted file mode 100644 index 73423027..00000000 --- a/spec/resources/export/launchd/launchd-a.default +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Label - app-alpha-1 - EnvironmentVariables - - PORT - 5000 - - ProgramArguments - - ./alpha - - KeepAlive - - RunAtLoad - - StandardOutPath - /var/log/app/app-alpha-1.log - StandardErrorPath - /var/log/app/app-alpha-1.log - UserName - app - WorkingDirectory - /tmp/app - - diff --git a/spec/resources/export/launchd/launchd-b.default b/spec/resources/export/launchd/launchd-b.default deleted file mode 100644 index 51b63630..00000000 --- a/spec/resources/export/launchd/launchd-b.default +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Label - app-bravo-1 - EnvironmentVariables - - PORT - 5100 - - ProgramArguments - - ./bravo - - KeepAlive - - RunAtLoad - - StandardOutPath - /var/log/app/app-bravo-1.log - StandardErrorPath - /var/log/app/app-bravo-1.log - UserName - app - WorkingDirectory - /tmp/app - - diff --git a/spec/resources/export/launchd/launchd-c.default b/spec/resources/export/launchd/launchd-c.default deleted file mode 100644 index b157d843..00000000 --- a/spec/resources/export/launchd/launchd-c.default +++ /dev/null @@ -1,30 +0,0 @@ - - - - - Label - app-alpha-1 - EnvironmentVariables - - PORT - 5000 - - ProgramArguments - - ./alpha - charlie - - KeepAlive - - RunAtLoad - - StandardOutPath - /var/log/app/app-alpha-1.log - StandardErrorPath - /var/log/app/app-alpha-1.log - UserName - app - WorkingDirectory - /tmp/app - - diff --git a/spec/resources/export/runit/app-alpha-1/log/run b/spec/resources/export/runit/app-alpha-1/log/run deleted file mode 100644 index 3b06c7b6..00000000 --- a/spec/resources/export/runit/app-alpha-1/log/run +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -set -e - -LOG=/var/log/app/alpha-1 - -test -d "$LOG" || mkdir -p -m 2750 "$LOG" && chown app "$LOG" -exec chpst -u app svlogd "$LOG" diff --git a/spec/resources/export/runit/app-alpha-1/run b/spec/resources/export/runit/app-alpha-1/run deleted file mode 100644 index 9d6ea2fa..00000000 --- a/spec/resources/export/runit/app-alpha-1/run +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -cd /tmp/app -exec 2>&1 -exec chpst -u app -e /tmp/init/app-alpha-1/env ./alpha bar=baz diff --git a/spec/resources/export/runit/app-alpha-2/log/run b/spec/resources/export/runit/app-alpha-2/log/run deleted file mode 100644 index 5f458b47..00000000 --- a/spec/resources/export/runit/app-alpha-2/log/run +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -set -e - -LOG=/var/log/app/alpha-2 - -test -d "$LOG" || mkdir -p -m 2750 "$LOG" && chown app "$LOG" -exec chpst -u app svlogd "$LOG" diff --git a/spec/resources/export/runit/app-alpha-2/run b/spec/resources/export/runit/app-alpha-2/run deleted file mode 100644 index 0477f43e..00000000 --- a/spec/resources/export/runit/app-alpha-2/run +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -cd /tmp/app -exec 2>&1 -exec chpst -u app -e /tmp/init/app-alpha-2/env ./alpha bar=baz diff --git a/spec/resources/export/runit/app-bravo-1/log/run b/spec/resources/export/runit/app-bravo-1/log/run deleted file mode 100644 index db684368..00000000 --- a/spec/resources/export/runit/app-bravo-1/log/run +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -set -e - -LOG=/var/log/app/bravo-1 - -test -d "$LOG" || mkdir -p -m 2750 "$LOG" && chown app "$LOG" -exec chpst -u app svlogd "$LOG" diff --git a/spec/resources/export/runit/app-bravo-1/run b/spec/resources/export/runit/app-bravo-1/run deleted file mode 100644 index 84bbbe6e..00000000 --- a/spec/resources/export/runit/app-bravo-1/run +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -cd /tmp/app -exec 2>&1 -exec chpst -u app -e /tmp/init/app-bravo-1/env ./bravo diff --git a/spec/resources/export/supervisord/app-alpha-1.conf b/spec/resources/export/supervisord/app-alpha-1.conf deleted file mode 100644 index ccffab65..00000000 --- a/spec/resources/export/supervisord/app-alpha-1.conf +++ /dev/null @@ -1,42 +0,0 @@ -[program:app-alpha-1] -command=./alpha -autostart=true -autorestart=true -stdout_logfile=/var/log/app/alpha-1.log -stderr_logfile=/var/log/app/alpha-1.error.log -user=app -directory=/tmp/app -environment=FOO="bar",URL="http://example.com/api?foo=bar&baz=1",PORT="5000" - -[program:app-bravo-1] -command=./bravo -autostart=true -autorestart=true -stdout_logfile=/var/log/app/bravo-1.log -stderr_logfile=/var/log/app/bravo-1.error.log -user=app -directory=/tmp/app -environment=FOO="bar",URL="http://example.com/api?foo=bar&baz=1",PORT="5100" - -[program:app-foo_bar-1] -command=./foo_bar -autostart=true -autorestart=true -stdout_logfile=/var/log/app/foo_bar-1.log -stderr_logfile=/var/log/app/foo_bar-1.error.log -user=app -directory=/tmp/app -environment=FOO="bar",URL="http://example.com/api?foo=bar&baz=1",PORT="5200" - -[program:app-foo-bar-1] -command=./foo-bar -autostart=true -autorestart=true -stdout_logfile=/var/log/app/foo-bar-1.log -stderr_logfile=/var/log/app/foo-bar-1.error.log -user=app -directory=/tmp/app -environment=FOO="bar",URL="http://example.com/api?foo=bar&baz=1",PORT="5300" - -[group:app] -programs=app-alpha-1,app-bravo-1,app-foo_bar-1,app-foo-bar-1 diff --git a/spec/resources/export/supervisord/app-alpha-2.conf b/spec/resources/export/supervisord/app-alpha-2.conf deleted file mode 100644 index 0782e6f4..00000000 --- a/spec/resources/export/supervisord/app-alpha-2.conf +++ /dev/null @@ -1,22 +0,0 @@ -[program:app-alpha-1] -command=./alpha -autostart=true -autorestart=true -stdout_logfile=/var/log/app/alpha-1.log -stderr_logfile=/var/log/app/alpha-1.error.log -user=app -directory=/tmp/app -environment=PORT="5000" - -[program:app-alpha-2] -command=./alpha -autostart=true -autorestart=true -stdout_logfile=/var/log/app/alpha-2.log -stderr_logfile=/var/log/app/alpha-2.error.log -user=app -directory=/tmp/app -environment=PORT="5001" - -[group:app] -programs=app-alpha-1,app-alpha-2 diff --git a/spec/resources/export/systemd/app-alpha.1.service b/spec/resources/export/systemd/app-alpha.1.service deleted file mode 100644 index 7e1f828c..00000000 --- a/spec/resources/export/systemd/app-alpha.1.service +++ /dev/null @@ -1,18 +0,0 @@ -[Unit] -PartOf=app.target -StopWhenUnneeded=yes - -[Service] -User=app -WorkingDirectory=/tmp/app -Environment=PORT=5000 -Environment=PS=alpha.1 -ExecStart=/bin/bash -lc 'exec -a "app-alpha.1" ./alpha' -Restart=always -RestartSec=14s -StandardInput=null -StandardOutput=syslog -StandardError=syslog -SyslogIdentifier=%n -KillMode=mixed -TimeoutStopSec=5 diff --git a/spec/resources/export/systemd/app-alpha.2.service b/spec/resources/export/systemd/app-alpha.2.service deleted file mode 100644 index 3e48bc56..00000000 --- a/spec/resources/export/systemd/app-alpha.2.service +++ /dev/null @@ -1,18 +0,0 @@ -[Unit] -PartOf=app.target -StopWhenUnneeded=yes - -[Service] -User=app -WorkingDirectory=/tmp/app -Environment=PORT=5001 -Environment=PS=alpha.2 -ExecStart=/bin/bash -lc 'exec -a "app-alpha.2" ./alpha' -Restart=always -RestartSec=14s -StandardInput=null -StandardOutput=syslog -StandardError=syslog -SyslogIdentifier=%n -KillMode=mixed -TimeoutStopSec=5 diff --git a/spec/resources/export/systemd/app-alpha.target b/spec/resources/export/systemd/app-alpha.target deleted file mode 100644 index d3456fb0..00000000 --- a/spec/resources/export/systemd/app-alpha.target +++ /dev/null @@ -1,2 +0,0 @@ -[Unit] -PartOf=app.target diff --git a/spec/resources/export/systemd/app-bravo.1.service b/spec/resources/export/systemd/app-bravo.1.service deleted file mode 100644 index a9d1f307..00000000 --- a/spec/resources/export/systemd/app-bravo.1.service +++ /dev/null @@ -1,18 +0,0 @@ -[Unit] -PartOf=app.target -StopWhenUnneeded=yes - -[Service] -User=app -WorkingDirectory=/tmp/app -Environment=PORT=5100 -Environment=PS=bravo.1 -ExecStart=/bin/bash -lc 'exec -a "app-bravo.1" ./bravo' -Restart=always -RestartSec=14s -StandardInput=null -StandardOutput=syslog -StandardError=syslog -SyslogIdentifier=%n -KillMode=mixed -TimeoutStopSec=5 diff --git a/spec/resources/export/systemd/app-bravo.target b/spec/resources/export/systemd/app-bravo.target deleted file mode 100644 index d3456fb0..00000000 --- a/spec/resources/export/systemd/app-bravo.target +++ /dev/null @@ -1,2 +0,0 @@ -[Unit] -PartOf=app.target diff --git a/spec/resources/export/systemd/app.target b/spec/resources/export/systemd/app.target deleted file mode 100644 index 419bcdec..00000000 --- a/spec/resources/export/systemd/app.target +++ /dev/null @@ -1,5 +0,0 @@ -[Unit] -Wants=app-alpha.1.service app-bravo.1.service app-foo_bar.1.service app-foo-bar.1.service - -[Install] -WantedBy=multi-user.target diff --git a/spec/resources/export/upstart/app-alpha-1.conf b/spec/resources/export/upstart/app-alpha-1.conf deleted file mode 100644 index c39f9217..00000000 --- a/spec/resources/export/upstart/app-alpha-1.conf +++ /dev/null @@ -1,11 +0,0 @@ -start on starting app-alpha -stop on stopping app-alpha -respawn - -env PORT=5000 - -setuid app - -chdir /tmp/app - -exec ./alpha diff --git a/spec/resources/export/upstart/app-alpha-2.conf b/spec/resources/export/upstart/app-alpha-2.conf deleted file mode 100644 index 9a81529a..00000000 --- a/spec/resources/export/upstart/app-alpha-2.conf +++ /dev/null @@ -1,11 +0,0 @@ -start on starting app-alpha -stop on stopping app-alpha -respawn - -env PORT=5001 - -setuid app - -chdir /tmp/app - -exec ./alpha diff --git a/spec/resources/export/upstart/app-alpha.conf b/spec/resources/export/upstart/app-alpha.conf deleted file mode 100644 index 848119ec..00000000 --- a/spec/resources/export/upstart/app-alpha.conf +++ /dev/null @@ -1,2 +0,0 @@ -start on starting app -stop on stopping app diff --git a/spec/resources/export/upstart/app-bravo-1.conf b/spec/resources/export/upstart/app-bravo-1.conf deleted file mode 100644 index 40620403..00000000 --- a/spec/resources/export/upstart/app-bravo-1.conf +++ /dev/null @@ -1,11 +0,0 @@ -start on starting app-bravo -stop on stopping app-bravo -respawn - -env PORT=5100 - -setuid app - -chdir /tmp/app - -exec ./bravo diff --git a/spec/resources/export/upstart/app-bravo.conf b/spec/resources/export/upstart/app-bravo.conf deleted file mode 100644 index 848119ec..00000000 --- a/spec/resources/export/upstart/app-bravo.conf +++ /dev/null @@ -1,2 +0,0 @@ -start on starting app -stop on stopping app diff --git a/spec/resources/export/upstart/app.conf b/spec/resources/export/upstart/app.conf deleted file mode 100644 index 7bf1666f..00000000 --- a/spec/resources/export/upstart/app.conf +++ /dev/null @@ -1,2 +0,0 @@ -start on runlevel [2345] -stop on runlevel [!2345] diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 87e68890..7d221b2d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,174 +1,68 @@ -require "simplecov" -SimpleCov.start do - add_filter "/spec/" -end - -require "rspec" -require "timecop" -require "pp" -require "fakefs/safe" -require "fakefs/spec_helpers" - -$:.unshift File.expand_path("../../lib", __FILE__) - -def mock_export_error(message) - expect { yield }.to raise_error(Foreman::Export::Exception, message) -end - -def mock_error(subject, message) - mock_exit do - expect(subject).to receive(:puts).with("ERROR: #{message}") - yield +# frozen_string_literal: true + +require "foruiman" +require "tmpdir" +require "fileutils" +require "timeout" +require "rbconfig" +require "shellwords" +require "open3" + +module SpecHelpers + def write_file(name, content) + filename = File.join(@directory, name) + FileUtils.mkdir_p(File.dirname(filename)) + File.write(filename, content) + filename end -end - -def make_pipe - IO.method(:pipe).arity.zero? ? IO.pipe : IO.pipe("BINARY") -end -def foreman(args) - capture_stdout do - begin - Foreman::CLI.start(args.split(" ")) - rescue SystemExit - end + def fixture(mode, *args) + [RbConfig.ruby, File.expand_path("fixtures/child.rb", __dir__), mode, *args].shelljoin end -end -def forked_foreman(args) - rd, wr = make_pipe - Process.spawn("bundle exec bin/foreman #{args}", :out => wr, :err => wr) - wr.close - rd.read -end - -def fork_and_capture(&blk) - rd, wr = make_pipe - pid = fork do - rd.close - wr.sync = true - $stdout.reopen wr - $stderr.reopen wr - blk.call - $stdout.flush - $stdout.close - end - wr.close - Process.wait pid - buffer = "" - until rd.eof? - buffer += rd.gets + def build_engine(entries = {}, **) + engine = Foruiman::Engine.new(root: @directory, term_timeout: 0.15, **) + @engines << engine + entries.each { |name, command| engine.register(name, command) } + engine end -end - -def fork_and_get_exitstatus(args) - pid = Process.spawn("bundle exec bin/foreman #{args}", :out => "/dev/null", :err => "/dev/null") - Process.wait(pid) - $?.exitstatus -end - -def mock_exit(&block) - expect { block.call }.to raise_error(SystemExit) -end -def write_foreman_config(app) - File.open("/etc/foreman/#{app}.conf", "w") do |file| - file.puts %{#{app}_processes="alpha bravo"} - file.puts %{#{app}_alpha="1"} - file.puts %{#{app}_bravo="2"} - end -end + def eventually(engine = nil, timeout: 5) + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout + until yield + raise "condition timed out after #{timeout}s" if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline -def write_procfile(procfile="Procfile", alpha_env="") - FileUtils.mkdir_p(File.dirname(procfile)) - File.open(procfile, "w") do |file| - file.puts "alpha: ./alpha" + " #{alpha_env}".rstrip - file.puts "\n" - file.puts "bravo:\t./bravo" - file.puts "foo_bar:\t./foo_bar" - file.puts "foo-bar:\t./foo-bar" - file.puts "# baz:\t./baz" - end - File.expand_path(procfile) -end - -def write_file(file) - FileUtils.mkdir_p(File.dirname(file)) - File.open(file, 'w') do |f| - yield(f) if block_given? - end -end - -def write_env(env=".env", options={"FOO"=>"bar"}) - File.open(env, "w") do |file| - options.each do |key, val| - file.puts "#{key}=#{val}" + engine ? engine.tick(timeout: 0.01) : sleep(0.01) end end -end -def without_fakefs - FakeFS.deactivate! - ret = yield - FakeFS.activate! - ret -end + def alive?(pid) + Process.kill(0, pid) + state = File.read("/proc/#{pid}/stat").rpartition(") ").last.split.first if RUBY_PLATFORM.include?("linux") + return false if %w[Z X].include?(state) -def load_export_templates_into_fakefs(type) - without_fakefs do - Dir[File.expand_path("../../data/export/#{type}/**/*", __FILE__)].inject({}) do |hash, file| - next(hash) if File.directory?(file) - hash.update(file => File.read(file)) - end - end.each do |filename, contents| - FileUtils.mkdir_p File.dirname(filename) - File.open(filename, "w") do |f| - f.puts contents - end + true + rescue Errno::ESRCH, Errno::ENOENT + false end -end - -def resource_path(filename) - File.expand_path("../resources/#{filename}", __FILE__) -end - -def example_export_file(filename) - FakeFS.deactivate! - data = File.read(File.expand_path(resource_path("export/#{filename}"), __FILE__)) - FakeFS.activate! - data -end -def preserving_env - old_env = ENV.to_hash - begin - yield - ensure - ENV.clear - ENV.update(old_env) + def cli(*, env: {}) + Open3.capture3(env, RbConfig.ruby, "-I", File.expand_path("../lib", __dir__), + File.expand_path("../bin/foruiman", __dir__), *, chdir: @directory) end end -def normalize_space(s) - s.gsub(/\n[\n\s]*/, "\n") -end - -def capture_stdout - old_stdout = $stdout.dup - rd, wr = make_pipe - $stdout = wr - yield - wr.close - rd.read -ensure - $stdout = old_stdout -end - RSpec.configure do |config| - config.color = true - config.order = 'rand' - config.include FakeFS::SpecHelpers, :fakefs - config.before(:each) do - FileUtils.mkdir_p('/tmp') + config.include SpecHelpers + config.around do |example| + Dir.mktmpdir("foruiman-spec-") do |directory| + @directory = directory + @engines = [] + begin + example.run + ensure + @engines.each(&:close) + end + end end end diff --git a/tasks/dist.rake b/tasks/dist.rake deleted file mode 100644 index 84bfab8e..00000000 --- a/tasks/dist.rake +++ /dev/null @@ -1,112 +0,0 @@ -require "erb" -require "fileutils" -require "tmpdir" - -def assemble(source, target, perms=0644) - FileUtils.mkdir_p(File.dirname(target)) - File.open(target, "w") do |f| - f.puts ERB.new(File.read(source)).result(binding) - end - File.chmod(perms, target) -end - -def assemble_distribution(target_dir=Dir.pwd) - distribution_files.each do |source| - target = source.gsub(/^#{project_root}/, target_dir) - FileUtils.mkdir_p(File.dirname(target)) - FileUtils.cp(source, target) - end -end - -GEM_BLACKLIST = %w( bundler foreman ) - -def assemble_gems(target_dir=Dir.pwd) - lines = %x{ cd #{project_root} && bundle show }.strip.split("\n") - raise "error running bundler" unless $?.success? - - %x{ env BUNDLE_WITHOUT="development:test" bundle show }.split("\n").each do |line| - if line =~ /^ \* (.*?) \((.*?)\)/ - next if GEM_BLACKLIST.include?($1) - puts "vendoring: #{$1}-#{$2}" - gem_dir = %x{ bundle show #{$1} }.strip - FileUtils.mkdir_p "#{target_dir}/vendor/gems" - %x{ cp -R "#{gem_dir}" "#{target_dir}/vendor/gems" } - end - end.compact -end - -def beta? - Foreman::VERSION.to_s =~ /pre/ -end - -def clean(file) - rm file if File.exist?(file) -end - -def distribution_files(type=nil) - require "foreman/distribution" - base_files = Foreman::Distribution.files - type_files = type ? - Dir[File.expand_path("../../dist/resources/#{type}/**/*", __FILE__)] : [] - base_files.concat(type_files) -end - -def mkchdir(dir) - FileUtils.mkdir_p(dir) - Dir.chdir(dir) do |dir| - yield(File.expand_path(dir)) - end -end - -def pkg(filename) - File.expand_path("../../pkg/#{filename}", __FILE__) -end - -def project_root - File.expand_path("../..", __FILE__) -end - -def resource(name) - File.expand_path("../../dist/resources/#{name}", __FILE__) -end - -def s3_connect - return if @s3_connected - - require "aws/s3" - - unless ENV["FOREMAN_RELEASE_ACCESS"] && ENV["FOREMAN_RELEASE_SECRET"] - puts "please set FOREMAN_RELEASE_ACCESS and FOREMAN_RELEASE_SECRET in your environment" - exit 1 - end - - AWS::S3::Base.establish_connection!( - :access_key_id => ENV["FOREMAN_RELEASE_ACCESS"], - :secret_access_key => ENV["FOREMAN_RELEASE_SECRET"] - ) - - @s3_connected = true -end - -def store(package_file, filename, bucket="assets.foreman.io") - s3_connect - puts "storing: #{filename}" - AWS::S3::S3Object.store(filename, File.open(package_file), bucket, :access => :public_read) -end - -def tempdir - Dir.mktmpdir do |dir| - Dir.chdir(dir) do - yield(dir) - end - end -end - -def version - require "foreman/version" - Foreman::VERSION -end - -Dir[File.expand_path("../../dist/**/*.rake", __FILE__)].each do |rake| - import rake -end diff --git a/tasks/release.rake b/tasks/release.rake deleted file mode 100644 index eefc1917..00000000 --- a/tasks/release.rake +++ /dev/null @@ -1,68 +0,0 @@ -require "time" - -desc "Build the manual" -task :man do - ENV['RONN_MANUAL'] = "Foreman Manual" - ENV['RONN_ORGANIZATION'] = "Foreman #{Foreman::VERSION}" - sh "ronn -w -s toc -r5 --markdown man/*.ronn" -end - -desc "Commit the manual to git" -task "man:commit" => :man do - sh "git add README.md" - sh "git commit -am 'update docs' || echo 'nothing to commit'" - sh "git push" -end - -desc "Generate the Github docs" -task :pages => "man:commit" do - sh %{ - cp man/foreman.1.html /tmp/foreman.1.html - git checkout gh-pages - rm ./index.html - cp /tmp/foreman.1.html ./index.html - git add -u index.html - git commit -m "saving man page to github docs" - git push origin -f gh-pages - git checkout main - } -end - -def latest_release - latest = File.read("Changelog.md").split("\n").first.split(" ")[1] -end - -def newer_release - tags = %x{ git tag --contains v#{latest_release} | grep -v pre }.split("\n").sort_by do |tag| - Gem::Version.new(tag[1..-1]) - end - tags[1] -end - -desc "Generate a Changelog" -task :changelog do - while release = newer_release - entry = %x{ git show --format="%cd" #{release} | head -n 1 } - puts entry - date = Time.parse(entry.chomp).strftime("%Y-%m-%d") - - message = "## #{release[1..-1]} (#{date})\n\n" - message += %x{ git log --format="* %s [%an]" v#{latest_release}..#{release} | grep -v "Merge pull request" | grep -v "* #{release[1..-1]}" | grep -v "* update docs" } - - changelog = File.read("Changelog.md") - changelog = message + "\n" + changelog - - puts release - - File.open("Changelog.md", "w") do |file| - file.print changelog - end - end -end - -desc "Cut a release" -task :release do - Rake::Task["changelog"].invoke - Rake::Task["pages"].invoke - Rake::Task["gem:release"].invoke -end diff --git a/tasks/rspec.rake b/tasks/rspec.rake deleted file mode 100644 index 898349d6..00000000 --- a/tasks/rspec.rake +++ /dev/null @@ -1,8 +0,0 @@ -require "rspec/core/rake_task" - -task :default => :spec - -desc "Run all specs" -RSpec::Core::RakeTask.new(:spec) do |t| - t.pattern = 'spec/**/*_spec.rb' -end