sproc 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.gitignore +4 -0
- data/CODE_OF_CONDUCT.adoc +84 -0
- data/Gemfile +12 -0
- data/Gemfile.lock +43 -0
- data/LICENSE.txt +21 -0
- data/README.adoc +44 -0
- data/Rakefile +17 -0
- data/bin/console +15 -0
- data/bin/setup +8 -0
- data/lib/sproc.rb +9 -0
- data/lib/sproc/core.rb +307 -0
- data/lib/sproc/version.rb +5 -0
- data/sproc.gemspec +40 -0
- metadata +74 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 4ac0687b964181bd44d7c34228c256b251643e535f698575ae74bf95cef213d7
|
4
|
+
data.tar.gz: 29f4903a79f3535bf4b86aa1b324a211c2dd3d94ff3afd571f9ae192e3187d6e
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: ecbf92993cd338dec5463529da1abe25da308d6f0b6860f8b80d0ceca55fcd36aa59906fcc744ea9c87e616df8c915cf0980ec5dba1c70253833dea81a324983
|
7
|
+
data.tar.gz: 8acd7eb691cd5b601b4c6858b2adfa9e2988e72a9b21a4969bad0c227527e2339c31748a2d762e009d01a4c90c4836b37c62feb0ac75eab4a2c05d4e7337a6f1
|
data/.gitignore
ADDED
@@ -0,0 +1,84 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
6
|
+
|
7
|
+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
8
|
+
|
9
|
+
## Our Standards
|
10
|
+
|
11
|
+
Examples of behavior that contributes to a positive environment for our community include:
|
12
|
+
|
13
|
+
* Demonstrating empathy and kindness toward other people
|
14
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
15
|
+
* Giving and gracefully accepting constructive feedback
|
16
|
+
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
17
|
+
* Focusing on what is best not just for us as individuals, but for the overall community
|
18
|
+
|
19
|
+
Examples of unacceptable behavior include:
|
20
|
+
|
21
|
+
* The use of sexualized language or imagery, and sexual attention or
|
22
|
+
advances of any kind
|
23
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
24
|
+
* Public or private harassment
|
25
|
+
* Publishing others' private information, such as a physical or email
|
26
|
+
address, without their explicit permission
|
27
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
28
|
+
professional setting
|
29
|
+
|
30
|
+
## Enforcement Responsibilities
|
31
|
+
|
32
|
+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
33
|
+
|
34
|
+
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
35
|
+
|
36
|
+
## Scope
|
37
|
+
|
38
|
+
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
39
|
+
|
40
|
+
## Enforcement
|
41
|
+
|
42
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at anders.rillbert@kutso.se. All complaints will be reviewed and investigated promptly and fairly.
|
43
|
+
|
44
|
+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
45
|
+
|
46
|
+
## Enforcement Guidelines
|
47
|
+
|
48
|
+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
49
|
+
|
50
|
+
### 1. Correction
|
51
|
+
|
52
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
53
|
+
|
54
|
+
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
55
|
+
|
56
|
+
### 2. Warning
|
57
|
+
|
58
|
+
**Community Impact**: A violation through a single incident or series of actions.
|
59
|
+
|
60
|
+
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
61
|
+
|
62
|
+
### 3. Temporary Ban
|
63
|
+
|
64
|
+
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
65
|
+
|
66
|
+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
67
|
+
|
68
|
+
### 4. Permanent Ban
|
69
|
+
|
70
|
+
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
71
|
+
|
72
|
+
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
73
|
+
|
74
|
+
## Attribution
|
75
|
+
|
76
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
|
77
|
+
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
78
|
+
|
79
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
80
|
+
|
81
|
+
[homepage]: https://www.contributor-covenant.org
|
82
|
+
|
83
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
84
|
+
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
|
data/Gemfile
ADDED
data/Gemfile.lock
ADDED
@@ -0,0 +1,43 @@
|
|
1
|
+
PATH
|
2
|
+
remote: .
|
3
|
+
specs:
|
4
|
+
sproc (0.1.0)
|
5
|
+
|
6
|
+
GEM
|
7
|
+
remote: https://rubygems.org/
|
8
|
+
specs:
|
9
|
+
ast (2.4.2)
|
10
|
+
minitest (5.14.3)
|
11
|
+
parallel (1.20.1)
|
12
|
+
parser (3.0.0.0)
|
13
|
+
ast (~> 2.4.1)
|
14
|
+
rainbow (3.0.0)
|
15
|
+
rake (13.0.3)
|
16
|
+
regexp_parser (2.0.3)
|
17
|
+
rexml (3.2.4)
|
18
|
+
rubocop (0.93.1)
|
19
|
+
parallel (~> 1.10)
|
20
|
+
parser (>= 2.7.1.5)
|
21
|
+
rainbow (>= 2.2.2, < 4.0)
|
22
|
+
regexp_parser (>= 1.8)
|
23
|
+
rexml
|
24
|
+
rubocop-ast (>= 0.6.0)
|
25
|
+
ruby-progressbar (~> 1.7)
|
26
|
+
unicode-display_width (>= 1.4.0, < 2.0)
|
27
|
+
rubocop-ast (1.4.1)
|
28
|
+
parser (>= 2.7.1.5)
|
29
|
+
ruby-progressbar (1.11.0)
|
30
|
+
unicode-display_width (1.7.0)
|
31
|
+
|
32
|
+
PLATFORMS
|
33
|
+
ruby
|
34
|
+
x86_64-linux
|
35
|
+
|
36
|
+
DEPENDENCIES
|
37
|
+
minitest (~> 5.0)
|
38
|
+
rake (~> 13.0)
|
39
|
+
rubocop (~> 0.80)
|
40
|
+
sproc!
|
41
|
+
|
42
|
+
BUNDLED WITH
|
43
|
+
2.2.0
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2021 Anders Rillbert
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.adoc
ADDED
@@ -0,0 +1,44 @@
|
|
1
|
+
= SProc
|
2
|
+
|
3
|
+
WARNING: Work-in-progress
|
4
|
+
|
5
|
+
== Installation
|
6
|
+
|
7
|
+
Add this line to your application's Gemfile:
|
8
|
+
|
9
|
+
[source,ruby]
|
10
|
+
----
|
11
|
+
gem 'sproc'
|
12
|
+
----
|
13
|
+
|
14
|
+
And then execute:
|
15
|
+
|
16
|
+
$ bundle install
|
17
|
+
|
18
|
+
Or install it yourself as:
|
19
|
+
|
20
|
+
$ gem install sproc
|
21
|
+
|
22
|
+
== Usage
|
23
|
+
|
24
|
+
TBD...
|
25
|
+
|
26
|
+
== Development
|
27
|
+
|
28
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
29
|
+
|
30
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
31
|
+
|
32
|
+
== Contributing
|
33
|
+
|
34
|
+
TBD...
|
35
|
+
// Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/sproc. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/sproc/blob/master/CODE_OF_CONDUCT.md).
|
36
|
+
|
37
|
+
== License
|
38
|
+
|
39
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
40
|
+
|
41
|
+
== Code of Conduct
|
42
|
+
|
43
|
+
Everyone interacting in the Sproc project's codebases, issue trackers, chat rooms and mailing lists is expected
|
44
|
+
to follow the [code of conduct](https://github.com/[USERNAME]/sproc/blob/master/CODE_OF_CONDUCT.adoc).
|
data/Rakefile
ADDED
@@ -0,0 +1,17 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'bundler/gem_tasks'
|
4
|
+
require 'rake/testtask'
|
5
|
+
|
6
|
+
Rake::TestTask.new(:test) do |t|
|
7
|
+
t.libs << 'test'
|
8
|
+
t.libs << 'lib'
|
9
|
+
t.test_files = FileList['test/**/*_test.rb']
|
10
|
+
end
|
11
|
+
|
12
|
+
require 'rubocop/rake_task'
|
13
|
+
|
14
|
+
RuboCop::RakeTask.new
|
15
|
+
|
16
|
+
# task default: %i[test rubocop]
|
17
|
+
task default: :test
|
data/bin/console
ADDED
@@ -0,0 +1,15 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
require "bundler/setup"
|
5
|
+
require "sproc"
|
6
|
+
|
7
|
+
# You can add fixtures and/or initialization code here to make experimenting
|
8
|
+
# with your gem easier. You can also use a different console, if you like.
|
9
|
+
|
10
|
+
# (If you use this, don't forget to add pry to your Gemfile!)
|
11
|
+
# require "pry"
|
12
|
+
# Pry.start
|
13
|
+
|
14
|
+
require "irb"
|
15
|
+
IRB.start(__FILE__)
|
data/bin/setup
ADDED
data/lib/sproc.rb
ADDED
data/lib/sproc/core.rb
ADDED
@@ -0,0 +1,307 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'shellwords'
|
4
|
+
require 'open3'
|
5
|
+
|
6
|
+
module SProc
|
7
|
+
module ShellType
|
8
|
+
SHELL_TYPES = [NATIVE = 0, BASH = 1].freeze
|
9
|
+
end
|
10
|
+
|
11
|
+
# The possible states of this subprocess
|
12
|
+
module ExecutionState
|
13
|
+
NOT_STARTED = 0
|
14
|
+
RUNNING = 1
|
15
|
+
ABORTED = 2
|
16
|
+
COMPLETED = 3
|
17
|
+
FAILED_TO_START = 4
|
18
|
+
end
|
19
|
+
|
20
|
+
# Represents queryable info about the task run by this SubProcess
|
21
|
+
TaskInfo = Struct.new(
|
22
|
+
:cmd_str, # the invokation string used to start the process
|
23
|
+
:exception, # the exception terminating the process (nil if everything ok)
|
24
|
+
:wall_time, # the time (in s) between start and completion of the process
|
25
|
+
:process_status, # the ProcessStatus object (see Ruby docs)
|
26
|
+
:popen_thread, # the thread created by the popen call, nil before started
|
27
|
+
:stdout, # a String containing all output from the process' stdout
|
28
|
+
:stderr # a String containing all output from the process' stderr
|
29
|
+
)
|
30
|
+
|
31
|
+
# Execute a command in a subprocess, either synchronuously or asyncronously.
|
32
|
+
class SProc
|
33
|
+
# support a class-wise logger instance
|
34
|
+
@logger = nil
|
35
|
+
class << self
|
36
|
+
attr_accessor :logger
|
37
|
+
end
|
38
|
+
|
39
|
+
def logger
|
40
|
+
self.class.logger
|
41
|
+
end
|
42
|
+
|
43
|
+
include ShellType
|
44
|
+
include ExecutionState
|
45
|
+
|
46
|
+
# prepare to run a sub process
|
47
|
+
# @param type the ShellType used to run the process within
|
48
|
+
# @param stdout_callback a callback that will receive all stdout output
|
49
|
+
# from the process as it is running (default nil)
|
50
|
+
# @param stderr_callback a callback that will receive all stderr output
|
51
|
+
# from the process as it is running (default nil)
|
52
|
+
#
|
53
|
+
# example callback signature: def my_stdout_cb(line)
|
54
|
+
def initialize(type = ShellType::NATIVE, stdout_callback = nil,
|
55
|
+
stderr_callback = nil)
|
56
|
+
@run_opts = {
|
57
|
+
type: type,
|
58
|
+
stdout_callback: stdout_callback,
|
59
|
+
stderr_callback: stderr_callback
|
60
|
+
}
|
61
|
+
@runner = TaskRunner.new(@run_opts)
|
62
|
+
@execution_thread = nil
|
63
|
+
end
|
64
|
+
|
65
|
+
# @return the TaskInfo representing this SubProcess, nil if
|
66
|
+
# process has not started
|
67
|
+
def task_info
|
68
|
+
@runner.task_info
|
69
|
+
end
|
70
|
+
|
71
|
+
# check if this process has completed with exit code 0
|
72
|
+
# (success) or not
|
73
|
+
def exit_zero?
|
74
|
+
return false unless execution_state == ExecutionState::COMPLETED
|
75
|
+
|
76
|
+
task_info[:process_status].exitstatus.zero?
|
77
|
+
end
|
78
|
+
|
79
|
+
# Return the execution state of this SubProcess. Note that it is not
|
80
|
+
# identical with the life-cycle of the underlying ProcessStatus object
|
81
|
+
# @return current ExecutionState
|
82
|
+
def execution_state
|
83
|
+
return ExecutionState::NOT_STARTED if @execution_thread.nil?
|
84
|
+
|
85
|
+
# Count this SubProcess as running as long as the thread
|
86
|
+
# that executes it is alive (this includes book keeping
|
87
|
+
# chores within this class as well)
|
88
|
+
return ExecutionState::RUNNING if @execution_thread.alive?
|
89
|
+
|
90
|
+
status = task_info[:process_status]
|
91
|
+
|
92
|
+
# an execution thread that has run but not generated a task_info
|
93
|
+
# means that we tried to start a process but failed
|
94
|
+
return ExecutionState::FAILED_TO_START if status.nil?
|
95
|
+
|
96
|
+
# a process can terminate for different reasons:
|
97
|
+
# - its done
|
98
|
+
# - an uncaught exception-
|
99
|
+
# - an uncaught signal
|
100
|
+
|
101
|
+
# this should take care of uncaught signals
|
102
|
+
return ExecutionState::ABORTED if status.signaled?
|
103
|
+
|
104
|
+
# If the process completed (either successfully or not)
|
105
|
+
return ExecutionState::COMPLETED if status.exited?
|
106
|
+
|
107
|
+
# We don't currently handle a process that has been stopped...
|
108
|
+
# status.stopped?
|
109
|
+
end
|
110
|
+
|
111
|
+
# Start the process non-blocking. Use one of the wait... methods
|
112
|
+
# to later block on the process.
|
113
|
+
# @return this SubProcess instance
|
114
|
+
def exec_sync(cmd, *args, **opts)
|
115
|
+
exec(true, cmd, *args, **opts)
|
116
|
+
end
|
117
|
+
|
118
|
+
# Start the process non-blocking. Use one of the wait... methods
|
119
|
+
# to later block on the process.
|
120
|
+
# @return this SubProcess instance
|
121
|
+
def exec_async(cmd, *args, **opts)
|
122
|
+
exec(false, cmd, *args, **opts)
|
123
|
+
end
|
124
|
+
|
125
|
+
# Block caller until this subprocess has completed or aborted
|
126
|
+
# @return the TaskInfo struct of the completed process
|
127
|
+
def wait_on_completion
|
128
|
+
return if @execution_thread.nil?
|
129
|
+
|
130
|
+
@execution_thread.join
|
131
|
+
task_info
|
132
|
+
end
|
133
|
+
|
134
|
+
# blocks until all processes in the given array are completed/aborted.
|
135
|
+
#
|
136
|
+
# the implementation polls each process after each given poll interval
|
137
|
+
# (in ms)
|
138
|
+
#
|
139
|
+
# @return true if all processes exited with status 0, false in all other
|
140
|
+
# cases
|
141
|
+
def self.wait_on_all(running_proc, polling_interval = 100, &block)
|
142
|
+
until running_proc.empty?
|
143
|
+
done = get_finished(running_proc)
|
144
|
+
running_proc -= done
|
145
|
+
next unless block_given?
|
146
|
+
|
147
|
+
done.each(&block) if block_given?
|
148
|
+
sleep polling_interval / 1000
|
149
|
+
end
|
150
|
+
end
|
151
|
+
|
152
|
+
# Wait for processes to complete and give a block an opportunity to
|
153
|
+
# start one or more new processes for each completed one.
|
154
|
+
# a given block will be handed each completed SubProcess. If the block
|
155
|
+
# returns one or more SubProcess objects, these will be waited upon as well.
|
156
|
+
#
|
157
|
+
# @param running_proc an array of running proecesses to block on
|
158
|
+
# @param polling_interval how often (in ms) we check the run state of the
|
159
|
+
# running processes (default every 100 ms)
|
160
|
+
# @return all finished processes
|
161
|
+
#
|
162
|
+
# Example usage:
|
163
|
+
#
|
164
|
+
# # start 3 processes asyncronously
|
165
|
+
# nof_processes = 3
|
166
|
+
# p_array = (1..nof_processes).collect do
|
167
|
+
# SubProcess.new(SubProcess::NATIVE).exec_async('ping', ['127.0.0.1'])
|
168
|
+
# end
|
169
|
+
#
|
170
|
+
# # block until a process completes and then immediately start a new process
|
171
|
+
# # until we've started 10 in total
|
172
|
+
# p_total = SubProcess.wait_or_back_to_back(p_array) do |p|
|
173
|
+
# # create new processes until we reach 10
|
174
|
+
# unless nof_processes >= 10
|
175
|
+
# np = SubProcess.new.exec_async('echo', "Process #{nof_processes}")
|
176
|
+
# nof_processes += 1
|
177
|
+
# end
|
178
|
+
# np
|
179
|
+
# end
|
180
|
+
# ... here p_total will contain all 10 finished SubProcess objects
|
181
|
+
def self.wait_or_back_to_back(running_proc, polling_interval = 100)
|
182
|
+
all_proc = running_proc.dup
|
183
|
+
until running_proc.empty?
|
184
|
+
done = get_finished(running_proc)
|
185
|
+
running_proc -= done
|
186
|
+
next unless block_given?
|
187
|
+
|
188
|
+
done.each do |p|
|
189
|
+
new_proc = Array(yield(p)).select { |r| r.is_a?(SProc) }
|
190
|
+
running_proc += new_proc
|
191
|
+
all_proc += new_proc
|
192
|
+
end
|
193
|
+
sleep polling_interval / 1000
|
194
|
+
end
|
195
|
+
all_proc
|
196
|
+
end
|
197
|
+
|
198
|
+
# return processes that are no longer running
|
199
|
+
def self.get_finished(running_proc)
|
200
|
+
running_proc.select do |p|
|
201
|
+
[ExecutionState::COMPLETED,
|
202
|
+
ExecutionState::ABORTED,
|
203
|
+
ExecutionState::FAILED_TO_START].include?(p.execution_state)
|
204
|
+
end
|
205
|
+
end
|
206
|
+
|
207
|
+
private
|
208
|
+
|
209
|
+
def exec(synch, cmd, *args, **opts)
|
210
|
+
@execution_thread = Thread.new do
|
211
|
+
@runner.execute(cmd, *args, **opts)
|
212
|
+
end
|
213
|
+
@execution_thread.join if synch
|
214
|
+
self
|
215
|
+
end
|
216
|
+
|
217
|
+
# Helper class that runs one task using the preconditions given at
|
218
|
+
# instantiation.
|
219
|
+
# This class is not intended for external use
|
220
|
+
class TaskRunner
|
221
|
+
attr_reader :task_info
|
222
|
+
|
223
|
+
include ShellType
|
224
|
+
|
225
|
+
DEFAULT_OPTS = {
|
226
|
+
type: NATIVE,
|
227
|
+
stdout_callback: nil,
|
228
|
+
stderr_callback: nil
|
229
|
+
}.freeze
|
230
|
+
|
231
|
+
def initialize(opts)
|
232
|
+
@task_info = TaskInfo.new('', nil, 0, nil, nil, String.new, String.new)
|
233
|
+
@opts = DEFAULT_OPTS.dup.merge!(opts)
|
234
|
+
end
|
235
|
+
|
236
|
+
# Runs the process and blocks until it is completed or aborted.
|
237
|
+
# The stdout and stdin streams are continuously read in parallal with
|
238
|
+
# the process execution.
|
239
|
+
def execute(cmd, *args, **opts)
|
240
|
+
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
241
|
+
begin
|
242
|
+
shell_out_via_popen(cmd, *args, **opts)
|
243
|
+
rescue StandardError => e
|
244
|
+
@task_info[:exception] = e
|
245
|
+
end
|
246
|
+
@task_info[:wall_time] = (Process.clock_gettime(
|
247
|
+
Process::CLOCK_MONOTONIC
|
248
|
+
) - start_time)
|
249
|
+
end
|
250
|
+
|
251
|
+
private
|
252
|
+
|
253
|
+
def shell_out_via_popen(cmd, *args, **opts)
|
254
|
+
args = case @opts[:type]
|
255
|
+
when NATIVE then get_args_native(cmd, *args, **opts)
|
256
|
+
when BASH then get_args_bash(cmd, *args, **opts)
|
257
|
+
else raise ArgumentError, "Unknown task type: #{@type}!!"
|
258
|
+
end
|
259
|
+
SProc.logger&.debug { "Start: #{task_info[:cmd_str]}" }
|
260
|
+
Open3.popen3(*args) do |stdin, stdout, stderr, thread|
|
261
|
+
threads = do_while_process_running(stdin, stdout, stderr, thread)
|
262
|
+
@task_info[:process_status] = thread.value
|
263
|
+
threads.each(&:join)
|
264
|
+
end
|
265
|
+
end
|
266
|
+
|
267
|
+
def get_args_native(cmd, *args, **opts)
|
268
|
+
cmd_args = args.flatten.map(&:to_s)
|
269
|
+
@task_info[:cmd_str] = "#{cmd} #{cmd_args.join(' ')}"
|
270
|
+
[cmd.to_s, *cmd_args, opts]
|
271
|
+
end
|
272
|
+
|
273
|
+
# convert arguments to a string prepended with bash -c
|
274
|
+
def get_args_bash(cmd, *args, **opts)
|
275
|
+
cmd_str = ([cmd] + args).each { |a| Shellwords.escape(a) }.join(' ')
|
276
|
+
@task_info[:cmd_str] = "bash -c \"#{cmd_str}\""
|
277
|
+
[@task_info[:cmd_str], opts]
|
278
|
+
end
|
279
|
+
|
280
|
+
def do_while_process_running(_stdin, stdout, stderr, thread)
|
281
|
+
@task_info[:popen_thread] = thread
|
282
|
+
th1 = process_output_stream(stdout,
|
283
|
+
@task_info[:stdout], @opts[:stdout_callback])
|
284
|
+
th2 = process_output_stream(stderr,
|
285
|
+
@task_info[:stderr], @opts[:stderr_callback])
|
286
|
+
[th1, th2]
|
287
|
+
end
|
288
|
+
|
289
|
+
# process an output stream within a separate thread
|
290
|
+
def process_output_stream(stream, stream_cache = nil,
|
291
|
+
process_callback = nil)
|
292
|
+
Thread.new do
|
293
|
+
begin
|
294
|
+
until (raw_line = stream.gets).nil?
|
295
|
+
process_callback&.call(raw_line)
|
296
|
+
stream_cache << raw_line unless stream_cache.nil?
|
297
|
+
end
|
298
|
+
rescue IOError => e
|
299
|
+
l = SProc.logger
|
300
|
+
l&.warn { 'Stream closed before all output were read!' }
|
301
|
+
l&.warn { e.message }
|
302
|
+
end
|
303
|
+
end
|
304
|
+
end
|
305
|
+
end
|
306
|
+
end
|
307
|
+
end
|
data/sproc.gemspec
ADDED
@@ -0,0 +1,40 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "lib/sproc/version"
|
4
|
+
|
5
|
+
Gem::Specification.new do |spec|
|
6
|
+
spec.name = "sproc"
|
7
|
+
spec.version = SProc::VERSION
|
8
|
+
spec.authors = ["Anders Rillbert"]
|
9
|
+
spec.email = ["anders.rillbert@kutso.se"]
|
10
|
+
|
11
|
+
spec.summary = "Run subprocess asynch/synch."
|
12
|
+
spec.description = "Run subprocess asynch/synch."
|
13
|
+
spec.homepage = "https://github.com/rillbert/sproc"
|
14
|
+
spec.license = "MIT"
|
15
|
+
spec.required_ruby_version = Gem::Requirement.new(">= 2.7.0")
|
16
|
+
|
17
|
+
spec.metadata["allowed_push_host"] = "https://rubygems.org"
|
18
|
+
|
19
|
+
spec.metadata["homepage_uri"] = spec.homepage
|
20
|
+
spec.metadata["source_code_uri"] = spec.homepage
|
21
|
+
spec.metadata["changelog_uri"] = spec.homepage
|
22
|
+
|
23
|
+
# Specify which files should be added to the gem when it is released.
|
24
|
+
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
25
|
+
spec.files = Dir.chdir(File.expand_path(__dir__)) do
|
26
|
+
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
|
27
|
+
end
|
28
|
+
spec.bindir = "exe"
|
29
|
+
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|
30
|
+
spec.require_paths = ["lib"]
|
31
|
+
|
32
|
+
# Developer dependencies
|
33
|
+
spec.add_development_dependency "minitest", "~> 5.1"
|
34
|
+
|
35
|
+
# Uncomment to register a new dependency of your gem
|
36
|
+
# spec.add_dependency "example-gem", "~> 1.0"
|
37
|
+
|
38
|
+
# For more information and examples about making a new gem, checkout our
|
39
|
+
# guide at: https://bundler.io/guides/creating_gem.html
|
40
|
+
end
|
metadata
ADDED
@@ -0,0 +1,74 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: sproc
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Anders Rillbert
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2021-02-18 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: minitest
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - "~>"
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '5.1'
|
20
|
+
type: :development
|
21
|
+
prerelease: false
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
23
|
+
requirements:
|
24
|
+
- - "~>"
|
25
|
+
- !ruby/object:Gem::Version
|
26
|
+
version: '5.1'
|
27
|
+
description: Run subprocess asynch/synch.
|
28
|
+
email:
|
29
|
+
- anders.rillbert@kutso.se
|
30
|
+
executables: []
|
31
|
+
extensions: []
|
32
|
+
extra_rdoc_files: []
|
33
|
+
files:
|
34
|
+
- ".gitignore"
|
35
|
+
- CODE_OF_CONDUCT.adoc
|
36
|
+
- Gemfile
|
37
|
+
- Gemfile.lock
|
38
|
+
- LICENSE.txt
|
39
|
+
- README.adoc
|
40
|
+
- Rakefile
|
41
|
+
- bin/console
|
42
|
+
- bin/setup
|
43
|
+
- lib/sproc.rb
|
44
|
+
- lib/sproc/core.rb
|
45
|
+
- lib/sproc/version.rb
|
46
|
+
- sproc.gemspec
|
47
|
+
homepage: https://github.com/rillbert/sproc
|
48
|
+
licenses:
|
49
|
+
- MIT
|
50
|
+
metadata:
|
51
|
+
allowed_push_host: https://rubygems.org
|
52
|
+
homepage_uri: https://github.com/rillbert/sproc
|
53
|
+
source_code_uri: https://github.com/rillbert/sproc
|
54
|
+
changelog_uri: https://github.com/rillbert/sproc
|
55
|
+
post_install_message:
|
56
|
+
rdoc_options: []
|
57
|
+
require_paths:
|
58
|
+
- lib
|
59
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
60
|
+
requirements:
|
61
|
+
- - ">="
|
62
|
+
- !ruby/object:Gem::Version
|
63
|
+
version: 2.7.0
|
64
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
65
|
+
requirements:
|
66
|
+
- - ">="
|
67
|
+
- !ruby/object:Gem::Version
|
68
|
+
version: '0'
|
69
|
+
requirements: []
|
70
|
+
rubygems_version: 3.1.4
|
71
|
+
signing_key:
|
72
|
+
specification_version: 4
|
73
|
+
summary: Run subprocess asynch/synch.
|
74
|
+
test_files: []
|