debian-mirror-gitlab/lib/gitlab/shell.rb

434 lines
13 KiB
Ruby
Raw Normal View History

2018-12-13 13:39:08 +05:30
# frozen_string_literal: true
2018-11-08 19:23:39 +05:30
# Gitaly note: SSH key operations are not part of Gitaly so will never be migrated.
2017-09-10 17:25:29 +05:30
2016-08-24 12:49:21 +05:30
require 'securerandom'
2014-09-02 18:07:02 +05:30
module Gitlab
class Shell
2017-09-10 17:25:29 +05:30
GITLAB_SHELL_ENV_VARS = %w(GIT_TERMINAL_PROMPT).freeze
2017-08-17 22:00:37 +05:30
Error = Class.new(StandardError)
2014-09-02 18:07:02 +05:30
2015-12-23 02:04:40 +05:30
KeyAdder = Struct.new(:io) do
2014-09-02 18:07:02 +05:30
def add_key(id, key)
2016-09-29 09:46:39 +05:30
key = Gitlab::Shell.strip_key(key)
# Newline and tab are part of the 'protocol' used to transmit id+key to the other end
if key.include?("\t") || key.include?("\n")
raise Error.new("Invalid key: #{key.inspect}")
end
2015-10-24 18:46:33 +05:30
io.puts("#{id}\t#{key}")
2014-09-02 18:07:02 +05:30
end
end
2015-04-26 12:48:37 +05:30
class << self
2016-11-03 12:29:30 +05:30
def secret_token
@secret_token ||= begin
File.read(Gitlab.config.gitlab_shell.secret_file).chomp
end
end
def ensure_secret_token!
return if File.exist?(File.join(Gitlab.config.gitlab_shell.path, '.gitlab_shell_secret'))
generate_and_link_secret_token
end
2015-04-26 12:48:37 +05:30
def version_required
2017-09-10 17:25:29 +05:30
@version_required ||= File.read(Rails.root
.join('GITLAB_SHELL_VERSION')).strip
2015-04-26 12:48:37 +05:30
end
2016-09-29 09:46:39 +05:30
def strip_key(key)
2017-08-17 22:00:37 +05:30
key.split(/[ ]+/)[0, 2].join(' ')
2016-09-29 09:46:39 +05:30
end
2016-11-03 12:29:30 +05:30
private
# Create (if necessary) and link the secret token file
def generate_and_link_secret_token
secret_file = Gitlab.config.gitlab_shell.secret_file
shell_path = Gitlab.config.gitlab_shell.path
unless File.size?(secret_file)
# Generate a new token of 16 random hexadecimal characters and store it in secret_file.
@secret_token = SecureRandom.hex(16)
File.write(secret_file, @secret_token)
end
link_path = File.join(shell_path, '.gitlab_shell_secret')
if File.exist?(shell_path) && !File.exist?(link_path)
FileUtils.symlink(secret_file, link_path)
end
end
2015-04-26 12:48:37 +05:30
end
2014-09-02 18:07:02 +05:30
# Init new repository
#
2018-10-15 14:42:47 +05:30
# storage - the shard key
2018-03-17 18:26:18 +05:30
# name - project disk path
2014-09-02 18:07:02 +05:30
#
# Ex.
2018-10-15 14:42:47 +05:30
# create_repository("default", "gitlab/gitlab-ci")
2014-09-02 18:07:02 +05:30
#
2018-05-09 12:01:36 +05:30
def create_repository(storage, name)
2018-03-17 18:26:18 +05:30
relative_path = name.dup
relative_path << '.git' unless relative_path.end_with?('.git')
2018-11-18 11:00:15 +05:30
repository = Gitlab::Git::Repository.new(storage, relative_path, '')
wrapped_gitaly_errors { repository.gitaly_repository_client.create_repository }
true
2018-05-09 12:01:36 +05:30
rescue => err # Once the Rugged codes gets removes this can be improved
2018-03-17 18:26:18 +05:30
Rails.logger.error("Failed to add repository #{storage}/#{name}: #{err}")
false
2014-09-02 18:07:02 +05:30
end
# Import repository
#
2018-05-09 12:01:36 +05:30
# storage - project's storage name
2018-03-17 18:26:18 +05:30
# name - project disk path
# url - URL to import from
2014-09-02 18:07:02 +05:30
#
# Ex.
2018-05-09 12:01:36 +05:30
# import_repository("nfs-file06", "gitlab/gitlab-ci", "https://gitlab.com/gitlab-org/gitlab-test.git")
2014-09-02 18:07:02 +05:30
#
2016-08-24 12:49:21 +05:30
def import_repository(storage, name, url)
2018-03-17 18:26:18 +05:30
if url.start_with?('.', '/')
raise Error.new("don't use disk paths with import_repository: #{url.inspect}")
end
2018-11-08 19:23:39 +05:30
relative_path = "#{name}.git"
2018-11-18 11:00:15 +05:30
cmd = GitalyGitlabProjects.new(storage, relative_path)
2018-03-17 18:26:18 +05:30
2018-11-08 19:23:39 +05:30
success = cmd.import_project(url, git_timeout)
2018-03-17 18:26:18 +05:30
raise Error, cmd.output unless success
success
2017-08-17 22:00:37 +05:30
end
2018-03-17 18:26:18 +05:30
# Move repository reroutes to mv_directory which is an alias for
# mv_namespace. Given the underlying implementation is a move action,
# indescriminate of what the folders might be.
#
2016-08-24 12:49:21 +05:30
# storage - project's storage path
2018-03-17 18:26:18 +05:30
# path - project disk path
# new_path - new project disk path
2014-09-02 18:07:02 +05:30
#
# Ex.
2016-08-24 12:49:21 +05:30
# mv_repository("/path/to/storage", "gitlab/gitlab-ci", "randx/gitlab-ci-new")
def mv_repository(storage, path, new_path)
2018-03-17 18:26:18 +05:30
return false if path.empty? || new_path.empty?
!!mv_directory(storage, "#{path}.git", "#{new_path}.git")
2014-09-02 18:07:02 +05:30
end
2018-03-17 18:26:18 +05:30
# Fork repository to new path
2018-05-09 12:01:36 +05:30
# forked_from_storage - forked-from project's storage name
# forked_from_disk_path - project disk relative path
# forked_to_storage - forked-to project's storage name
# forked_to_disk_path - forked project disk relative path
2014-09-02 18:07:02 +05:30
#
# Ex.
2018-05-09 12:01:36 +05:30
# fork_repository("nfs-file06", "gitlab/gitlab-ci", "nfs-file07", "new-namespace/gitlab-ci")
2018-03-17 18:26:18 +05:30
def fork_repository(forked_from_storage, forked_from_disk_path, forked_to_storage, forked_to_disk_path)
2018-11-08 19:23:39 +05:30
forked_from_relative_path = "#{forked_from_disk_path}.git"
fork_args = [forked_to_storage, "#{forked_to_disk_path}.git"]
GitalyGitlabProjects.new(forked_from_storage, forked_from_relative_path).fork_repository(*fork_args)
2014-09-02 18:07:02 +05:30
end
2018-03-17 18:26:18 +05:30
# Removes a repository from file system, using rm_diretory which is an alias
# for rm_namespace. Given the underlying implementation removes the name
# passed as second argument on the passed storage.
2014-09-02 18:07:02 +05:30
#
2016-08-24 12:49:21 +05:30
# storage - project's storage path
2018-03-17 18:26:18 +05:30
# name - project disk path
2014-09-02 18:07:02 +05:30
#
# Ex.
2016-08-24 12:49:21 +05:30
# remove_repository("/path/to/storage", "gitlab/gitlab-ci")
def remove_repository(storage, name)
2018-03-17 18:26:18 +05:30
return false if name.empty?
!!rm_directory(storage, "#{name}.git")
rescue ArgumentError => e
Rails.logger.warn("Repository does not exist: #{e} at: #{name}.git")
false
2014-09-02 18:07:02 +05:30
end
# Add new key to gitlab-shell
#
# Ex.
# add_key("key-42", "sha-rsa ...")
#
def add_key(key_id, key_content)
2018-03-17 18:26:18 +05:30
return unless self.authorized_keys_enabled?
2017-09-10 17:25:29 +05:30
gitlab_shell_fast_execute([gitlab_shell_keys_path,
'add-key', key_id, self.class.strip_key(key_content)])
2014-09-02 18:07:02 +05:30
end
# Batch-add keys to authorized_keys
#
# Ex.
# batch_add_keys { |adder| adder.add_key("key-42", "sha-rsa ...") }
def batch_add_keys(&block)
2018-03-17 18:26:18 +05:30
return unless self.authorized_keys_enabled?
2014-09-02 18:07:02 +05:30
IO.popen(%W(#{gitlab_shell_path}/bin/gitlab-keys batch-add-keys), 'w') do |io|
2017-08-17 22:00:37 +05:30
yield(KeyAdder.new(io))
2014-09-02 18:07:02 +05:30
end
end
# Remove ssh key from gitlab shell
#
# Ex.
# remove_key("key-342", "sha-rsa ...")
#
2018-03-17 18:26:18 +05:30
def remove_key(key_id, key_content = nil)
return unless self.authorized_keys_enabled?
2017-09-10 17:25:29 +05:30
args = [gitlab_shell_keys_path, 'rm-key', key_id]
args << key_content if key_content
gitlab_shell_fast_execute(args)
2014-09-02 18:07:02 +05:30
end
# Remove all ssh keys from gitlab shell
#
# Ex.
# remove_all_keys
#
def remove_all_keys
2018-03-17 18:26:18 +05:30
return unless self.authorized_keys_enabled?
2017-09-10 17:25:29 +05:30
gitlab_shell_fast_execute([gitlab_shell_keys_path, 'clear'])
2014-09-02 18:07:02 +05:30
end
2018-03-17 18:26:18 +05:30
# Remove ssh keys from gitlab shell that are not in the DB
#
# Ex.
# remove_keys_not_found_in_db
#
2018-12-05 23:21:45 +05:30
# rubocop: disable CodeReuse/ActiveRecord
2018-03-17 18:26:18 +05:30
def remove_keys_not_found_in_db
return unless self.authorized_keys_enabled?
Rails.logger.info("Removing keys not found in DB")
batch_read_key_ids do |ids_in_file|
ids_in_file.uniq!
keys_in_db = Key.where(id: ids_in_file)
next unless ids_in_file.size > keys_in_db.count # optimization
ids_to_remove = ids_in_file - keys_in_db.pluck(:id)
ids_to_remove.each do |id|
Rails.logger.info("Removing key-#{id} not found in DB")
remove_key("key-#{id}")
end
end
end
2018-12-05 23:21:45 +05:30
# rubocop: enable CodeReuse/ActiveRecord
2018-03-17 18:26:18 +05:30
# Iterate over all ssh key IDs from gitlab shell, in batches
#
# Ex.
# batch_read_key_ids { |batch| keys = Key.where(id: batch) }
#
def batch_read_key_ids(batch_size: 100, &block)
return unless self.authorized_keys_enabled?
list_key_ids do |key_id_stream|
key_id_stream.lazy.each_slice(batch_size) do |lines|
key_ids = lines.map { |l| l.chomp.to_i }
yield(key_ids)
end
end
end
# Stream all ssh key IDs from gitlab shell, separated by newlines
#
# Ex.
# list_key_ids
#
def list_key_ids(&block)
return unless self.authorized_keys_enabled?
IO.popen(%W(#{gitlab_shell_path}/bin/gitlab-keys list-key-ids), &block)
end
2014-09-02 18:07:02 +05:30
# Add empty directory for storing repositories
#
# Ex.
2018-10-15 14:42:47 +05:30
# add_namespace("default", "gitlab")
2014-09-02 18:07:02 +05:30
#
2016-08-24 12:49:21 +05:30
def add_namespace(storage, name)
2018-10-15 14:42:47 +05:30
Gitlab::GitalyClient::NamespaceService.new(storage).add(name)
2018-03-17 18:26:18 +05:30
rescue GRPC::InvalidArgument => e
raise ArgumentError, e.message
2014-09-02 18:07:02 +05:30
end
# Remove directory from repositories storage
# Every repository inside this directory will be removed too
#
# Ex.
2018-10-15 14:42:47 +05:30
# rm_namespace("default", "gitlab")
2014-09-02 18:07:02 +05:30
#
2016-08-24 12:49:21 +05:30
def rm_namespace(storage, name)
2018-10-15 14:42:47 +05:30
Gitlab::GitalyClient::NamespaceService.new(storage).remove(name)
2018-03-17 18:26:18 +05:30
rescue GRPC::InvalidArgument => e
raise ArgumentError, e.message
2014-09-02 18:07:02 +05:30
end
2018-03-17 18:26:18 +05:30
alias_method :rm_directory, :rm_namespace
2014-09-02 18:07:02 +05:30
# Move namespace directory inside repositories storage
#
# Ex.
2016-08-24 12:49:21 +05:30
# mv_namespace("/path/to/storage", "gitlab", "gitlabhq")
2014-09-02 18:07:02 +05:30
#
2016-08-24 12:49:21 +05:30
def mv_namespace(storage, old_name, new_name)
2018-10-15 14:42:47 +05:30
Gitlab::GitalyClient::NamespaceService.new(storage).rename(old_name, new_name)
2019-02-13 22:33:31 +05:30
rescue GRPC::InvalidArgument => e
Gitlab::Sentry.track_acceptable_exception(e, extra: { old_name: old_name, new_name: new_name, storage: storage })
2018-03-17 18:26:18 +05:30
false
2014-09-02 18:07:02 +05:30
end
2019-02-13 22:33:31 +05:30
alias_method :mv_directory, :mv_namespace # Note: ShellWorker uses this alias
2014-09-02 18:07:02 +05:30
2015-04-26 12:48:37 +05:30
def url_to_repo(path)
2014-09-02 18:07:02 +05:30
Gitlab.config.gitlab_shell.ssh_path_prefix + "#{path}.git"
end
# Return GitLab shell version
def version
gitlab_shell_version_file = "#{gitlab_shell_path}/VERSION"
if File.readable?(gitlab_shell_version_file)
2015-04-26 12:48:37 +05:30
File.read(gitlab_shell_version_file).chomp
2014-09-02 18:07:02 +05:30
end
end
2015-09-11 14:41:01 +05:30
# Check if such directory exists in repositories.
#
# Usage:
2016-08-24 12:49:21 +05:30
# exists?(storage, 'gitlab')
# exists?(storage, 'gitlab/cookies.git')
2015-09-11 14:41:01 +05:30
#
2018-12-05 23:21:45 +05:30
# rubocop: disable CodeReuse/ActiveRecord
2016-08-24 12:49:21 +05:30
def exists?(storage, dir_name)
2018-10-15 14:42:47 +05:30
Gitlab::GitalyClient::NamespaceService.new(storage).exists?(dir_name)
2016-08-24 12:49:21 +05:30
end
2018-12-05 23:21:45 +05:30
# rubocop: enable CodeReuse/ActiveRecord
2016-08-24 12:49:21 +05:30
2014-09-02 18:07:02 +05:30
protected
def gitlab_shell_path
2018-03-17 18:26:18 +05:30
File.expand_path(Gitlab.config.gitlab_shell.path)
end
def gitlab_shell_hooks_path
File.expand_path(Gitlab.config.gitlab_shell.hooks_path)
2014-09-02 18:07:02 +05:30
end
def gitlab_shell_user_home
File.expand_path("~#{Gitlab.config.gitlab_shell.ssh_user}")
end
2016-08-24 12:49:21 +05:30
def full_path(storage, dir_name)
2014-09-02 18:07:02 +05:30
raise ArgumentError.new("Directory name can't be blank") if dir_name.blank?
2018-10-15 14:42:47 +05:30
File.join(Gitlab.config.repositories.storages[storage].legacy_disk_path, dir_name)
2014-09-02 18:07:02 +05:30
end
2015-04-26 12:48:37 +05:30
def gitlab_shell_projects_path
File.join(gitlab_shell_path, 'bin', 'gitlab-projects')
end
def gitlab_shell_keys_path
File.join(gitlab_shell_path, 'bin', 'gitlab-keys')
end
2017-09-10 17:25:29 +05:30
2018-03-17 18:26:18 +05:30
def authorized_keys_enabled?
# Return true if nil to ensure the authorized_keys methods work while
# fixing the authorized_keys file during migration.
return true if Gitlab::CurrentSettings.current_application_settings.authorized_keys_enabled.nil?
Gitlab::CurrentSettings.current_application_settings.authorized_keys_enabled
end
2017-09-10 17:25:29 +05:30
private
def gitlab_shell_fast_execute(cmd)
output, status = gitlab_shell_fast_execute_helper(cmd)
return true if status.zero?
Rails.logger.error("gitlab-shell failed with error #{status}: #{output}")
false
end
def gitlab_shell_fast_execute_raise_error(cmd, vars = {})
output, status = gitlab_shell_fast_execute_helper(cmd, vars)
raise Error, output unless status.zero?
2018-03-17 18:26:18 +05:30
2017-09-10 17:25:29 +05:30
true
end
def gitlab_shell_fast_execute_helper(cmd, vars = {})
vars.merge!(ENV.to_h.slice(*GITLAB_SHELL_ENV_VARS))
# Don't pass along the entire parent environment to prevent gitlab-shell
# from wasting I/O by searching through GEM_PATH
Bundler.with_original_env { Popen.popen(cmd, nil, vars) }
end
2018-03-17 18:26:18 +05:30
def git_timeout
Gitlab.config.gitlab_shell.git_timeout
end
2018-11-18 11:00:15 +05:30
def wrapped_gitaly_errors
yield
2018-03-17 18:26:18 +05:30
rescue GRPC::NotFound, GRPC::BadStatus => e
# Old Popen code returns [Error, output] to the caller, so we
# need to do the same here...
raise Error, e
end
2018-11-08 19:23:39 +05:30
class GitalyGitlabProjects
attr_reader :shard_name, :repository_relative_path, :output
def initialize(shard_name, repository_relative_path)
@shard_name = shard_name
@repository_relative_path = repository_relative_path
@output = ''
end
def import_project(source, _timeout)
raw_repository = Gitlab::Git::Repository.new(shard_name, repository_relative_path, nil)
Gitlab::GitalyClient::RepositoryService.new(raw_repository).import_repository(source)
true
rescue GRPC::BadStatus => e
@output = e.message
false
end
def fork_repository(new_shard_name, new_repository_relative_path)
target_repository = Gitlab::Git::Repository.new(new_shard_name, new_repository_relative_path, nil)
raw_repository = Gitlab::Git::Repository.new(shard_name, repository_relative_path, nil)
Gitlab::GitalyClient::RepositoryService.new(target_repository).fork_repository(raw_repository)
rescue GRPC::BadStatus => e
logger.error "fork-repository failed: #{e.message}"
false
end
def logger
Rails.logger
end
end
2014-09-02 18:07:02 +05:30
end
end