foreman_openbolt 1.2.1 → 1.4.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.
Files changed (49) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +4 -1
  3. data/app/controllers/api/v2/openbolt_jobs_controller.rb +78 -0
  4. data/app/controllers/api/v2/openbolt_tasks_controller.rb +85 -0
  5. data/app/controllers/concerns/foreman_openbolt/common.rb +121 -0
  6. data/app/controllers/concerns/foreman_openbolt/jobs.rb +85 -0
  7. data/app/controllers/concerns/foreman_openbolt/tasks.rb +143 -0
  8. data/app/controllers/foreman_openbolt/task_controller.rb +12 -291
  9. data/app/lib/actions/foreman_openbolt/cleanup_proxy_artifacts.rb +4 -2
  10. data/app/lib/actions/foreman_openbolt/poll_task_status.rb +48 -29
  11. data/app/models/foreman_openbolt/task_job.rb +11 -3
  12. data/config/routes.rb +39 -4
  13. data/db/migrate/20260824000000_remove_view_smart_proxies_openbolt_permission.rb +18 -0
  14. data/db/migrate/20261118000000_add_host_groups_to_openbolt_task_jobs.rb +7 -0
  15. data/lib/foreman_openbolt/engine.rb +15 -7
  16. data/lib/foreman_openbolt/version.rb +1 -1
  17. data/lib/proxy_api/openbolt.rb +64 -13
  18. data/package.json +1 -1
  19. data/test/acceptance/api_acceptance_helper.rb +109 -0
  20. data/test/acceptance/tests/api/authn_authz_test.rb +82 -0
  21. data/test/acceptance/tests/api/jobs_test.rb +77 -0
  22. data/test/acceptance/tests/api/launch_test.rb +79 -0
  23. data/test/acceptance/tests/api/proxy_tasks_test.rb +51 -0
  24. data/test/unit/controllers/api/v2/openbolt_jobs_controller_test.rb +251 -0
  25. data/test/unit/controllers/api/v2/openbolt_tasks_controller_test.rb +438 -0
  26. data/test/unit/controllers/task_controller_test.rb +197 -39
  27. data/test/unit/docker/Dockerfile +7 -0
  28. data/test/unit/lib/actions/poll_task_status_test.rb +112 -34
  29. data/test/unit/lib/proxy_api/openbolt_test.rb +121 -6
  30. data/test/unit/models/task_job_test.rb +13 -0
  31. data/webpack/src/Components/LaunchTask/HostSelector/index.js +31 -5
  32. data/webpack/src/Components/LaunchTask/__tests__/helpers.test.js +60 -0
  33. data/webpack/src/Components/LaunchTask/helpers.js +16 -0
  34. data/webpack/src/Components/LaunchTask/hooks/__tests__/useOpenBoltOptions.test.js +3 -0
  35. data/webpack/src/Components/LaunchTask/hooks/__tests__/useTasksData.test.js +5 -4
  36. data/webpack/src/Components/LaunchTask/hooks/useOpenBoltOptions.js +1 -1
  37. data/webpack/src/Components/LaunchTask/hooks/useTasksData.js +4 -1
  38. data/webpack/src/Components/LaunchTask/index.js +29 -13
  39. data/webpack/src/Components/TaskExecution/ExecutionDetails.js +8 -0
  40. data/webpack/src/Components/TaskExecution/ExecutionDisplay.js +4 -0
  41. data/webpack/src/Components/TaskExecution/__tests__/TaskExecution.test.js +1 -1
  42. data/webpack/src/Components/TaskExecution/hooks/__tests__/useJobPolling.test.js +8 -8
  43. data/webpack/src/Components/TaskExecution/hooks/useJobPolling.js +6 -3
  44. data/webpack/src/Components/TaskExecution/index.js +43 -7
  45. data/webpack/src/Components/TaskHistory/__tests__/TaskHistory.test.js +6 -6
  46. data/webpack/src/Components/TaskHistory/index.js +8 -3
  47. data/webpack/src/Components/common/HostGroupsPopover.js +53 -0
  48. data/webpack/src/Components/common/__tests__/HostGroupsPopover.test.js +20 -0
  49. metadata +22 -7
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a6aae14c90bc7a4af6435767a84d174b69309e9f98ae59a221477067be2492b8
4
- data.tar.gz: 2d3e9188b01cf3c03bc132440106271b541f8ab753df060984e559b624058631
3
+ metadata.gz: 71f5e8b870d9c27a1314ab3b2567fab231b6c23b460b615a10053003513ce619
4
+ data.tar.gz: b1454607486de4a76b8d2a9cf230f25d9ca5c47cbd70ae24384eddd9328fbbe2
5
5
  SHA512:
6
- metadata.gz: 4f2f8a142ca2e214836b36c5f22be10975c322b5df20830110edc09ef49ac6b1445bccb22ffbe7b6d3252efb140d9ce45b1fa11d12987df27270fbd014e497ca
7
- data.tar.gz: b05c9442560d6acc1720c7495c30fe213f2b59ea72f5aefe37f3b7cab98b863b6c22add8fa3fd010b6b3803075b4c46ad130232c7b804d2dfffd6f4f118f17fe
6
+ metadata.gz: 9fbb0751b94c7173b802ff6a267f2e1ceaf5a8d34f6f1c1e93fe61e5561015623bc3dd9fd4d35af629ee8d8f3b48e6c060abc3a1b87bcc34eaf9e03ace4716db
7
+ data.tar.gz: 296caaa91415bddec17f00197ed7dcfdeff7ebe3dda78995e288e7ac3398d053422e0e8b2035270dcbb3c86bc589c2b6016c4e6cb830e19a079e2bb86b8a8d47
data/README.md CHANGED
@@ -5,8 +5,9 @@
5
5
  [![Release](https://github.com/overlookinfra/foreman_openbolt/actions/workflows/release.yml/badge.svg)](https://github.com/overlookinfra/foreman_openbolt/actions/workflows/release.yml)
6
6
  [![RubyGem Version](https://img.shields.io/gem/v/foreman_openbolt.svg)](https://rubygems.org/gems/foreman_openbolt)
7
7
  [![RubyGem Downloads](https://img.shields.io/gem/dt/foreman_openbolt.svg)](https://rubygems.org/gems/foreman_openbolt)
8
+ [![Foreman Landscape](https://img.shields.io/badge/Foreman-Landscape-blue.svg)](https://theforeman.github.io/foreman-plugin-overview/)
8
9
 
9
- Bringing OpenBolt Task & Plans into Foreman!
10
+ Bringing [OpenBolt](https://docs.openvoxproject.org/openbolt/latest/) Task & Plans into [Foreman](https://theforeman.org/)!
10
11
 
11
12
  ## Introduction
12
13
 
@@ -68,9 +69,11 @@ A handful of core/default Tasks & Plans are also included in the [OpenBolt rpm/d
68
69
  ## Documentation
69
70
 
70
71
  - [Usage](docs/usage.md): screenshots and walkthrough of the UI
72
+ - [API](docs/api.md): REST API reference, authentication, and example requests
71
73
  - [Development](docs/development.md): linting, unit tests, acceptance tests, building packages
72
74
  - [Releasing](docs/releasing.md): version locations, release steps, RPM/DEB packaging
73
75
  - [Choria Testing](docs/choria-testing.md): setting up Choria on a Foreman install for transport testing
76
+ - [Foreman + Choria Example Code](docs/choria.md): Example Hiera and Puppet code to get started with Foreman and OpenBolt and Choria
74
77
 
75
78
  ## Contributing & support
76
79
 
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Api
4
+ module V2
5
+ class OpenboltJobsController < Api::V2::BaseController
6
+ include Api::Version2
7
+ include ForemanOpenbolt::Jobs
8
+
9
+ resource_description do
10
+ resource_id 'openbolt_jobs'
11
+ api_version 'v2'
12
+ api_base_url '/api/v2/openbolt'
13
+ end
14
+
15
+ def resource_class
16
+ ForemanOpenbolt::TaskJob
17
+ end
18
+
19
+ def_param_group :job do
20
+ property :job_id, String, desc: N_('Proxy-issued job ID')
21
+ property :kind, %w[task], desc: N_("Job kind. Currently always 'task', and will include 'plan' at a later date.")
22
+ property :status, ForemanOpenbolt::TaskJob::STATUSES, desc: N_('Status of the job')
23
+ property :submitted_at, Time, desc: N_('When the job was submitted to the proxy')
24
+ property :completed_at, Time, allow_nil: true, desc: N_('When the job completed. Empty while the job is running.')
25
+ property :duration, Float, allow_nil: true, desc: N_('Job duration in seconds. Empty while the job is running.')
26
+ property :name, String, desc: N_('Name of the launched Bolt task (or later, plan)')
27
+ property :description, String, allow_nil: true, desc: N_('Description of the launched Bolt task (or later, plan)')
28
+ property :parameters, Hash, desc: N_('Parameters the job was launched with')
29
+ property :targets, Array, of: String, desc: N_('Target hosts the job was launched against for tasks')
30
+ property :host_groups, Array, of: String, desc: N_('Host groups the job was launched against')
31
+ property :smart_proxy, Hash, desc: N_('Smart proxy that executed the job') do
32
+ property :id, Integer, desc: N_('Smart proxy ID')
33
+ property :name, String, desc: N_('Smart proxy name')
34
+ end
35
+ end
36
+
37
+ api :GET, '/jobs', N_('List of OpenBolt jobs recorded in Foreman')
38
+ param_group :pagination, Api::V2::BaseController
39
+ returns code: 200, desc: N_('Paginated list of jobs') do
40
+ property :total, Integer, desc: N_('Total number of recorded jobs')
41
+ property :page, Integer, desc: N_('Current page number')
42
+ property :per_page, Integer, desc: N_('Number of jobs per page')
43
+ property :results, Array, desc: N_('Job objects for the requested page') do
44
+ param_group :job, ::Api::V2::OpenboltJobsController
45
+ end
46
+ end
47
+ def jobs
48
+ super
49
+ end
50
+
51
+ api :GET, '/jobs/:job_id/status', N_('Get the current status of an OpenBolt job')
52
+ param :job_id, :identifier, required: true, desc: N_('Proxy-issued job ID returned by /launch/task')
53
+ returns :job, code: 200, desc: N_('Current status of the job')
54
+ def job_status
55
+ super
56
+ end
57
+
58
+ api :GET, '/jobs/:job_id/result',
59
+ N_('Get the full result (command, OpenBolt result value, log) of a completed OpenBolt job')
60
+ param :job_id, :identifier, required: true, desc: N_('Proxy-issued job ID returned by /launch/task')
61
+ returns code: 200, desc: N_('Full result of the job') do
62
+ property :kind, %w[task], desc: N_("Job kind. Currently always 'task', and will include 'plan' at a later date.")
63
+ property :status, ForemanOpenbolt::TaskJob::STATUSES, desc: N_('Status of the job')
64
+ property :command, String, allow_nil: true,
65
+ desc: N_('The OpenBolt command the proxy ran, with sensitive option values scrubbed. ' \
66
+ 'Empty until the proxy reports the first status update.')
67
+ property :value, [Hash, String], allow_nil: true,
68
+ desc: N_('Run result as produced by the OpenBolt CLI, passed through unmodified. ' \
69
+ 'Its layout depends on the job kind and the OpenBolt Result format. ' \
70
+ 'On failure or exception, this may instead be a plain string holding the raw output.')
71
+ property :log, String, allow_nil: true, desc: N_('Output log of the run')
72
+ end
73
+ def job_result
74
+ super
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'foreman/logging'
4
+ require 'proxy_api/openbolt'
5
+
6
+ module Api
7
+ module V2
8
+ class OpenboltTasksController < Api::V2::BaseController
9
+ include Api::Version2
10
+ include ForemanOpenbolt::Tasks
11
+
12
+ resource_description do
13
+ resource_id 'openbolt_tasks'
14
+ api_version 'v2'
15
+ api_base_url '/api/v2/openbolt'
16
+ end
17
+
18
+ def_param_group :task_map do
19
+ property :task_name, Hash, required: false,
20
+ desc: N_('One entry per task, keyed by the task name. "task_name" is a placeholder, and the actual keys are the task names.') do
21
+ property :description, String, desc: N_('Description from the task metadata')
22
+ property :parameters, Hash,
23
+ desc: N_('Parameter definitions from the task metadata, keyed by parameter name')
24
+ end
25
+ end
26
+
27
+ api :GET, '/smart_proxies/:smart_proxy_id/tasks', N_('List Bolt tasks available on a smart proxy')
28
+ param :smart_proxy_id, Integer, required: true, desc: N_('ID of the smart proxy to query')
29
+ returns :task_map, code: 200, additional_properties: true,
30
+ desc: N_('Hash keyed by task name. task_name below is a placeholder, and the actual keys are the task names.')
31
+ def tasks
32
+ super
33
+ end
34
+
35
+ api :POST, '/smart_proxies/:smart_proxy_id/tasks/reload', N_("Reload the smart proxy's Bolt task cache")
36
+ param :smart_proxy_id, Integer, required: true, desc: N_('ID of the smart proxy to reload')
37
+ returns :task_map, code: 200, additional_properties: true,
38
+ desc: N_('The refreshed task list, in the same shape as the tasks endpoint response')
39
+ def reload_tasks
40
+ super
41
+ end
42
+
43
+ api :GET, '/smart_proxies/:smart_proxy_id/tasks/options',
44
+ N_('Get OpenBolt options metadata for a smart proxy, with Foreman setting defaults merged in')
45
+ param :smart_proxy_id, Integer, required: true, desc: N_('ID of the smart proxy to query')
46
+ returns code: 200, additional_properties: true,
47
+ desc: N_('Hash keyed by option name. "option_name" is a placeholder, and the actual keys are the option names.') do
48
+ property :option_name, Hash, required: false, desc: N_('One entry per option, keyed by the option name') do
49
+ property :type, [String, Array],
50
+ desc: N_("The option's value type, either a type name or an array of the allowed values")
51
+ property :transport, Array, of: String, desc: N_('Transports the option applies to')
52
+ property :sensitive, [true, false], desc: N_('Whether the value is scrubbed from recorded commands and logs')
53
+ property :description, String, desc: N_('Human readable description of the option')
54
+ property :default, [String, Integer, TrueClass, FalseClass], required: false,
55
+ desc: N_('Default value, from the smart proxy or a Foreman setting when one is set. ' \
56
+ 'If a Foreman setting is present and this is a sensitive type, the default value ' \
57
+ 'will read "[Use saved ecrypted default]".')
58
+ end
59
+ end
60
+ def task_options
61
+ super
62
+ end
63
+
64
+ api :POST, '/launch/task', N_('Launch a Bolt task on a smart proxy')
65
+ param :smart_proxy_id, Integer, required: true,
66
+ desc: N_('ID of the smart proxy that will execute the task')
67
+ param :task_name, String, required: true, desc: N_('Name of the Bolt task to run')
68
+ param :targets, String, required: true,
69
+ desc: N_('Comma-separated list of target hosts the task should run on')
70
+ param :host_groups, String, required: false,
71
+ desc: N_('Comma-separated list of host groups the task was launched against')
72
+ param :parameters, Hash, required: false,
73
+ desc: N_('Task-specific parameters, keyed by parameter name')
74
+ param :options, Hash, required: false,
75
+ desc: N_('OpenBolt options (transport, user, run-as, etc.) as accepted by the bolt CLI')
76
+ returns code: 201, desc: N_('Job accepted by the smart proxy') do
77
+ property :job_id, String, desc: N_('Proxy-issued job ID, usable with the /jobs/:job_id endpoints')
78
+ property :kind, %w[task], desc: N_("Currently always 'task', and will include 'plan' at a later date.")
79
+ end
80
+ def launch_task
81
+ super
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'foreman/logging'
4
+ require 'proxy_api/openbolt'
5
+
6
+ module ForemanOpenbolt
7
+ module Common
8
+ extend ActiveSupport::Concern
9
+
10
+ ENCRYPTED_PLACEHOLDER = '[Use saved encrypted default]'
11
+ REDACTED_PLACEHOLDER = '*****'
12
+
13
+ class LaunchError < StandardError; end
14
+
15
+ # The caller sent the encrypted placeholder for an option with no saved setting.
16
+ class MissingEncryptedDefault < StandardError; end
17
+
18
+ # The proxy accepted the task but Foreman could not record or track it.
19
+ class PartialLaunchError < StandardError; end
20
+
21
+ included do
22
+ rescue_from ForemanOpenbolt::Common::LaunchError do |error|
23
+ logger.warn("OpenBolt #{openbolt_surface} launch failed: #{error.class}: #{error.message}")
24
+ render_json_error(error.message, :bad_request)
25
+ end
26
+
27
+ rescue_from ForemanOpenbolt::Common::PartialLaunchError do |error|
28
+ Foreman::Logging.exception("OpenBolt #{openbolt_surface} partial launch failure: #{error.message}", error)
29
+ render_json_error(error.message, :internal_server_error)
30
+ end
31
+
32
+ rescue_from ProxyAPI::ProxyException do |error|
33
+ Foreman::Logging.exception("OpenBolt #{openbolt_surface} proxy call failed", error)
34
+ render_json_error("Smart Proxy error: #{error.message}", :bad_gateway)
35
+ end
36
+
37
+ rescue_from ForemanOpenbolt::Common::MissingEncryptedDefault do |error|
38
+ logger.warn("OpenBolt #{openbolt_surface} missing encrypted default failure: #{error.message}")
39
+ render_json_error(error.message, :bad_request)
40
+ end
41
+ end
42
+
43
+ def openbolt_surface
44
+ self.class.name.start_with?('Api::') ? 'API' : 'UI'
45
+ end
46
+
47
+ def openbolt_settings
48
+ @openbolt_settings ||= Foreman.settings.category_settings(:openbolt).values
49
+ end
50
+
51
+ def merge_encrypted_defaults(options)
52
+ merged = options.dup
53
+ merged.each do |key, value|
54
+ next unless value == ENCRYPTED_PLACEHOLDER
55
+
56
+ saved = Setting["openbolt_#{key}"]
57
+ if saved.nil? || saved.to_s.empty?
58
+ raise MissingEncryptedDefault,
59
+ "No saved value for encrypted option '#{key}'. Configure it on the Foreman Settings page or provide a value."
60
+ end
61
+ merged[key] = saved
62
+ end
63
+ merged
64
+ end
65
+
66
+ def scrub_options_for_storage(options)
67
+ scrubbed = options.dup
68
+ openbolt_settings.select(&:encrypted?).each do |setting|
69
+ option_name = setting.name.sub(/^openbolt_/, '')
70
+ scrubbed[option_name] = REDACTED_PLACEHOLDER if scrubbed.key?(option_name)
71
+ end
72
+ scrubbed
73
+ end
74
+
75
+ def openbolt_options_with_defaults
76
+ options = @openbolt_api.openbolt_options
77
+
78
+ defaults = {}
79
+ openbolt_settings.each do |setting|
80
+ key = setting.name.sub(/^openbolt_/, '')
81
+ if setting.encrypted?
82
+ defaults[key] = ENCRYPTED_PLACEHOLDER unless setting.value.to_s.empty?
83
+ elsif !setting.value.to_s.empty?
84
+ defaults[key] = setting.value
85
+ end
86
+ end
87
+
88
+ result = {}
89
+ options.each do |name, meta|
90
+ result[name] = meta.dup
91
+ result[name]['default'] = defaults[name] if defaults.key?(name)
92
+ end
93
+ result
94
+ end
95
+
96
+ # before_action helpers shared by UI and API controllers
97
+ def load_smart_proxy
98
+ smart_proxy_id = params[:smart_proxy_id]
99
+ if smart_proxy_id.blank?
100
+ render_json_error('Smart Proxy ID is required', :bad_request)
101
+ return
102
+ end
103
+ @smart_proxy = SmartProxy.authorized(:view_smart_proxies).find_by(id: smart_proxy_id)
104
+ return if @smart_proxy
105
+ render_json_error("Smart Proxy with ID #{smart_proxy_id} not found or not authorized", :not_found)
106
+ end
107
+
108
+ def load_openbolt_api
109
+ return unless @smart_proxy
110
+ @openbolt_api = ProxyAPI::Openbolt.new(url: @smart_proxy.url)
111
+ rescue StandardError => e
112
+ Foreman::Logging.exception("load_openbolt_api for proxy #{@smart_proxy.name}", e)
113
+ render_json_error('Failed to connect to Smart Proxy', :bad_gateway)
114
+ end
115
+
116
+ # Matches Foreman's custom_error template so UI and API errors share one shape.
117
+ def render_json_error(message, status)
118
+ render json: { error: { message: message } }, status: status
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ForemanOpenbolt
4
+ module Jobs
5
+ extend ActiveSupport::Concern
6
+ include ForemanOpenbolt::Common
7
+
8
+ included do
9
+ before_action :load_task_job, only: [:job_status, :job_result]
10
+ end
11
+
12
+ def load_task_job
13
+ job_id = params[:job_id]
14
+ if job_id.blank?
15
+ render_json_error('Job ID is required', :bad_request)
16
+ return
17
+ end
18
+ @task_job = ForemanOpenbolt::TaskJob.find_by(job_id: job_id)
19
+ logger.debug { "TaskJob lookup #{job_id.inspect}: #{@task_job ? @task_job.status : 'not found'}" }
20
+ return if @task_job
21
+ render_json_error("Job #{job_id} not found", :not_found)
22
+ end
23
+
24
+ def task_job_status(task_job)
25
+ {
26
+ job_id: task_job.job_id,
27
+ kind: task_job.kind,
28
+ status: task_job.status,
29
+ submitted_at: task_job.submitted_at,
30
+ completed_at: task_job.completed_at,
31
+ duration: task_job.duration,
32
+ name: task_job.task_name,
33
+ description: task_job.task_description,
34
+ parameters: task_job.task_parameters,
35
+ targets: task_job.targets,
36
+ host_groups: task_job.host_groups,
37
+ smart_proxy: {
38
+ id: task_job.smart_proxy_id,
39
+ name: task_job.smart_proxy&.name || '(unknown)',
40
+ },
41
+ }
42
+ end
43
+
44
+ def task_job_result(task_job)
45
+ {
46
+ kind: task_job.kind,
47
+ status: task_job.status,
48
+ command: task_job.command,
49
+ value: task_job.result,
50
+ log: task_job.log,
51
+ }
52
+ end
53
+
54
+ def paginated_task_jobs(per_page_param:, page:)
55
+ page = [page.to_i, 1].max
56
+ per_page = if per_page_param == 'all'
57
+ [ForemanOpenbolt::TaskJob.count, 1].max
58
+ elsif per_page_param.present?
59
+ per_page_param.to_i.clamp(1, 100)
60
+ else
61
+ 20
62
+ end
63
+ ForemanOpenbolt::TaskJob.includes(:smart_proxy).recent.paginate(page: page, per_page: per_page)
64
+ end
65
+
66
+ def job_status
67
+ render json: task_job_status(@task_job)
68
+ end
69
+
70
+ def job_result
71
+ render json: task_job_result(@task_job)
72
+ end
73
+
74
+ def jobs
75
+ paginated = paginated_task_jobs(per_page_param: params[:per_page], page: params[:page])
76
+
77
+ render json: {
78
+ total: paginated.total_entries,
79
+ page: paginated.current_page,
80
+ per_page: paginated.per_page,
81
+ results: paginated.map { |job| task_job_status(job) },
82
+ }
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,143 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'foreman/logging'
4
+
5
+ module ForemanOpenbolt
6
+ module Tasks
7
+ extend ActiveSupport::Concern
8
+ include ForemanOpenbolt::Common
9
+
10
+ included do
11
+ before_action :load_smart_proxy, only: [:tasks, :reload_tasks, :task_options, :launch_task]
12
+ before_action :load_openbolt_api, only: [:tasks, :reload_tasks, :task_options, :launch_task]
13
+ end
14
+
15
+ # Shared by the API and UI controllers. The API controller wraps each
16
+ # action with super so it can attach apipie docs.
17
+ def tasks
18
+ render json: @openbolt_api.tasks
19
+ end
20
+
21
+ def reload_tasks
22
+ render json: @openbolt_api.reload_tasks
23
+ end
24
+
25
+ def task_options
26
+ render json: openbolt_options_with_defaults
27
+ end
28
+
29
+ def launch_task
30
+ job_id = dispatch_task(
31
+ smart_proxy: @smart_proxy,
32
+ openbolt_api: @openbolt_api,
33
+ task_name: params[:task_name],
34
+ targets: params[:targets],
35
+ host_groups: params[:host_groups] || '',
36
+ parameters: params[:parameters] || {},
37
+ options: params[:options] || {}
38
+ )
39
+ render json: { job_id: job_id, kind: 'task' }, status: :created
40
+ end
41
+
42
+ # Submits a task to the proxy, saves the TaskJob, and schedules polling.
43
+ # Returns the proxy-issued job id. Failures after the proxy accepts the
44
+ # launch raise PartialLaunchError. The proxy job keeps running and there
45
+ # is no proxy-side cancel hook right now, so we only surface the failure.
46
+ def dispatch_task(smart_proxy:, openbolt_api:, task_name:, targets:, host_groups:, parameters:, options:)
47
+ task_name = task_name.to_s.strip
48
+ targets = targets.to_s.strip
49
+ host_groups = host_groups.to_s.strip
50
+ raise ForemanOpenbolt::Common::LaunchError, 'Task name and targets cannot be empty' if task_name.empty? || targets.empty?
51
+
52
+ merged_options = merge_encrypted_defaults(options)
53
+
54
+ logger.info { "Launching OpenBolt task '#{task_name}' on targets '#{targets}' via proxy #{smart_proxy.name}" }
55
+
56
+ response = openbolt_api.launch_task(
57
+ name: task_name,
58
+ targets: targets,
59
+ parameters: parameters,
60
+ options: merged_options
61
+ )
62
+ logger.debug { "Task execution response: #{response.inspect}" }
63
+
64
+ if response['error']
65
+ error_detail = response['error'].is_a?(Hash) ? response['error']['message'] : response['error']
66
+ raise ForemanOpenbolt::Common::LaunchError, "Task execution failed: #{error_detail}"
67
+ end
68
+ raise ForemanOpenbolt::Common::LaunchError, 'Task execution failed: No job ID returned' unless response['id']
69
+
70
+ # The proxy is now running the task so any failures below are partial state.
71
+ job_id = response['id']
72
+
73
+ task_job = begin
74
+ # Metadata is optional and a fetch failure should not abort a running job.
75
+ metadata = begin
76
+ fetched = openbolt_api.tasks[task_name]
77
+ if fetched.nil?
78
+ logger.warn(
79
+ "Proxy accepted launch of '#{task_name}' (job #{job_id}) but " \
80
+ "the task is not in the proxy's task list. Description will be empty."
81
+ )
82
+ end
83
+ fetched || {}
84
+ rescue StandardError => e
85
+ logger.warn(
86
+ "Could not fetch task metadata for #{task_name} after launching " \
87
+ "job #{job_id}: #{e.class}: #{e.message}. Proceeding without description."
88
+ )
89
+ {}
90
+ end
91
+
92
+ ForemanOpenbolt::TaskJob.create_from_execution!(
93
+ proxy: smart_proxy,
94
+ task_name: task_name,
95
+ task_description: metadata['description'] || '',
96
+ targets: targets.split(',').map(&:strip),
97
+ host_groups: host_groups.split(',').map(&:strip),
98
+ parameters: parameters,
99
+ options: scrub_options_for_storage(merged_options),
100
+ job_id: job_id
101
+ )
102
+ rescue StandardError => e
103
+ Foreman::Logging.exception(
104
+ "OpenBolt job #{job_id} launched on proxy #{smart_proxy.name} " \
105
+ "but the Foreman TaskJob row could not be created",
106
+ e
107
+ )
108
+ raise ForemanOpenbolt::Common::PartialLaunchError,
109
+ "Task launched on the proxy (job #{job_id}) but Foreman could not " \
110
+ "record it. The task will run on the proxy unmonitored. Error: #{e.message}"
111
+ end
112
+
113
+ begin
114
+ ForemanTasks.async_task(Actions::ForemanOpenbolt::PollTaskStatus,
115
+ job_id,
116
+ smart_proxy.id)
117
+ rescue StandardError => e
118
+ Foreman::Logging.exception(
119
+ "OpenBolt job #{job_id} launched on proxy #{smart_proxy.name} " \
120
+ "but PollTaskStatus could not be scheduled",
121
+ e
122
+ )
123
+ # Capture before update! flips the in-memory status.
124
+ previous_status = task_job.status
125
+ begin
126
+ task_job.update!(status: 'exception')
127
+ rescue StandardError => update_error
128
+ Foreman::Logging.exception(
129
+ "Could not mark TaskJob #{job_id} as exception after polling-" \
130
+ "schedule failure. Row will remain in '#{previous_status}' state.",
131
+ update_error
132
+ )
133
+ end
134
+ raise ForemanOpenbolt::Common::PartialLaunchError,
135
+ "Task launched on the proxy (job #{job_id}) but background polling " \
136
+ "could not be scheduled. The task will run on the proxy without " \
137
+ "status updates in Foreman. Error: #{e.message}"
138
+ end
139
+
140
+ job_id
141
+ end
142
+ end
143
+ end