rideler
rideler

Reputation: 66

Gitlab job fails because of a while loop

I have a gitlab job that keeps on failing if i'm adding this while loop to it:

- while [ ! $PID ] ;do sleep 60;PID=$(ps -ef | grep Runner |grep java | awk '{print $3}'| tail -n1);echo "waiting for $PID";  done

I'm sure this is the problem because without this specific line I manage to have a successful job run.

Here is the gitlab_ci.yaml:

stages:
  - deploy
  - test
deploy:
  stage: deploy
  when: always
  script:
    -irrelevant code that always works
test:
  stage: test
  when: always
  needs: [deploy]
  script:
    - while [ ! $PID ] ;do sleep 60;PID=$(ps -ef | grep Runner |grep java);echo "waiting for $PID to Finish before testing";  done
    - command that starts the testing and also always works
    - PID=0
    - while [ ! $PID ] ;do sleep 60;PID=$(ps -ef | grep Runner |grep java);echo "waiting for $PID";  done
    - echo "Finish"
  artifacts:
    when: always
    paths:
      - src/

The job can successfully run the first while loop. The issue with the second loop is that when it finish the whole gitlab job fails and it doesn't run the echo "finish" command.

I'm using the while command and not wait because wait command only works if the process is something you initiated and not someone else like this case. Also i'm not using sleep as the times of the process i'm tracking changes from run to run.

Upvotes: 1

Views: 988

Answers (1)

KamilCuk
KamilCuk

Reputation: 141040

When pid is empty then [ ! -f $PID ] then $PID expands to nothing, in which case the following:

[ ! -f ]

is executed. From man test:

   -n STRING
          the length of STRING is nonzero

   STRING equivalent to -n STRING

Because the length of -f string is nonzero, the ! is negation, the [ command returns failure.

Because the file with the result of expansion of $PID does not exists, the second loop is an endless loop.

Remember to check your scripts with shellcheck.net . Learn about quoting in shell and when to use it and always use it. Quote variable expansions - "$PID".

And, anyway, if you want to wait for a PID do not check if a filename with the PID name exists. Instead, wait for the exit status of script pipe to be zero:

- while ! ps -ef | grep Runner | grep -q java; do
     sleep 60;
     echo "somthing";
  done

If available, use pgrep instead. Split long lines with newlines - see gitlab-ci documentation.

Upvotes: 1

Related Questions