Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Initial mess

Marcello Rocha3ae65dbefff9
diff --git a/db/migrate/20231109080454_add_health_info_to_storages.rb b/db/migrate/20231109080454_add_health_info_to_storages.rb
new file mode 100644
index 00000000000..dfa5c4c4077
--- /dev/null
+++ b/db/migrate/20231109080454_add_health_info_to_storages.rb
@@ -0,0 +1,5 @@
+class AddHealthInfoToStorages < ActiveRecord::Migration[7.0]
+ def change
+ add_column :storages, :health_info, :jsonb, default: {}
+ end
+end
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/add_user_to_group_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/add_user_to_group_command.rb
index 8dbc1faa9ea..8e5896573e8 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/add_user_to_group_command.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/add_user_to_group_command.rb
@@ -53,33 +53,36 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
)
)
+ error_data = Storages::StorageErrorData.new(source: self.class, payload: response)
+
case response
when Net::HTTPSuccess
statuscode = Nokogiri::XML(response.body).xpath('/ocs/meta/statuscode').text
+
case statuscode
when "100"
ServiceResult.success(message: "User has been added successfully")
when "101"
- Util.error(:error, "No group specified", response)
+ Util.error(:error, "No group specified", error_data)
when "102"
- Util.error(:error, "Group does not exist", response)
+ Util.error(:error, "Group does not exist", error_data)
when "103"
- Util.error(:error, "User does not exist", response)
+ Util.error(:error, "User does not exist", error_data)
when "104"
- Util.error(:error, "Insufficient privileges", response)
+ Util.error(:error, "Insufficient privileges", error_data)
when "105"
- Util.error(:error, "Failed to add user to group", response)
+ Util.error(:error, "Failed to add user to group", error_data)
end
when Net::HTTPMethodNotAllowed
- Util.error(:not_allowed, 'Outbound request method not allowed', response)
+ Util.error(:not_allowed, 'Outbound request method not allowed', error_data)
when Net::HTTPNotFound
- Util.error(:not_found, 'Outbound request destination not found', response)
+ Util.error(:not_found, 'Outbound request destination not found', error_data)
when Net::HTTPUnauthorized
- Util.error(:unauthorized, 'Outbound request not authorized', response)
+ Util.error(:unauthorized, 'Outbound request not authorized', error_data)
when Net::HTTPConflict
- Util.error(:conflict, Util.error_text_from_response(response), response)
+ Util.error(:conflict, Util.error_text_from_response(response), error_data)
else
- Util.error(:error, 'Outbound request failed', response)
+ Util.error(:error, 'Outbound request failed', error_data)
end
end
# rubocop:enable Metrics/AbcSize
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/create_folder_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/create_folder_command.rb
index e7dcad18f8c..fdbdb811166 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/create_folder_command.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/create_folder_command.rb
@@ -50,6 +50,8 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
Util.basic_auth_header(@username, @password)
)
+ error_data = Storages::StorageErrorData.new(source: self.class, payload: response)
+
case response
when Net::HTTPSuccess
ServiceResult.success(message: 'Folder was successfully created.')
@@ -57,18 +59,19 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
if Util.error_text_from_response(response) == 'The resource you tried to create already exists'
ServiceResult.success(message: 'Folder already exists.')
else
- Util.error(:not_allowed, 'Outbound request method not allowed', response)
+ Util.error(:not_allowed, 'Outbound request method not allowed', error_data)
end
when Net::HTTPNotFound
- Util.error(:not_found, 'Outbound request destination not found', response)
+ Util.error(:not_found, 'Outbound request destination not found', error_data)
when Net::HTTPUnauthorized
- Util.error(:unauthorized, 'Outbound request not authorized', response)
+ Util.error(:unauthorized, 'Outbound request not authorized', error_data)
when Net::HTTPConflict
- Util.error(:conflict, Util.error_text_from_response(response), response)
+ Util.error(:conflict, Util.error_text_from_error_data(error_data), error_data)
else
- Util.error(:error, 'Outbound request failed', response)
+ Util.error(:error, 'Outbound request failed', error_data)
end
end
+
# rubocop:enable Metrics/AbcSize
end
end
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/group_users_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/group_users_query.rb
index 2a7a612976e..92e63054a8f 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/group_users_query.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/group_users_query.rb
@@ -48,6 +48,9 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
Util.join_uri_path(@uri.path, "ocs/v1.php/cloud/groups", CGI.escapeURIComponent(group)),
Util.basic_auth_header(@username, @password).merge('OCS-APIRequest' => 'true')
)
+
+ error_data = Storages::StorageErrorData.new(source: self.class, payload: response)
+
case response
when Net::HTTPSuccess
group_users = Nokogiri::XML(response.body)
@@ -55,15 +58,15 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
.map(&:text)
ServiceResult.success(result: group_users)
when Net::HTTPMethodNotAllowed
- Util.error(:not_allowed, 'Outbound request method not allowed', response)
+ Util.error(:not_allowed, 'Outbound request method not allowed', error_data)
when Net::HTTPNotFound
- Util.error(:not_found, 'Outbound request destination not found', response)
+ Util.error(:not_found, 'Outbound request destination not found', error_data)
when Net::HTTPUnauthorized
- Util.error(:unauthorized, 'Outbound request not authorized', response)
+ Util.error(:unauthorized, 'Outbound request not authorized', error_data)
when Net::HTTPConflict
- Util.error(:conflict, Util.error_text_from_response(response), response)
+ Util.error(:conflict, Util.error_text_from_response(response), error_data)
else
- Util.error(:error, 'Outbound request failed', response)
+ Util.error(:error, 'Outbound request failed', error_data)
end
end
# rubocop:enable Metrics/AbcSize
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/internal/propfind_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/internal/propfind_query.rb
index 9855eac583f..866e11fca73 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/internal/propfind_query.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/internal/propfind_query.rb
@@ -101,6 +101,8 @@ module Storages::Peripherals::StorageInteraction::Nextcloud::Internal
UTIL.basic_auth_header(@username, @password).merge('Depth' => depth)
)
+ error_data = Storages::StorageErrorData.new(source: self.class, payload: response)
+
case response
when Net::HTTPSuccess
doc = Nokogiri::XML response.body
@@ -120,13 +122,13 @@ module Storages::Peripherals::StorageInteraction::Nextcloud::Internal
ServiceResult.success(result:)
when Net::HTTPMethodNotAllowed
- UTIL.error(:not_allowed, 'Outbound request method not allowed', response)
+ UTIL.error(:not_allowed, 'Outbound request method not allowed', error_data)
when Net::HTTPNotFound
- UTIL.error(:not_found, 'Outbound request destination not found', response)
+ UTIL.error(:not_found, 'Outbound request destination not found', error_data)
when Net::HTTPUnauthorized
- UTIL.error(:unauthorized, 'Outbound request not authorized', response)
+ UTIL.error(:unauthorized, 'Outbound request not authorized', error_data)
else
- UTIL.error(:error, 'Outbound request failed', response)
+ UTIL.error(:error, 'Outbound request failed', error_data)
end
end
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/remove_user_from_group_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/remove_user_from_group_command.rb
index 2544d0c6315..06bb0daf0ff 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/remove_user_from_group_command.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/remove_user_from_group_command.rb
@@ -53,6 +53,8 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
)
)
+ error_data = Storages::StorageErrorData.new(source: self.class, payload: response)
+
case response
when Net::HTTPSuccess
statuscode = Nokogiri::XML(response.body).xpath('/ocs/meta/statuscode').text
@@ -60,27 +62,27 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
when "100"
ServiceResult.success(message: "User has been removed from group")
when "101"
- Util.error(:error, "No group specified", response)
+ Util.error(:error, "No group specified", error_data)
when "102"
- Util.error(:error, "Group does not exist", response)
+ Util.error(:error, "Group does not exist", error_data)
when "103"
- Util.error(:error, "User does not exist", response)
+ Util.error(:error, "User does not exist", error_data)
when "104"
- Util.error(:error, "Insufficient privileges", response)
+ Util.error(:error, "Insufficient privileges", error_data)
when "105"
message = Nokogiri::XML(response.body).xpath('/ocs/meta/message').text
- Util.error(:error, "Failed to remove user #{user} from group #{group}: #{message}", response)
+ Util.error(:error, "Failed to remove user #{user} from group #{group}: #{message}", error_data)
end
when Net::HTTPMethodNotAllowed
- Util.error(:not_allowed, 'Outbound request method not allowed', response)
+ Util.error(:not_allowed, 'Outbound request method not allowed', error_data)
when Net::HTTPNotFound
- Util.error(:not_found, 'Outbound request destination not found', response)
+ Util.error(:not_found, 'Outbound request destination not found', error_data)
when Net::HTTPUnauthorized
- Util.error(:unauthorized, 'Outbound request not authorized', response)
+ Util.error(:unauthorized, 'Outbound request not authorized', error_data)
when Net::HTTPConflict
- Util.error(:conflict, Util.error_text_from_response(response), response)
+ Util.error(:conflict, Util.error_text_from_response(response), error_data)
else
- Util.error(:error, 'Outbound request failed', response)
+ Util.error(:error, 'Outbound request failed', error_data)
end
end
# rubocop:enable Metrics/AbcSize
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/rename_file_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/rename_file_command.rb
index 6ce8e83e521..f4e85a078b5 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/rename_file_command.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/rename_file_command.rb
@@ -51,15 +51,17 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
)
)
+ error_data = Storages::StorageErrorData.new(source: self.class, payload: response)
+
case response
when Net::HTTPSuccess
ServiceResult.success
when Net::HTTPNotFound
- Util.error(:not_found, 'Outbound request destination not found', response)
+ Util.error(:not_found, 'Outbound request destination not found', error_data)
when Net::HTTPUnauthorized
- Util.error(:unauthorized, 'Outbound request not authorized', response)
+ Util.error(:unauthorized, 'Outbound request not authorized', error_data)
else
- Util.error(:error, 'Outbound request failed', response)
+ Util.error(:error, 'Outbound request failed', error_data)
end
end
end
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/set_permissions_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/set_permissions_command.rb
index b70da235296..5de94706e7d 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/set_permissions_command.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/set_permissions_command.rb
@@ -88,20 +88,22 @@ module Storages::Peripherals::StorageInteraction::Nextcloud
Util.basic_auth_header(@username, @password)
)
+ error_data = Storages::StorageErrorData.new(source: self.class, payload: response)
+
case response
when Net::HTTPSuccess
doc = Nokogiri::XML(response.body)
if doc.xpath("/d:multistatus/d:response/d:propstat[d:status[text() = 'HTTP/1.1 200 OK']]/d:prop/nc:acl-list").present?
ServiceResult.success(result: :success)
else
- Util.error(:error, "nc:acl properly has not been set for #{path}")
+ Util.error(:error, "nc:acl properly has not been set for #{path}", error_data)
end
when Net::HTTPNotFound
- Util.error(:not_found, 'Outbound request destination not found', response)
+ Util.error(:not_found, 'Outbound request destination not found', error_data)
when Net::HTTPUnauthorized
- Util.error(:unauthorized, 'Outbound request not authorized', response)
+ Util.error(:unauthorized, 'Outbound request not authorized', error_data)
else
- Util.error(:error, 'Outbound request failed', response)
+ Util.error(:error, 'Outbound request failed', error_data)
end
end
# rubocop:enable Metrics/AbcSize
diff --git a/modules/storages/app/models/storages/nextcloud_storage.rb b/modules/storages/app/models/storages/nextcloud_storage.rb
index 06451b2beb7..e46b7dcc137 100644
--- a/modules/storages/app/models/storages/nextcloud_storage.rb
+++ b/modules/storages/app/models/storages/nextcloud_storage.rb
@@ -41,20 +41,7 @@ module Storages
store_attribute :provider_fields, :group, :string
store_attribute :provider_fields, :group_folder, :string
- def self.sync_all_group_folders
- # Returns false if lock cannot be acquired, block is not executed then.
- OpenProject::Mutex.with_advisory_lock(self,
- 'sync_all_group_folders',
- timeout_seconds: 0,
- transaction: false) do
- where("provider_fields->>'automatically_managed' = 'true'")
- .includes(:oauth_client)
- .find_each do |storage|
- GroupFolderPropertiesSyncService.new(storage).call
- end
- true
- end
- end
+ scope :automatically_managed, -> { where("provider_fields->>'automatically_managed' = 'true'") }
def oauth_configuration
Peripherals::OAuthConfigurations::NextcloudConfiguration.new(self)
@@ -78,6 +65,26 @@ module Storages
end
end
+ def mark_as_unhealthy(reason: nil)
+ return true if unhealthy?
+
+ update(health_status: :unhealthy, health_changed_at: Time.now.utc, health_reason: reason)
+ end
+
+ def mark_as_healthy
+ return true if unhealthy?
+
+ update(health_status: :ok, health_changed_at: Time.now.utc, health_reason: nil)
+ end
+
+ def healthy?
+ health_status == 'ok'
+ end
+
+ def unhealthy?
+ not healthy?
+ end
+
def provider_fields_defaults
PROVIDER_FIELDS_DEFAULTS
end
diff --git a/modules/storages/app/models/storages/storage.rb b/modules/storages/app/models/storages/storage.rb
index eba093b7e58..8572139c9e3 100644
--- a/modules/storages/app/models/storages/storage.rb
+++ b/modules/storages/app/models/storages/storage.rb
@@ -61,6 +61,10 @@ module Storages
has_one :oauth_client, as: :integration, dependent: :destroy
has_one :oauth_application, class_name: '::Doorkeeper::Application', as: :integration, dependent: :destroy
+ store_attribute :health_info, :status, :string, prefix: :health
+ store_attribute :health_info, :changed_at, :datetime, prefix: :health
+ store_attribute :health_info, :reason, :string, prefix: :health
+
PROVIDER_TYPES = [
PROVIDER_TYPE_NEXTCLOUD = 'Storages::NextcloudStorage',
PROVIDER_TYPE_ONE_DRIVE = 'Storages::OneDriveStorage'
diff --git a/modules/storages/app/services/storages/group_folder_properties_sync_service.rb b/modules/storages/app/services/storages/group_folder_properties_sync_service.rb
index c305f0a9773..89686997be6 100644
--- a/modules/storages/app/services/storages/group_folder_properties_sync_service.rb
+++ b/modules/storages/app/services/storages/group_folder_properties_sync_service.rb
@@ -46,12 +46,20 @@ module Storages
ALL_PERMISSIONS = PERMISSIONS_MAP.values.sum
NO_PERMISSIONS = 0
+ def self.call(storage)
+ new(storage).call
+ end
+
def initialize(storage)
@storage = storage
end
def call
- prepare_remote_folders and apply_permissions_to_folders
+ # We can return the collected errors
+ prepare_remote_folders.error_and { |error| return ServiceResult.failure(errors: error) }
+
+ # We need to make this into a ServiceResult
+ apply_permissions_to_folders.error_and { |error| return ServiceResult.failure(errors: error) }
end
private
@@ -59,27 +67,19 @@ module Storages
# rubocop:disable Metrics/AbcSize
def prepare_remote_folders
remote_folders = remote_root_folder_properties.result_or do |error|
- error_msg = { command: 'nextcloud.file_ids',
- folder: @storage.group_folder,
- message: error.log_message,
- data: { status: error.data.code, body: error.data.body } }.to_json
+ format_and_log_error(error, { folder: @storage.group_folder })
- raise error_msg if error.code == :error
-
- return OpenProject.logger.warn error_msg
+ # This hides the folder, but it will be in the logs
+ return ServiceResult.failure(errors: error)
end
- ensure_root_folder_permissions.error_and do |error|
- error_msg = { command: 'nextcloud.set_permissions',
- folder: @storage.group_folder,
- message: error.log_message,
- data: { status: error.data.code, body: error.data.body } }.to_json
- raise error_msg if error.code == :error
+ ensure_root_folder_permissions.on_failure do |service_result|
+ format_and_log_error(service_result.errors, { folder: @storage.group_folder })
- return OpenProject.logger.warn(error_msg)
+ return service_result
end
- ensure_folders_exist(remote_folders) and hide_inactive_folders(remote_folders)
+ ensure_folders_exist(remote_folders).on_success { hide_inactive_folders(remote_folders) }
end
def apply_permissions_to_folders
@@ -90,35 +90,27 @@ module Storages
end
add_remove_users_to_group
+
+ ServiceResult.success
end
def add_remove_users_to_group
remote_users = remote_group_users.result_or do |error|
- return OpenProject.logger.warn({ command: 'nextcloud.group_users',
- group: @storage.group,
- message: error.log_message,
- data: { status: error.data.code, body: error.data.body } }.to_json)
+ return format_and_log_error(error, group: @storage.group)
+ # ServiceResult.failure(errors: error)
end
local_users = client_tokens_scope.order(:id).pluck(:origin_user_id)
(remote_users - local_users - [@storage.username]).each do |user|
- remove_user_from_remote_group(user).result_or do |error|
- OpenProject.logger.warn({ command: 'nextcloud.remove_user_from_group',
- group: @storage.group,
- user:,
- message: error.log_message,
- data: { status: error.data.code, body: error.data.body } }.to_json)
+ remove_user_from_remote_group(user).error_and do |error|
+ format_and_log_error(error, group: @storage.group, user:)
end
end
(local_users - remote_users - [@storage.username]).each do |user|
- add_user_to_remote_group(user).result_or do |error|
- OpenProject.logger.warn({ command: 'nextcloud.add_users_to_group',
- group: @storage.group,
- user:,
- message: error.log_message,
- data: { status: error.data.code, body: error.data.body } }.to_json)
+ add_user_to_remote_group(user).error_and do |error|
+ format_and_log_error(error, group: @storage.group, user:)
end
end
end
@@ -158,10 +150,7 @@ module Storages
.resolve("commands.nextcloud.set_permissions")
.call(storage: @storage, **command_params)
.result_or do |error|
- OpenProject.logger.warn({ command: 'nextcloud.set_permissions',
- folder: project_storage.project_folder_path,
- message: error.log_message,
- data: { status: error.data.code, body: error.data.body } }.to_json)
+ format_and_log_error(error, folder: project_storage.project_folder_path)
end
end
@@ -191,11 +180,8 @@ module Storages
Peripherals::Registry
.resolve("commands.nextcloud.set_permissions")
.call(storage: @storage, **command_params)
- .result_or do |error|
- OpenProject.logger.warn({ command: 'nextcloud.set_permissions',
- folder: path,
- message: error.log_message,
- data: { status: error.data.code, body: error.data.body } }.to_json)
+ .on_failure do |service_result|
+ format_and_log_error(service_result.errors, folder: path, context: 'hide_folder')
end
end
end
@@ -207,21 +193,20 @@ module Storages
next create_folder(project_storage) unless id_folder_map.key?(project_storage.project_folder_id)
current_path = id_folder_map[project_storage.project_folder_id]
- if current_path == project_storage.project_folder_path
- project_storage.project_folder_id
- else
- rename_folder(project_storage, current_path)
- .result_or do |error|
- error_msg = { command: 'nextcloud.rename_file',
- source: current_path,
- target: project_storage.project_folder_path,
- data: { status: error.data.code, body: error.data.body } }.to_json
+ if current_path != project_storage.project_folder_path
+ rename_folder(project_storage, current_path).on_failure do |service_result|
+ format_and_log_error(service_result.errors,
+ source: current_path,
+ target: project_storage.project_folder_path)
# we need to stop as this would mess with the other processes
- return OpenProject.logger.warn error_msg
+ return service_result
end
end
end
+
+ # We processed every folder successfully
+ ServiceResult.success
end
def rename_folder(project_storage, current_name)
@@ -236,21 +221,17 @@ module Storages
.resolve("commands.nextcloud.create_folder")
.call(storage: @storage, folder_path:)
.result_or do |error|
- error_msg = { command: 'nextcloud.create_folder',
- folder: folder_path,
- data: { status: error.data.code, body: error.data.body } }.to_json
+ format_and_log_error(error, folder: folder_path)
- return OpenProject.logger.warn(error_msg)
+ return ServiceResult.failure(errors: error)
end
folder_id = Peripherals::Registry
.resolve('queries.nextcloud.file_ids')
.call(storage: @storage, path: folder_path)
.result_or do |error|
- return OpenProject.logger.warn({ command: 'nextcloud.file_ids',
- path:,
- message: error.log_message,
- data: { status: error.data.code, body: error.data.body } }.to_json)
+ format_and_log_error(error, path:)
+ ServiceResult.failure(errors: error)
end
project_storage.update(project_folder_id: folder_id.dig(folder_path, 'fileid'))
@@ -302,5 +283,13 @@ module Storages
def admin_client_tokens_scope
OAuthClientToken.where(oauth_client: @storage.oauth_client, user: User.admin.active)
end
+
+ def format_and_log_error(error, context = {})
+ error_message = context.merge({ command: error.data.source,
+ message: error.log_message,
+ data: { status: error.data.payload.code, body: error.data.payload.body } })
+
+ OpenProject.logger.warn error_message.to_json
+ end
end
end
diff --git a/modules/storages/app/workers/storages/manage_nextcloud_integration_cron_job.rb b/modules/storages/app/workers/storages/manage_nextcloud_integration_cron_job.rb
index 9bae7389044..0d9bfcd052e 100644
--- a/modules/storages/app/workers/storages/manage_nextcloud_integration_cron_job.rb
+++ b/modules/storages/app/workers/storages/manage_nextcloud_integration_cron_job.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2023 the OpenProject GmbH
@@ -26,14 +28,25 @@
# See COPYRIGHT and LICENSE files for more details.
#++
-class Storages::ManageNextcloudIntegrationCronJob < Cron::CronJob
- using ::Storages::Peripherals::ServiceResultRefinements
+module Storages
+ class ManageNextcloudIntegrationCronJob < Cron::CronJob
+ using Peripherals::ServiceResultRefinements
- queue_with_priority :low
+ queue_with_priority :low
- self.cron_expression = '*/5 * * * *'
+ self.cron_expression = '*/5 * * * *'
- def perform
- Storages::NextcloudStorage.sync_all_group_folders
+ def perform
+ OpenProject::Mutex.with_advisory_lock(NextcloudStorage, 'sync_all_group_folders', timeout_seconds: 0, transaction: false) do
+ NextcloudStorage.automatically_managed.includes(:oauth_client).find_each do |storage|
+ result = GroupFolderPropertiesSyncService.call(storage)
+ result.error_and do |error_messages|
+ # Sample code
+ storage.mark_as_unhealthy(reason: error_messages.first[:log_message])
+ end
+ end
+ true
+ end
+ end
end
end
diff --git a/modules/storages/spec/models/nextcloud_storage_spec.rb b/modules/storages/spec/models/nextcloud_storage_spec.rb
index 25a03819a16..7f1662f8153 100644
--- a/modules/storages/spec/models/nextcloud_storage_spec.rb
+++ b/modules/storages/spec/models/nextcloud_storage_spec.rb
@@ -42,6 +42,42 @@ RSpec.describe Storages::NextcloudStorage do
it { expect(storage).not_to be_a_provider_type_one_drive }
end
+ describe '#mark_as_unhealthy' do
+ it 'records the time at which it became unhealthy' do
+ Timecop.freeze('2023-03-14T15:17:00Z') do
+ expect { storage.mark_as_unhealthy }.to change(storage, :health_changed_at).to(Time.now.utc)
+ end
+ end
+
+ it 'sets the health_status as unhealthy' do
+ expect { storage.mark_as_unhealthy }.to change(storage, :health_status).to('unhealthy')
+ end
+
+ it 'sets a reason if provided' do
+ expect do
+ storage.mark_as_unhealthy(reason: 'thou_shall_not_pass_error')
+ end.to change(storage, :health_reason).to('thou_shall_not_pass_error')
+ end
+ end
+
+ describe '#mark_as_healthy' do
+ before { storage.mark_as_unhealthy(reason: 'just nope') }
+
+ it 'clears the unhealthy_since value' do
+ Timecop.freeze('2023-04-05T06:07:08.009Z') do
+ expect { storage.mark_as_healthy }.to change(storage, :health_changed_at).to(Time.now.utc)
+ end
+ end
+
+ it 'sets the health_status to ok' do
+ expect { storage.mark_as_healthy }.to change(storage, :health_status).to('ok')
+ end
+
+ it 'clears the health_reason' do
+ expect { storage.mark_as_healthy }.to change(storage, :health_reason).to(nil)
+ end
+ end
+
describe '#configured?' do
context 'with a complete configuration' do
let(:storage) do
@@ -129,41 +165,6 @@ RSpec.describe Storages::NextcloudStorage do
end
end
- describe '.sync_all_group_folders' do
- subject { described_class.sync_all_group_folders }
-
- context 'when lock is free' do
- it 'responds with true' do
- expect(subject).to be(true)
- end
-
- it 'calls GroupFolderPropertiesSyncService for each appropriate storage' do
- storage1 = create(:nextcloud_storage, :as_automatically_managed)
- storage2 = create(:nextcloud_storage, :as_not_automatically_managed)
-
- allow(Storages::GroupFolderPropertiesSyncService).to receive(:new).and_call_original
- allow_any_instance_of(Storages::GroupFolderPropertiesSyncService).to receive(:call).and_return(nil) # rubocop:disable RSpec/AnyInstance
-
- expect(subject).to be(true)
- expect(Storages::GroupFolderPropertiesSyncService).to have_received(:new).with(storage1).once
- expect(Storages::GroupFolderPropertiesSyncService).not_to have_received(:new).with(storage2)
- end
- end
-
- context 'when lock is unfree' do
- it 'responds with false' do
- allow(ApplicationRecord).to receive(:with_advisory_lock).and_return(false)
-
- expect(subject).to be(false)
- expect(ApplicationRecord).to have_received(:with_advisory_lock).with(
- 'sync_all_group_folders',
- timeout_seconds: 0,
- transaction: false
- ).once
- end
- end
- end
-
describe '#username' do
it_behaves_like 'a stored attribute with default value', :username, 'OpenProject'
end
diff --git a/modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rb b/modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rb
index 8b90637ed37..6f29ab80e5b 100644
--- a/modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rb
+++ b/modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rb
@@ -657,12 +657,18 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, :webmock do
described_class.new(storage).call
expect(OpenProject.logger).to have_received(:warn) do |msg, _|
- expect(msg).to eq({ command: 'nextcloud.file_ids',
- folder: 'OpenProject',
- message: 'Outbound request destination not found',
- data: { status: "404", body: '' } }.to_json)
+ expect(parse_error_msg(msg))
+ .to eq({ command: 'Storages::Peripherals::StorageInteraction::Nextcloud::Internal::PropfindQuery',
+ folder: 'OpenProject',
+ message: 'Outbound request destination not found',
+ data: { status: "404", body: '' } })
end
end
+
+ it 'returns a failure' do
+ result = described_class.new(storage).call
+ expect(result).to be_failure
+ end
end
it 'raises an error when dealing with an unhandled error case' do
@@ -675,7 +681,7 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, :webmock do
}
).to_return(status: 500, body: "", headers: {})
- expect { described_class.new(storage).call }.to raise_error RuntimeError
+ expect(described_class.new(storage).call).to be_failure
end
end
@@ -701,25 +707,14 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, :webmock do
described_class.new(storage).call
expect(OpenProject.logger).to have_received(:warn) do |msg, _|
- expect(msg).to eq({ command: 'nextcloud.set_permissions',
- folder: 'OpenProject',
- message: 'Outbound request not authorized',
- data: { status: '401', body: 'Heute nicht' } }.to_json)
+ expect(parse_error_msg(msg))
+ .to eq({ command: 'Storages::Peripherals::StorageInteraction::Nextcloud::SetPermissionsCommand',
+ folder: 'OpenProject',
+ message: 'Outbound request not authorized',
+ data: { status: '401', body: 'Heute nicht' } })
end
end
end
-
- it 'raises an error in case of an unhandled error case' do
- request_stubs[1] = stub_request(:proppatch, "#{storage.host}/remote.php/dav/files/OpenProject/OpenProject")
- .with(
- body: root_folder_set_permissions_request_body,
- headers: {
- 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg='
- }
- ).to_return(status: 500, body: 'this is a failure', headers: {})
-
- expect { described_class.new(storage).call }.to raise_error RuntimeError
- end
end
context 'when folder creation fails' do
@@ -748,9 +743,11 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, :webmock do
described_class.new(storage).call
expect(OpenProject.logger).to have_received(:warn) do |msg|
- expect(msg).to eq({ command: 'nextcloud.create_folder',
- folder: "OpenProject/[Sample] Project Name | Ehuu (#{project1.id})/",
- data: { status: '404', body: '' } }.to_json)
+ expect(parse_error_msg(msg))
+ .to eq({ command: 'Storages::Peripherals::StorageInteraction::Nextcloud::CreateFolderCommand',
+ message: 'Outbound request destination not found',
+ folder: "OpenProject/[Sample] Project Name | Ehuu (#{project1.id})/",
+ data: { status: '404', body: '' } })
end
end
end
@@ -778,10 +775,12 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, :webmock do
described_class.new(storage).call
expect(OpenProject.logger).to have_received(:warn) do |msg, _|
- expect(msg).to eq({ command: 'nextcloud.rename_file',
- source: "OpenProject/Lost Jedi Project Folder #3/",
- target: project_storage2.project_folder_path,
- data: { status: '404', body: '' } }.to_json)
+ expect(parse_error_msg(msg))
+ .to eq({ command: 'Storages::Peripherals::StorageInteraction::Nextcloud::RenameFileCommand',
+ message: 'Outbound request destination not found',
+ source: "OpenProject/Lost Jedi Project Folder #3/",
+ target: project_storage2.project_folder_path,
+ data: { status: '404', body: '' } })
end
end
end
@@ -809,10 +808,12 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, :webmock do
described_class.new(storage).call
expect(OpenProject.logger).to have_received(:warn) do |msg|
- expect(msg).to eq({ command: 'nextcloud.set_permissions',
- folder: 'OpenProject/Lost Jedi Project Folder #2/',
- message: 'Outbound request failed',
- data: { status: '500', body: 'A server error occurred' } }.to_json)
+ expect(parse_error_msg(msg))
+ .to eq({ command: 'Storages::Peripherals::StorageInteraction::Nextcloud::SetPermissionsCommand',
+ context: 'hide_folder',
+ folder: 'OpenProject/Lost Jedi Project Folder #2/',
+ message: 'Outbound request failed',
+ data: { status: '500', body: 'A server error occurred' } })
end
end
end
@@ -840,11 +841,12 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, :webmock do
described_class.new(storage).call
expect(OpenProject.logger).to have_received(:warn) do |msg|
- expect(msg).to eq({ command: 'nextcloud.set_permissions',
- folder: "OpenProject/Jedi Project Folder ||| (#{project2.id})/",
- message: 'Outbound request failed',
- data: { status: '500',
- body: 'Divide by cucumber error. Please reinstall universe and reboot.' } }.to_json)
+ expect(parse_error_msg(msg))
+ .to eq({ command: 'Storages::Peripherals::StorageInteraction::Nextcloud::SetPermissionsCommand',
+ folder: "OpenProject/Jedi Project Folder ||| (#{project2.id})/",
+ message: 'Outbound request failed',
+ data: { status: '500',
+ body: 'Divide by cucumber error. Please reinstall universe and reboot.' } })
end
end
end
@@ -872,11 +874,12 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, :webmock do
described_class.new(storage).call
expect(OpenProject.logger).to have_received(:warn) do |msg|
- expect(msg).to eq({ command: 'nextcloud.add_users_to_group',
- group: 'OpenProject',
- user: 'Obi-Wan',
- message: 'Outbound request failed',
- data: { status: '302', body: '' } }.to_json)
+ expect(parse_error_msg(msg))
+ .to eq({ command: 'Storages::Peripherals::StorageInteraction::Nextcloud::AddUserToGroupCommand',
+ group: 'OpenProject',
+ user: 'Obi-Wan',
+ message: 'Outbound request failed',
+ data: { status: '302', body: '' } })
end
end
end
@@ -907,12 +910,13 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, :webmock do
described_class.new(storage).call
expect(OpenProject.logger).to have_received(:warn) do |msg, _|
- expect(msg).to eq({ command: 'nextcloud.remove_user_from_group',
- group: 'OpenProject',
- user: 'Darth Maul',
- message: "Failed to remove user Darth Maul from group OpenProject: " \
- "Not viable to remove user from the last group you are SubAdmin of",
- data: { status: '200', body: remove_user_from_group_response } }.to_json)
+ expect(parse_error_msg(msg))
+ .to eq({ command: 'Storages::Peripherals::StorageInteraction::Nextcloud::RemoveUserFromGroupCommand',
+ group: 'OpenProject',
+ user: 'Darth Maul',
+ message: "Failed to remove user Darth Maul from group OpenProject: " \
+ "Not viable to remove user from the last group you are SubAdmin of",
+ data: { status: '200', body: remove_user_from_group_response } })
end
end
end
@@ -1121,5 +1125,9 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, :webmock do
body: propfind_request_body
).to_return(status: 200, body: propfind_response_body3, headers: {})
end
+
+ def parse_error_msg(msg)
+ MultiJson.load(msg, symbolize_keys: true)
+ end
end
end
diff --git a/modules/storages/spec/workers/storages/manage_nextcloud_integration_cron_job_spec.rb b/modules/storages/spec/workers/storages/manage_nextcloud_integration_cron_job_spec.rb
index 5307e996b57..96d8b9ff990 100644
--- a/modules/storages/spec/workers/storages/manage_nextcloud_integration_cron_job_spec.rb
+++ b/modules/storages/spec/workers/storages/manage_nextcloud_integration_cron_job_spec.rb
@@ -36,17 +36,38 @@ RSpec.describe Storages::ManageNextcloudIntegrationCronJob, type: :job do
expect(described_class.cron_expression).to eq('*/5 * * * *')
end
- describe '#perform' do
+ describe '.sync_all_group_folders' do
subject { described_class.new.perform }
- it 'works out silently' do
- allow(Storages::NextcloudStorage).to receive(:sync_all_group_folders).and_return(true)
- subject
+ context 'when lock is free' do
+ it 'responds with true' do
+ expect(subject).to be(true)
+ end
+
+ it 'calls GroupFolderPropertiesSyncService for each appropriate storage' do
+ storage1 = create(:nextcloud_storage, :as_automatically_managed)
+ storage2 = create(:nextcloud_storage, :as_not_automatically_managed)
+
+ allow(Storages::GroupFolderPropertiesSyncService).to receive(:call).and_call_original
+
+ expect(subject).to be(true)
+
+ expect(Storages::GroupFolderPropertiesSyncService).to have_received(:call).with(storage1).once
+ expect(Storages::GroupFolderPropertiesSyncService).not_to have_received(:call).with(storage2)
+ end
end
- it 'works out silently without doing anything when sync has been started by another process' do
- allow(Storages::NextcloudStorage).to receive(:sync_all_group_folders).and_return(false)
- subject
+ context 'when lock is unfree' do
+ it 'responds with false' do
+ allow(ApplicationRecord).to receive(:with_advisory_lock).and_return(false)
+
+ expect(subject).to be(false)
+ expect(ApplicationRecord).to have_received(:with_advisory_lock).with(
+ 'sync_all_group_folders',
+ timeout_seconds: 0,
+ transaction: false
+ ).once
+ end
end
end
end