An error occurred while fetching folder content
Summary
Any project overview, site loads but file content is not shown. After a while (timeout 30sec?) an error message is shown.
Steps to reproduce
Happens every time, tried Chrome and Firefox, different PCs (Windows), even with Android same result
Example Project
Happens on my selfhosted GitLab instance
What is the current bug behavior?
Developer mode shows “POST https://git.xxx.net/api/graphql error 500”
Initiator: bundle.esm.js
What is the expected correct behavior?
site loads completely
Relevant logs and/or screenshots
Happy to provide any necessary logs
Output of checks
Selfhosted GitLab
Results of GitLab environment info
Expand for output related to GitLab environment info
root@git:/# gitlab-rake gitlab:env:info System information System: Current User: git Using RVM: no Ruby Version: 2.7.2p137 Gem Version: 3.1.4 Bundler Version:2.1.4 Rake Version: 13.0.1 Redis Version: 5.0.9 Git Version: 2.29.0 Sidekiq Version:5.2.9 Go Version: unknown GitLab information Version: 13.6.3 Revision: 857c6c6a6a9 Directory: /opt/gitlab/embedded/service/gitlab-rails DB Adapter: PostgreSQL DB Version: 11.9 URL: http://git.xyz.net HTTP Clone URL: http://git.xyz.net/some-group/some-project.git SSH Clone URL: git@git.xyz.net:some-group/some-project.git Using LDAP: no Using Omniauth: yes Omniauth Providers: GitLab Shell Version: 13.13.0 Repository storage paths: - default: /var/opt/gitlab/git-data/repositories GitLab Shell path: /opt/gitlab/embedded/service/gitlab-shell Git: /opt/gitlab/embedded/bin/git
Results of GitLab application Check
Expand for output related to the GitLab application check
root@git:/# gitlab-rake gitlab:check SANITIZE=true Checking GitLab subtasks ...
Checking GitLab Shell ...
GitLab Shell: ... GitLab Shell version >= 13.13.0 ? ... OK (13.13.0) Running /opt/gitlab/embedded/service/gitlab-shell/bin/check Internal API available: OK Redis available via internal API: OK gitlab-shell self-check successful
Checking GitLab Shell ... Finished
Checking Gitaly ...
Gitaly: ... default ... OK
Checking Gitaly ... Finished
Checking Sidekiq ...
Sidekiq: ... Running? ... yes Number of Sidekiq processes ... 1
Checking Sidekiq ... Finished
Checking Incoming Email ...
Incoming Email: ... Reply by email is disabled in config/gitlab.yml
Checking Incoming Email ... Finished
Checking LDAP ...
LDAP: ... LDAP is disabled in config/gitlab.yml
Checking LDAP ... Finished
Checking GitLab App ...
Git configured correctly? ... yes Database config exists? ... yes All migrations up? ... yes Database contains orphaned GroupMembers? ... no GitLab config exists? ... yes GitLab config up to date? ... yes Log directory writable? ... yes Tmp directory writable? ... yes Uploads directory exists? ... yes Uploads directory has correct permissions? ... yes Uploads directory tmp has correct permissions? ... yes Init script exists? ... skipped (omnibus-gitlab has no init script) Init script up-to-date? ... skipped (omnibus-gitlab has no init script) Projects have namespace: ... 1/1 ... yes 1/2 ... yes 1/3 ... yes 1/4 ... yes Redis version >= 4.0.0? ... yes Ruby version >= 2.7.2 ? ... yes (2.7.2) Git version >= 2.29.0 ? ... yes (2.29.0) Git user has default SSH configuration? ... yes Active users: ... 1 Is authorized keys file accessible? ... yes GitLab configured to store new projects in hashed storage? ... yes All projects are in hashed storage? ... yes
Checking GitLab App ... Finished
Checking GitLab subtasks ... Finished
Possible fixes
Using a simple GitLab installation with docker (Debian 10.7, current docker version), HTTPS access with Traefik reverse proxy.
Happens since version gitlab/gitlab-ce:13.6.0-ce.0, still working with gitlab/gitlab-ce:13.5.4-ce.0 without changing my config.
Edited by Cyber MCM
Я случайно напутал владельцев файлов (chown на неправильном уровне …) на моем собственном Gitlab, запущенном в контейнере Docker. Мне удалось восстановить большую часть собственности.
Это было сделано путем бега. Однако это не сразу устранило проблему, поскольку журналы по-прежнему показывали ошибку отказа в разрешении для grafana db. Чтобы исправить это, я продолжил настройку нового Gitlab и сравнил / восстановил право собственности.
Хотя сам Gitlab теперь снова работает, я все еще получаю следующие ошибки:
- Когда я пытаюсь толкнуть, я получаю:
remote: GitLab: Push operation timed out
remote:
remote: Timing information for debugging purposes:
remote: Running checks for ref: XXXX
remote: Checking if you are allowed to push... (62.94ms)
remote: Checking if default branch is being deleted... (0.31ms)
remote: Scanning repository for blobs stored in LFS and verifying their files have been uploaded to GitLab... (cancelled after 29547.57ms)
To http://gitlab.XXXX.XX/XXXX/XXXX.git
! [remote rejected] XXXXX -> XXXX (pre-receive hook declined)
error: failed to push some refs to 'http://gitlab.XXXX.XX/XXXX/XXXX.git'
- Когда я нажимаю на проект в веб-интерфейсе, он показывает такую информацию, как ветки, общий размер файла и т. Д., Но не сам список файлов / файлов. Скорее
отображается.
Бег
при попытке нажать показывает следующее:
{"level":"info","msg":"I, [2021-07-05T17:13:19.676164 #3372254] INFO -- sentry: ** [Raven] Raven 3.0.4 configured not to capture errors: DSN not set","supervisor.args":["bundle","exec","bin/ruby-cd","/var/opt/gitlab/gitaly","/opt/gitlab/embedded/service/gitaly-ruby/bin/gitaly-ruby","3368488","/var/opt/gitlab/gitaly/internal_sockets/ruby.0"],"supervisor.name":"gitaly-ruby.0","time":"2021-07-05T17:13:19.692Z"}
{"error":"exit status 1","level":"warning","msg":"exited","supervisor.args":["bundle","exec","bin/ruby-cd","/var/opt/gitlab/gitaly","/opt/gitlab/embedded/service/gitaly-ruby/bin/gitaly-ruby","3368488","/var/opt/gitlab/gitaly/internal_sockets/ruby.0"],"supervisor.name":"gitaly-ruby.0","time":"2021-07-05T17:13:19.698Z"}
{"level":"info","msg":"I, [2021-07-05T17:13:20.817759 #3372257] INFO -- sentry: ** [Raven] Raven 3.0.4 configured not to capture errors: DSN not set","supervisor.args":["bundle","exec","bin/ruby-cd","/var/opt/gitlab/gitaly","/opt/gitlab/embedded/service/gitaly-ruby/bin/gitaly-ruby","3368488","/var/opt/gitlab/gitaly/internal_sockets/ruby.1"],"supervisor.name":"gitaly-ruby.1","time":"2021-07-05T17:13:20.835Z"}
{"error":"exit status 1","level":"warning","msg":"exited","supervisor.args":["bundle","exec","bin/ruby-cd","/var/opt/gitlab/gitaly","/opt/gitlab/embedded/service/gitaly-ruby/bin/gitaly-ruby","3368488","/var/opt/gitlab/gitaly/internal_sockets/ruby.1"],"supervisor.name":"gitaly-ruby.1","time":"2021-07-05T17:13:20.843Z"}
[...]
{"correlation_id":"01F9VTFEM5X7N2PZR6WVDAQQYN","error":"GitLab: Push operation timed out\n\nTiming information for debugging purposes:\nRunning checks for ref: XXXX\nChecking if you are allowed to push... (13.42ms)\nChecking if default branch is being deleted... (0.43ms)\nScanning repository for blobs stored in LFS and verifying their files have been uploaded to GitLab... (cancelled after 29583.1ms)","grpc.meta.deadline_type":"none","grpc.method":"PreReceiveHook","grpc.request.fullMethod":"/gitaly.HookService/PreReceiveHook","grpc.request.glProjectPath":"XXXX/XXXX","grpc.request.glRepository":"project-5","grpc.request.repoPath":"@hashed/ef/2d/ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d.git","grpc.request.repoStorage":"default","grpc.request.topLevelGroup":"@hashed","grpc.service":"gitaly.HookService","grpc.start_time":"2021-07-05T17:11:59.178Z","level":"warning","msg":"stopping transaction because pre-receive hook failed","peer.address":"@","pid":3368488,"span.kind":"server","system":"grpc","time":"2021-07-05T17:12:29.025Z"}
Кто-нибудь знает, как исправить эту проблему?
РЕДАКТИРОВАТЬ: я добавил информацию о
как обсуждалось в комментариях.
I have git error: «insufficient permission for adding an object to repository database .git/objects» every time I make «git pull origin develop».
remote: Counting objects: 70, done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 42 (delta 35), reused 42 (delta 35)
error: insufficient permission for adding an object to repository database .git/objects
fatal: failed to write object
fatal: unpack-objects failed
asked Sep 13, 2013 at 6:15
unnati patilunnati patil
1,5912 gold badges12 silver badges11 bronze badges
4
Assuming @ChrisHayes is right about an accidental sudo, this should fix it. From inside your repository:
sudo chown -R $USER:$USER "$(git rev-parse --show-toplevel)/.git"
Update: for those of you getting the illegal group name
error, try this instead:
sudo chown -R $(id -u):$(id -g) "$(git rev-parse --show-toplevel)/.git"
answered Nov 5, 2013 at 23:20
8
Go to project’s root directory and run below commands to fix this issue,
cd .git/objects
sudo chown -R yourname:yourgroup *
answered Mar 22, 2018 at 11:10
Priyank PatelPriyank Patel
12.2k8 gold badges66 silver badges85 bronze badges
1
Mine was a stupid mistake… the right username and group were set, but www-data was the account accessing it. The directory was owned by vaindil:www-data, but permissions were 755 so www-data couldn’t write to it. Fixed it with:
$ sudo chmod -R 775 /path/to/repo
answered Oct 24, 2016 at 18:20
vaindilvaindil
7,29621 gold badges70 silver badges123 bronze badges
NOT A GOOD PRACTICE (Just an alternative)
I am using Ubuntu and faced the same problem. To solve it, I simply switched user to root and I see no further error.
$su
password
Then,
$git pull origin master
Recommended way: CHANGE THE PERMISSION OF THE DIRECTORY
answered Mar 2, 2016 at 11:20
NabinNabin
11k8 gold badges64 silver badges98 bronze badges
4
Когда я пытаюсь нажать на общий пульт git, я получаю следующую ошибку:
insufficient permission for adding an object to repository database
Затем я прочитал об исправлении здесь: Fix Это сработало для следующего нажатия, поскольку все файлы были правильной группы, но в следующий раз, когда кто-то подтолкнул изменение, он сделал новый элемент в папке объектов, в которой группа по умолчанию была группой. Единственное, что я могу придумать, это изменить всю группу разработчиков по умолчанию для элементов, которые они проверяют, но это похоже на взлома. Есть идеи? Спасибо.
Ответ 1
Разрешения на ремонт
После того, как вы определили и устранили основную причину (см. Ниже), вы захотите восстановить разрешения:
cd /path/to/repo.git
sudo chgrp -R groupname .
sudo chmod -R g+rwX .
find . -type d -exec chmod g+s '{}' +
Обратите внимание: если вы хотите, чтобы все могли изменять репозиторий, вам не нужен chgrp
и вы захотите изменить chmod на sudo chmod -R a+rwX.
Если вы не исправите основную причину, ошибка продолжит возвращаться, и вам придется снова и снова повторять -R отмену вышеуказанных команд.
Основные причины
Ошибка может быть вызвана одним из следующих:
-
Репозиторий не настроен для использования в качестве общего репозитория (см.
core.sharedRepository
вgit help config
). Если на выходе:git config core.sharedRepository
не является
group
илиtrue
или1
или какой-то маской, попробуйте выполнить:git config core.sharedRepository group
а затем повторно -R un рекурсивные
chmod
иchgrp
(см. «Разрешения на восстановление» выше). -
Операционная система не интерпретирует бит setgid для каталогов, поскольку «все новые файлы и подкаталоги должны наследовать владельца группы».
Когда
core.sharedRepository
имеет значениеtrue
илиgroup
, Git использует функцию операционных систем GNU (например, каждый дистрибутив Linux), чтобы гарантировать, что вновь созданные подкаталоги принадлежат правильной группе (группе, в которой находятся все пользователи репозитория). Эта функция описана в документации GNU coreutils:… [Если] установлен бит set-group-ID каталога, вновь созданные подфайлы наследуют ту же группу, что и каталог, а вновь созданные подкаталоги наследуют бит set-group-ID родительского каталога…. [Этот механизм позволяет] пользователям легче обмениваться файлами, уменьшая необходимость использовать
chmod
илиchown
для обмена новыми файлами.Однако не все операционные системы имеют эту функцию (NetBSD является одним из примеров). Для этих операционных систем вы должны убедиться, что все ваши пользователи Git имеют одинаковую группу по умолчанию. В качестве альтернативы, вы можете сделать хранилище доступным для записи в мире, запустив
git config core.sharedRepository world
(но будьте осторожны — это менее безопасно). - Файловая система не поддерживает бит setgid (например, FAT). ext2, ext3, ext4 все поддерживают бит setgid. Насколько я знаю, файловые системы, которые не поддерживают бит setgid, также не поддерживают концепцию владения группой, поэтому все файлы и каталоги в любом случае будут принадлежать одной и той же группе (какая группа является опцией монтирования). В этом случае убедитесь, что все пользователи Git входят в группу, которой принадлежат все файлы в файловой системе.
- Не все пользователи Git находятся в одной группе, которая владеет каталогами репозитория. Убедитесь, что владелец группы в каталогах указан правильно и что все пользователи находятся в этой группе.
Ответ 2
Для Ubuntu (или любого Linux)
Из корня проекта
cd .git/objects
ls -al
sudo chown -R yourname:yourgroup *
Вы можете указать, что должно быть у вашего имени и вашей группы, посмотрев разрешения на большую часть вывода из этой команды ls -al
Примечание: помните звезду в конце строки sudo
Ответ 3
sudo chmod -R ug+w .;
В принципе, файл .git/objects
не имеет разрешений на запись. Вышеупомянутая строка предоставляет разрешение всем файлам и папкам в каталоге.
Ответ 4
используйте следующую команду, работает как magic
sudo chown -R "${USER:-$(id -un)}" .
введите команду точно так, как она есть (с дополнительными пробелами и одной точкой в конце)
Ответ 5
Я просто хотел добавить свое решение. У меня было репо на OS X, у которого было право на root в некоторых каталогах и Home (это мой каталог пользователей) на других, которые вызвали ту же ошибку, что и выше.
Решение было просто благодарно. От терминала:
sudo chown -R Home projectdirectory
Ответ 6
Хороший способ отладки — это в следующий раз, когда это произойдет, SSH в удаленное репо, cd в папку с объектами и выполните ls -al
.
Если вы видите 2-3 файла с разными правами пользователя: группа, то это проблема.
В прошлом мне случалось, что некоторые устаревшие скрипты обращались к нашему репозиторию git и обычно означает, что другой (unix) пользователь вставлял/модифицировал файлы последним, и у вашего пользователя нет разрешений на перезапись этих файлов. Вы должны создать общую группу git, в которой находятся все git -enabled пользователи, а затем рекурсивно chgrp
папка objects
, и это содержимое, так что это групповое владение является общей группой git
.
Вы также должны добавить липкий бит в папку, чтобы все файлы, созданные в папке, всегда имели группу git
.
chmod g + s имя-каталога
Обновление: я не знал о core.sharedRepository. Полезно знать, хотя он, вероятно, просто делает это.
Ответ 7
Решенный для меня…
только это:
sudo chmod 777 -R .git/objects
Ответ 8
Это может произойти, если вы запустили git init
с другим пользователем из того, который вы планируете использовать при нажатии изменений.
Если вы слепо следуете инструкциям в [1], это произойдет, поскольку вы, вероятно, создали git -user как root, а затем сразу же перешли к git init без изменения пользователя между ними.
[1] http://git-scm.com/book/en/Git-on-the-Server-Setting-Up-the-Server
Ответ 9
После того, как вы добавите некоторые вещи… зафиксируйте их и после того, как закончите, нажмите на них! BANG !! Начните все проблемы… Как вы должны заметить, существуют некоторые различия в способах определения как новых, так и существующих проектов. Если какой-то другой человек попытается добавить/зафиксировать/отправить те же файлы или содержимое (git сохранит оба одинаковых объекта), мы столкнемся со следующей ошибкой:
$ git push
Counting objects: 31, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (17/17), done.
Writing objects: 100% (21/21), 2.07 KiB | 0 bytes/s, done.
Total 21 (delta 12), reused 0 (delta 0)
remote: error: insufficient permission for adding an object to repository database ./objects remote: fatal: failed to write object
Чтобы решить эту проблему, вы должны иметь в виду систему разрешений операционной системы, поскольку в этом случае вы ограничены ею. Чтобы лучше понять проблему, проверьте папку с объектами git (.git/objects). Вы, вероятно, увидите что-то подобное:
<your user_name>@<the machine name> objects]$ ls -la
total 200
drwxr-xr-x 25 <your user_name> <group_name> 2048 Feb 10 09:28 .
drwxr-xr-x 3 <his user_name> <group_name> 1024 Feb 3 15:06 ..
drwxr-xr-x 2 <his user_name> <group_name> 1024 Jan 31 13:39 02
drwxr-xr-x 2 <his user_name> <group_name> 1024 Feb 3 13:24 08
* Обратите внимание, что эти права доступа к файлам были предоставлены только вашим пользователям, никто никогда не сможет их изменить… *
Level u g o
Permission rwx r-x ---
Binary 111 101 000
Octal 7 5 0
РЕШЕНИЕ ПРОБЛЕМЫ
Если у вас есть разрешение суперпользователя, вы можете перейти вперед и изменить все разрешения самостоятельно, выполнив второй шаг. В любом другом случае вам нужно будет спросить всех пользователей, объекты которых созданы с их пользователями, используйте следующую команду, чтобы узнать, кто они:
$ ls -la | awk '{print $3}' | sort -u
<your user_name>
<his user_name>
Теперь вам и всем пользователям-владельцам файлов придется изменить разрешение на эти файлы, выполнив:
$ chmod -R 774 .
После этого вам нужно будет добавить новое свойство, которое эквивалентно —shared = group, для нового репозитория, в соответствии с документацией, это сделает репозиторий доступным для записи в группу, выполнив его:
$ git config core.sharedRepository group
https://coderwall.com/p/8b3ksg
Ответ 10
Linux, macOS:
cd .git/
sudo chown -R name:group *
где name
— ваше имя пользователя, а group
— это группа, к которой принадлежит ваше имя пользователя.
Ответ 11
В моем случае ни один из предложений не работал. Я нахожусь в Windows, и это сработало для меня:
- Копирование удаленного репо в другую папку
- Разделите папку и укажите соответствующие разрешения.
- Убедитесь, что вы можете получить доступ к папке с локальной машины.
- Добавьте это репо в качестве другого удаленного репо в вашем локальном репо. (
git remote add foo //SERVERNAME/path/to/copied/git
) - Нажмите на foo.
git push foo master
. Это сработало? Большой! Теперь удалите нерабочее репо и переименуйте его во все, что было раньше. Удостоверьтесь, что права и свойство share остаются прежними.
Ответ 12
Я попал в эту же проблему. Прочитав здесь, я понял, что это права на файлы, на которые ссылалось сообщение. Исправление для меня было:
/etc/inetd.d/git -gpv
Он начинал с git -demon как пользователь ‘ nobody, поэтому не было права на запись.
# Who When What
# GPV 20Nov13 Created this by hand while reading: http://linuxclues.blogspot.co.uk/2013/06>/git-daemon-ssh-create-repository-debian.html
# GPV 20Nov13 Changed owner (to user_git) otherise nobody lack permission to update the repository
#git stream tcp nowait nobody /usr/bin/git git daemon --inetd --verbose --enable=receive-pack --export-all /gitrepo
git stream tcp nowait user_git /usr/bin/git git daemon --inetd --verbose --enable=receive-pack --export-all /gitrepo
(Я сомневаюсь, что другие вызовут их inetd conf файл git -gpv. Обычно это было бы непосредственно в/etc/inetd.conf)
Ответ 13
Вам нужны достаточные права на запись в каталоге, на который вы нажимаете.
В моем случае: сервер Windows 2008
щелкните правой кнопкой мыши каталог git repo или родительский каталог.
Свойствa > вкладка «Общий доступ» > «Расширенный доступ» > «Разрешения» > убедитесь, что у пользователя есть соответствующие права доступа.
Ответ 14
Возможно, вы случайно вложили git-репозитории
Ответ 15
выполните следующую команду для .git:
chmod -R 777 .git
Ответ 16
Также возможно, что вы добавили другой локальный репозиторий с тем же псевдонимом. Например, теперь у вас есть 2 локальные папки, называемые origin
поэтому при попытке отправки удаленный репозиторий не примет ваши учетные данные.
Переименуйте псевдонимы локального репозитория, вы можете перейти по этой ссылке fooobar.com/questions/18602/…
Возможно, вы можете оставить 1 локальный репозиторий по своему вкусу как origin
а другие переименовать их, например, из origin
в anotherorigin
. Помните, что это просто псевдонимы, и все, что вам нужно сделать, это запомнить новые псевдонимы и их соответствующие удаленные ветки.
Ответ 17
Я получаю эту ошибку при попытке проталкивания через среду IDE (в данном случае PHPStorm).
Когда я пытался использовать терминал (OSX), он работает! Таким образом, это явно проблема разрешения.
Хотя я не могу найти, как навсегда исправить его, используя
$ sudo git push origin master
выполнит трюк
Ответ 18
Работает для меня
sudo chmod -R g+rwX .
Ответ 19
Я получил это при подключении к проекту Rstudio. Я понял, что забыл сделать:
sudo rstudio
при запуске программы. На самом деле, поскольку у меня есть еще одна ошибка, мне нужно сделать:
sudo rstudio --no-sandbox
По умолчанию вы не можете отправлять изменения в извлеченную ветвь репозитория. Обычно это вызывает большие проблемы! Вот что обычно происходит:
$ git push герой мастер ...Сообщения об ошибках... к героку ! [удаленный отказ] master -> master (ветвь в настоящее время проверена) ошибка: не удалось отправить некоторые ссылки на 'героку'
Поскольку вы ничего не упомянули Сообщения об ошибках, я предполагаю, что вы добавили следующее в свой heroku
конфигурация репозитория, или вы используете довольно старую версию Git:
[получить] denyCurrentBranch = false
Похоже, вы хотите проверить свежую копию основной ветки всякий раз, когда вы отправляете новую версию на свой heroku
репозиторий. Этого можно добиться с помощью хука post-receive. Создайте файл в своем heroku
хранилище .git/hooks/post-receive
, и дать это +x
разрешения.
#!/bin/sh
while read oldrev newrev refname
do
if test "$refname" = refs/heads/master
then
( cd ..; GIT_DIR=.git; git reset --hard )
fi
done
Теперь всякий раз, когда вы нажимаете новый master
филиал в heroku
, хук запустится и проверит новую ветку. Есть лучшие способы сделать такие вещи, но это просто.
Резюме: По умолчанию, когда вы отправляете изменения, изменяется только история но не рабочее дерево. Предполагается, что кто-то может работать с этим деревом, поэтому любые действия с ним могут быть разрушительными.
Sometimes when you do a git push, you might get the following permission error message.
This error typically happens when multiple users are working on a particular git repository.
The following git push error indicates that it doesn’t have enough permission for adding a new object to the ./objects directory under your repository.
Apart from the obvious permission issue, there is also another underlying problem that needs to be addressed, which is explained in this tutorial.
$ git push counting objects: 6, done. Delta compression using upto 4 threads. Compressing objects: 100% (3/3), done. Writing objects: 100% (4/4), 388 bytes, | 0 bytes/s, done. Total: 4 (delta 1), reused 0 (delta 0) error: insufficient permission for adding an object to repository database ./objects fatal: failed to write object error: unpack failed: unpack-objects abnormal exit ! [remote rejected] master -> master (n/a (unpacker error)) error: failed to push some refs to john@192.168.100.1:/home/git/myproj
It also shows that the git unpack failed with unpack-objects abnormal exit. Because of this error, it failed to push some refs as shown above.
First, cd to the git repository which is having this issue. If you don’t see the objects directory directly under your repository folder, then look under the .git folder as shown below.
[john@devdb]$ cd /home/git/myproj (or) [john@devdb]$ cd /home/git/myproj/.git
In this particular case, when john is trying to do ‘git push’, he is getting the above error because some of the directories under the objects folder of git repository are owned by lisa as shown below.
[john@devdb]$ ls -l objects drwxr-xr-x 2 john git 4096 Oct 8 2016 01 drwxr-xr-x 2 john git 4096 Oct 8 2016 02 drwxr-xr-x 2 lisa lisa 4096 Oct 8 2016 03 drwxr-xr-x 2 lisa lisa 4096 May 1 2017 04 drwxr-xr-x 2 john git 4096 May 1 2017 05 drwxr-xr-x 2 john git 4096 May 6 2017 06
Set the Appropriate Permissions on Objects Directory
To solve this problem, execute the following, which will set the group to git (or whatever group where all the users belongs to. Also make sure the user and group has read and write permission to the directory.
cd /your/git/repo chgrp -R git objects chmod -R g+rws objects
In the above:
- Make sure all your users who need access to git are part of the git group. Change the “git” in the above chgrp command to whatever group where all your developers belong to.
- The “s” option in the “g+rws” is to set the setuid bit on the objects folder. This will make sure any new directory created under objects folder will make the group name from the objects folder which is owned by git group.
You may be tempted to execute the following on your objects directory, which will solve the problem that you are having. But, as you can imagine, it is not a good idea to do 777. Instead execute the above chgrp and chmod command.
chmod -R 777 objects
Share the Git Repository with a Group
But, even after doing the above, the same problem might return again, and you may have to do the above chgrp and chmod whenever the problem occurs.
So, apart from fixing the permission error as explained above, we also need to fix the underlying problem.
In this case, the git repository (for example: myproj) is not setup as shared repository for groups. It might just be a bare repository.
If it is not setup as shared repository, you’ll see the above “insufficient permission on objects directory” issue starts to show-up again.
To verify whether your repository is already setup for group sharing, do the following git config -l option inside your git repository that has the problem.
$ cd /home/git/myproj $ git config -l user.name=John Smith user.email=john@thegeekstuff.com core.repositoryformatversion=0 core.filemode=true core.bare=true core.logallrefupdates=true
In the above output, we don’t see a parameter called “core.sharedrepository”. So, this particular repository (i.e myproj is not setup as shared repository).
The above command displays the configuration values from the “config” file that is located under your git repository.
$ cd /your/git/repo $ cat config [core] repositoryformatversion = 0 filemode = true bare = true logallrefupdates = true
The above is setup as a bare repository. To convert a bare repository to shared repository, do the following:
git config core.sharedRepository group
Note: In the above command, don’t replace the keyword “group” with your groupname (for example: git). Use the above above command exactly as shown without changing anything. The “group” in the above command should be typed exactly as it is.
Now, if you view the git config as shown below, you’ll see the “core.sharedrepository” parameter set to group.
$ git config -l user.name=John Smith user.email=john@thegeekstuff.com core.repositoryformatversion=0 core.filemode=true core.bare=true core.logallrefupdates=true core.sharedrepository=group
The above will solve the insufficient permission issue permanently.
After you set the sharedrepository, if you view the config file under your git repository, you’ll notice that the value of sharedrepository parameter is set to 2 (which is group) as shown below.
$ cat config [core] repositoryformatversion = 0 filemode = true bare = true sharedrepository = 2 [receive] denyNonFastforwards = true
Also, anytime you make a git repository as sharedrepository for group using the above command, it will also set the receive.denyNonFastforwards to true automatically as shown above.
Now I copied a folder into current repo, but I could not add the new folder into the repo. Then I tried using this command(git version 2.26.3
):
[dolphin@MiWiFi-R4CM-srv]~/Documents/GitHub/retire% git add zuul-service
[dolphin@MiWiFi-R4CM-srv]~/Documents/GitHub/retire% git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
seems did not add success, I tried using this command to force add to the repo:
[dolphin@MiWiFi-R4CM-srv]~/Documents/GitHub/retire% git add --force zuul-service
[dolphin@MiWiFi-R4CM-srv]~/Documents/GitHub/retire% git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
still not work. the next I tried to modify the folder zuul-service
file, no file change tips when using git status
to check. I also check the root folder’s .gitignore
and did not find ignore the zuul-service
folder. This is my first time to encount this strange problem and I have no clue about this problem. Where is going wrong and what should I do to add the zuul-service
folder into current repo? This is the project structure:
this is my .gitignore
files content:
# Compiled class file
*.class
# Log file
*.log
log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
*.icloud
*.bin
*.lock
.idea
*.tmp
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# dolphin-music
dolphin-music/dolphin-music-api/build/
dolphin-music/dolphin-music-service/build/
dolphin-music/dolphin-music-service/testngOutput
dolphin-music/dolphin-music-service/out
# dolphin-post
dolphin-post/dolphin-post-api/build/
dolphin-post/dolphin-post-service/build/
dolphin-post/dolphin-post-service/testngOutput
dolphin-post/dolphin-post-service/out
dolphin-acientbay/dolphin-acientbay-api/build
dolphin-acientbay/dolphin-acientbay-service/build
dolphin-acientbay/dolphin-acientbay-service/testngOutput
dolphin-acientbay/dolphin-acientbay-service/out
dolphin-common/build/
dolphin-common-biz/build/
dolphin-manage/dolphin-manage-service/out
eureka-service/out/
.gradle
.DS_Store
.gradle/buildOutputCleanup/buildOutputCleanup.lock
.idea/workspace.xml
dolphin-manage/dolphin-manage-service/out
dolphin-template/dolphin-template-service/out
dolphin-acientbay/dolphin-acientbay-service/out
the first time, the folder zuul-service
contains a .git
dir. then I removed it using this command:git rm -rf .git
. now the dir did not contains .git
folder.
Now I copied a folder into current repo, but I could not add the new folder into the repo. Then I tried using this command(git version 2.26.3
):
[dolphin@MiWiFi-R4CM-srv]~/Documents/GitHub/retire% git add zuul-service
[dolphin@MiWiFi-R4CM-srv]~/Documents/GitHub/retire% git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
seems did not add success, I tried using this command to force add to the repo:
[dolphin@MiWiFi-R4CM-srv]~/Documents/GitHub/retire% git add --force zuul-service
[dolphin@MiWiFi-R4CM-srv]~/Documents/GitHub/retire% git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
still not work. the next I tried to modify the folder zuul-service
file, no file change tips when using git status
to check. I also check the root folder’s .gitignore
and did not find ignore the zuul-service
folder. This is my first time to encount this strange problem and I have no clue about this problem. Where is going wrong and what should I do to add the zuul-service
folder into current repo? This is the project structure:
this is my .gitignore
files content:
# Compiled class file
*.class
# Log file
*.log
log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
*.icloud
*.bin
*.lock
.idea
*.tmp
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# dolphin-music
dolphin-music/dolphin-music-api/build/
dolphin-music/dolphin-music-service/build/
dolphin-music/dolphin-music-service/testngOutput
dolphin-music/dolphin-music-service/out
# dolphin-post
dolphin-post/dolphin-post-api/build/
dolphin-post/dolphin-post-service/build/
dolphin-post/dolphin-post-service/testngOutput
dolphin-post/dolphin-post-service/out
dolphin-acientbay/dolphin-acientbay-api/build
dolphin-acientbay/dolphin-acientbay-service/build
dolphin-acientbay/dolphin-acientbay-service/testngOutput
dolphin-acientbay/dolphin-acientbay-service/out
dolphin-common/build/
dolphin-common-biz/build/
dolphin-manage/dolphin-manage-service/out
eureka-service/out/
.gradle
.DS_Store
.gradle/buildOutputCleanup/buildOutputCleanup.lock
.idea/workspace.xml
dolphin-manage/dolphin-manage-service/out
dolphin-template/dolphin-template-service/out
dolphin-acientbay/dolphin-acientbay-service/out
the first time, the folder zuul-service
contains a .git
dir. then I removed it using this command:git rm -rf .git
. now the dir did not contains .git
folder.
mike@intel /var/www/git/MevSortableTreeBundle $ ls -a
. .. Controller .git MevSortableTreeBundle.php Resources
mike@intel /var/www/git/MevSortableTreeBundle $ git add .
mike@intel /var/www/git/MevSortableTreeBundle $ git status
On branch master
nothing to commit, working directory clean
Права на файлы 777. Несколько раз пересоздавал репозиторий. Не помогает.
mike@intel /var/www/git/MevSortableTreeBundle $ git ls-files
Controller/SortableTreeController.php
MevSortableTreeBundle.php
Resources/config/routing.yml
Resources/config/services.yml
Resources/views/Default/tree_up_down.html.twig
-
Вопрос заданболее трёх лет назад
-
7418 просмотров
Пригласить эксперта
Файл случайно не открыт на редактирование, а папки не пустые?
ну и попробуйте git check-ignore -v MevSortableTreeBundle.php
Такое бывает если ниже по дереву есть еще один репозиторий git.
Пример в корне
git status
изменено: vendor/friendsofsymfony/user-bundle (изменено содержимое)
cd vendor/friendsofsymfony/user-bundle
git status
изменено: .gitattributes
изменено: .github/ISSUE_TEMPLATE.md
изменено: .gitignore
изменено: .php_cs
изменено: .travis.yml
изменено: Changelog.md
изменено: Command/ActivateUserCommand.php
изменено: Command/ChangePasswordCommand.php
изменено: Command/CreateUserCommand.php
rm .git
cd ../../../
git add -A — ОК.
-
Показать ещё
Загружается…
28 янв. 2023, в 22:48
500 руб./за проект
28 янв. 2023, в 20:58
30000 руб./за проект
28 янв. 2023, в 20:46
50000 руб./за проект
Минуточку внимания
После того, как вы добавите какой-нибудь материал… скопируйте их и, после всего этого, нажмите его! BANG!! Начните все проблемы… Как вы заметили, есть некоторые различия в том, как были определены как новые, так и существующие проекты. Если какой-либо другой человек пытается добавить/зафиксировать/нажать те же файлы или содержимое (git сохранить оба как одни и те же объекты), мы столкнемся со следующей ошибкой:
$ git push
Counting objects: 31, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (17/17), done.
Writing objects: 100% (21/21), 2.07 KiB | 0 bytes/s, done.
Total 21 (delta 12), reused 0 (delta 0)
remote: error: insufficient permission for adding an object to repository database ./objects remote: fatal: failed to write object
Чтобы решить эту проблему, вам нужно иметь в виду систему системных разрешений, поскольку в этом случае вы ограничены ею. Tu лучше поймите проблему, идите в свою папку объектов git (.git/objects). Вероятно, вы увидите что-то подобное:
<your user_name>@<the machine name> objects]$ ls -la
total 200
drwxr-xr-x 25 <your user_name> <group_name> 2048 Feb 10 09:28 .
drwxr-xr-x 3 <his user_name> <group_name> 1024 Feb 3 15:06 ..
drwxr-xr-x 2 <his user_name> <group_name> 1024 Jan 31 13:39 02
drwxr-xr-x 2 <his user_name> <group_name> 1024 Feb 3 13:24 08
* Обратите внимание, что эти разрешения для файлов были предоставлены только для ваших пользователей, никто никогда не сможет его изменить… *
Level u g o
Permission rwx r-x ---
Binary 111 101 000
Octal 7 5 0
РЕШЕНИЕ ПРОБЛЕМЫ
Если у вас есть права суперпользователя, вы можете перейти и изменить все разрешения самостоятельно, используя второй шаг, в любом другом случае вам нужно будет спросить всех пользователей о объектах, созданных с их пользователями, используйте следующую команду, чтобы знать кто они:
$ ls -la | awk '{print $3}' | sort -u
<your user_name>
<his user_name>
Теперь вам и всем владельцам файлов необходимо будет изменить разрешение этих файлов:
$ chmod -R 774 .
После этого вам нужно будет добавить новое свойство, эквивалентное —shared = group done для нового репозитория, в соответствии с документацией, это сделает репозиторий доступным для группы, выполнив его:
$ git config core.sharedRepository group
https://coderwall.com/p/8b3ksg
I accidentally messed up with the file owners (chown on the wrong level…) on my self-hosted Gitlab running in a Docker container. I managed to restore most of the ownerships.
This was done by running docker exec gitlab_container_name update-permissions
. However, this did not immediately fix the problem as the logs still showed a permission denied error for the grafana db. In oder to fix this, I continued by setting up a fresh Gitlab and comparing/restoring the ownership.
While Gitlab itself is now running again, I still get the following errors:
- When I try to push, I receive:
remote: GitLab: Push operation timed out
remote:
remote: Timing information for debugging purposes:
remote: Running checks for ref: XXXX
remote: Checking if you are allowed to push... (62.94ms)
remote: Checking if default branch is being deleted... (0.31ms)
remote: Scanning repository for blobs stored in LFS and verifying their files have been uploaded to GitLab... (cancelled after 29547.57ms)
To http://gitlab.XXXX.XX/XXXX/XXXX.git
! [remote rejected] XXXXX -> XXXX (pre-receive hook declined)
error: failed to push some refs to 'http://gitlab.XXXX.XX/XXXX/XXXX.git'
- When I click on a project in the web UI it shows information such as the branches, total file size, etc., but not the list of files/files itself. Rather
**An error occurred while fetching folder content.**
is displayed.
Running gitlab-ctl tail
while trying to push shows the following:
{"level":"info","msg":"I, [2021-07-05T17:13:19.676164 #3372254] INFO -- sentry: ** [Raven] Raven 3.0.4 configured not to capture errors: DSN not set","supervisor.args":["bundle","exec","bin/ruby-cd","/var/opt/gitlab/gitaly","/opt/gitlab/embedded/service/gitaly-ruby/bin/gitaly-ruby","3368488","/var/opt/gitlab/gitaly/internal_sockets/ruby.0"],"supervisor.name":"gitaly-ruby.0","time":"2021-07-05T17:13:19.692Z"}
{"error":"exit status 1","level":"warning","msg":"exited","supervisor.args":["bundle","exec","bin/ruby-cd","/var/opt/gitlab/gitaly","/opt/gitlab/embedded/service/gitaly-ruby/bin/gitaly-ruby","3368488","/var/opt/gitlab/gitaly/internal_sockets/ruby.0"],"supervisor.name":"gitaly-ruby.0","time":"2021-07-05T17:13:19.698Z"}
{"level":"info","msg":"I, [2021-07-05T17:13:20.817759 #3372257] INFO -- sentry: ** [Raven] Raven 3.0.4 configured not to capture errors: DSN not set","supervisor.args":["bundle","exec","bin/ruby-cd","/var/opt/gitlab/gitaly","/opt/gitlab/embedded/service/gitaly-ruby/bin/gitaly-ruby","3368488","/var/opt/gitlab/gitaly/internal_sockets/ruby.1"],"supervisor.name":"gitaly-ruby.1","time":"2021-07-05T17:13:20.835Z"}
{"error":"exit status 1","level":"warning","msg":"exited","supervisor.args":["bundle","exec","bin/ruby-cd","/var/opt/gitlab/gitaly","/opt/gitlab/embedded/service/gitaly-ruby/bin/gitaly-ruby","3368488","/var/opt/gitlab/gitaly/internal_sockets/ruby.1"],"supervisor.name":"gitaly-ruby.1","time":"2021-07-05T17:13:20.843Z"}
[...]
{"correlation_id":"01F9VTFEM5X7N2PZR6WVDAQQYN","error":"GitLab: Push operation timed out\n\nTiming information for debugging purposes:\nRunning checks for ref: XXXX\nChecking if you are allowed to push... (13.42ms)\nChecking if default branch is being deleted... (0.43ms)\nScanning repository for blobs stored in LFS and verifying their files have been uploaded to GitLab... (cancelled after 29583.1ms)","grpc.meta.deadline_type":"none","grpc.method":"PreReceiveHook","grpc.request.fullMethod":"/gitaly.HookService/PreReceiveHook","grpc.request.glProjectPath":"XXXX/XXXX","grpc.request.glRepository":"project-5","grpc.request.repoPath":"@hashed/ef/2d/ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d.git","grpc.request.repoStorage":"default","grpc.request.topLevelGroup":"@hashed","grpc.service":"gitaly.HookService","grpc.start_time":"2021-07-05T17:11:59.178Z","level":"warning","msg":"stopping transaction because pre-receive hook failed","peer.address":"@","pid":3368488,"span.kind":"server","system":"grpc","time":"2021-07-05T17:12:29.025Z"}
Does anyone know how to fix this issue?
EDIT: I sdded the information about docker exec gitlab_container_name update-permissions
as discussed in the comments.
I have a GitLab project which is set up as follows:
myserver.com/SuperGroup/SubGroup/SubGroupProject
The tree of the following project is a top-level txt file and a txt file within a directory. I get the tree from the GitLab API with:
myserver.com/api/v4/projects/1/repository/tree?recursive=true
[{«id»:»aba61143388f605d3fe9de9033ecb4575e4d9b69″,»name»:»myDirectory»,»type»:»tree»,»path»:»myDirectory»,»mode»:»040000″},{«id»:»0e3a2b246ab92abac101d0eb2e96b57e2d24915d»,»name»:»1stLevelFile.txt»,»type»:»blob»,»path»:»myDirectory/1stLevelFile.txt»,»mode»:»100644″},{«id»:»3501682ba833c3e50addab55e42488e98200b323″,»name»:»top_level.txt»,»type»:»blob»,»path»:»top_level.txt»,»mode»:»100644″}]
If I request the contents for top_level.txt
they are returned without any issue via:
myserver.com/api/v4/projects/1/repository/files/top_level.txt?ref=master
However I am unable to access myDirectory/1stLevelFile.txt
with any API call I try. E.g.:
myserver.com/api/v4/projects/1/repository/files/"myDirectory%2F1stLevelFile.txt"?ref=master
and,myserver.com/api/v4/projects/1/repository/files/"myDirectory%2F1stLevelFile%2Etxt"?ref=master
Results in:
Not Found The requested URL /api/v4/projects/1/repository/files/myDirectory/1stLevelFile.txt was not found on this server.
Apache/2.4.25 (Debian) Server at myserver.com Port 443
myserver.com/api/v4/projects/1/repository/files/"myDirectory/1stLevelFile.txt"?ref=master
and,myserver.com/api/v4/projects/1/repository/files?ref=master&path=myDirectory%2F1stLevelFile.txt
Results in:
error «404 Not Found»
The versions of the components are:
GitLab 10.6.3-ee
GitLab Shell 6.0.4
GitLab Workhorse v4.0.0
GitLab API v4
Ruby 2.3.6p384
Rails 4.2.10
postgresql 9.6.8
According to my research there was a similar bug which was fixed with the 10.0.0 update.
I also added my ssh-key although I doubt it has any effect, following this advice with the same issue in php.
Solution:
I eventually solved it by adjusting the apache installed on the server.
Just follow these instructions: https://gitlab.com/gitlab-org/gitlab-ce/issues/35079#note_76374269