Solve the problem: git fetch origin hangs
Problem Statement
Problem Statement
In my previous article, I mentioned how to check new commits from git, but I encounter a problem which is the command git fetch origin
will hang, it was caused by I make a schedule to run it every half hours, and the network on the machine that run the script are not stable sometimes, if the script run on the time that network is poor, it will hang on git fetch origin
command.
Reproduce the problem
In order to reproduce the problem, I find that I can use the Network Link Conditioner
on mac, the Network Link Conditioner
was in Additional Tools for Xcode
, after download the tool, it’s a dmg file, and inside the dmg file, the tool was located in Hardware/Network Link Conditioner.prefPane
.
After install the Network Link Conditioner
, we can change the network to 100% Loss
, then run the git fetch origin
command, the command will hang.
The solutions to solve the problem
The solution I found was set the connect timeout for get fetch
, there are several solutions that we can use.
Solution 1
Set the timeout options on the command like below:GIT_SSH_COMMAND="ssh -o ConnectTimeout=10" git fetch origin
The command above set the timeout to 10 seconds, so it will timeout if the network is not stable.
Solution 2
The second solution is set the timeout on the ~/.ssh/config
, we can set it for all hosts or just the specify host like below:# The setting will be for all hosts
Host *
ConnectTimeout 10# The setting will be apply to github.com only
Host github.com
ConnectTimeout 10
Another problem
After test with different git server, I find another problem, when I connect to the server with IP address configured in ~/.ssh/config
, it will work, but for public server such as github.com, when I set network 100% loss
, it will report error after 30s like below:ssh: Could not resolve hostname github.com: nodename nor servname provided, or not known
fatal: Could not read from remote repository.Please make sure you have the correct access rights
and the repository exists.real 0m30.021s
But if I didn’t specify the ConnectTimeout
option, the operation will hang, so it’s better than hang, but I still need to investigate why the timeout will be 30 seconds when the network is 100% loss
.
Updated: The issue still exists, so I use another solution to solve the problem.
I hope that the article can help you on some way. Thanks for your time!