How can I make jenkins run "pip install"? - jenkins

I have a git repo and would like to get jenkins to clone it then run
virtualenv venv --distribute
/bin/bash venv/source/activate
pip install -r requirements.txt
python tests.py
The console output from jenkins is:
+ virtualenv venv --distribute
New python executable in venv/bin/python
Installing distribute..........................done.
Installing pip...............done.
+ /bin/bash venv/bin/activate
+ pip install -r requirements.txt
Downloading/unpacking flask (from -r requirements.txt (line 1))
Running setup.py egg_info for package flask
SNIP
creating /usr/local/lib/python2.7/dist-packages/flask
error: could not create '/usr/local/lib/python2.7/dist-packages/flask': Permission denied
----------------------------------------
Command /usr/bin/python -c "import setuptools;__file__='/var/lib/jenkins/workspace/infatics-website/build/flask/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-hkdBAi-record/install-record.txt failed with error code 1
Storing complete log in /home/jenkins/.pip/pip.log
Build step 'Execute shell' marked build as failure
Finished: FAILURE
I've tried adding sudo before the command, but it's doesn't work either:
+ sudo pip install -r requirements.txt
sudo: no tty present and no askpass program specified
Sorry, try again.
sudo: no tty present and no askpass program specified
Sorry, try again.
sudo: no tty present and no askpass program specified
Sorry, try again.
sudo: 3 incorrect password attempts
Build step 'Execute shell' marked build as failure
Finished: FAILURE
Any ideas how to get around this? Also when I run pip install -r requirement.txt in a terminal as the jenkins user it doesn't need sudo permission. Can I get jenkins (the process) to run as the jenkins user?

The fact that you have to run use sudo to run pip is a big warning that your virtual environment isn't working. The build output shows that pip is installing the requirements in your system site-packages directory, which is not the way virtualenv works.
Your build script doesn't actually preserve the activated virtual environment. The environment variables set by the activate script are set in a child bash process and are not propagated up to the build script. You should source the activate script instead of running a separate shell:
virtualenv venv --distribute
. venv/bin/activate
pip install -r requirements.txt
python tests.py
If you're running this as one build step, that should work (and install your packages in venv). If you want to add more steps, you'll need to set the PATH environment variable in your other steps. You're probably better off providing full paths to pip and python to ensure you're not dependent on system package installations.

Try using
stage('test') {
agent {
docker {
image 'qnib/pytest'
}
}
steps {
sh 'virtualenv venv && . venv/bin/activate && pip install -r requirements.txt && python tests.py'
}
}

I totally agree what has been said.... But to make this more "Jenkins"
Create a basic Project - and in the custom steps do something like this
PROJECT="Tree"
rm -Rf ~/Builds/$PROJECT
CODE_HOME=~/Builds/$PROJECT/code
PYENV_HOME=~/Builds/$PROJECT/python
export PYENV_HOME
export PYTHONPATH=""
echo "Creating new Python env"
/usr/local/bin/python3 -m venv --clear $PYENV_HOME
source $PYENV_HOME/bin/activate
echo "Get Project"
mkdir -p $CODE_HOME
cd $CODE_HOME
git clone https://github.com/MyUsername/MyTree.git .
pip install --upgrade pip
pip install nose
pip install coverage
pip install -r requirements.txt
python setup.py build
python setup.py install
After this you can then do you nose tests etc...

Here is what I did to make Jenkins execute pip install requirements on Windows machine:
In "Execute Windows batch command" pipeline
REM activate venv, update pip and install package
cmd /k "cd <path to your directory like C:\WebAPI> & .\venv\Scripts\activate.bat & python -m pip install -U pip & pip install -r .\requirements.txt"
cmd /k executes windows command prompt and you can add any commands there. & is a pipeline operator. So you can have multiple commands

Related

Getting 0% coverage in Sonarqube , Using nosetests for generating coverage.xml

I'm working on a project where code coverage needs to display in Sonarqube.
We are framing dockerfile.test where at ENTRYPOINT nosetests is provided. setup.cfg file is created putting all required nosetests plugins. Then sonar-project.properties file has been created for sonarqube reference. And a stage named "Test/Sonar" is created in jenkins ,
below has the script of all above mentioned files.
FROM python:3.7-slim
RUN apt-get update && apt-get install -y --no-install-recommends gcc gfortran perl libtest-utf8-perl \
libtest-file-perl libtest-files-perl cpanminus build-essential curl libcurl4-openssl-dev libssl-dev \
gfortran liblzma-dev libblas-dev liblapack-dev libpq-dev procps libldap2-dev libsasl2-dev ldap-utils git
RUN cpanm install File::Copy::Recursive
RUN pip install numpy && pip install scipy pandas scikit-learn
COPY requirements.txt /requirements.txt
RUN pip install --no-cache-dir -r /requirements.txt
COPY test_requirements.txt /test_requirements.txt
RUN pip install --no-cache-dir -r /test_requirements.txt
COPY . /app
WORKDIR /app
#Install Mim
RUN python mim-python-client/setup.py install
RUN mkdir -p /local/tmp/mim-cache
RUN chmod -R 777 /local/tmp/mim-cache
#Install Extract
WORKDIR /app/extract-rules
RUN bash --posix ./dev/build.sh
RUN cp ./bin/python_parser.py /opt/extract/bin/
WORKDIR /app/backend/worker
ENV PYTHONUNBUFFERED=1
ENTRYPOINT nosetests
[nosetests]
verbose=3
with-xunit=1
xunit-file=nosetests.xml
with-coverage=1
cover-xml=1
cover-package=.
exclude-dir=test
sonar.projectKey=IPA_NIP
sonar.projectName=IPA_NIP
sonar.projectVersion=1.0.0
sonar.language=py
sonar.sourceEncoding=UTF-8
sonar.python.coverage.reportPaths=coverage.xml
sonar.python.xunit.reportPaths=nosetests.xml
sonar.python.xunit.skipDetails=false
sonar.sources=backend/orch, backend/worker, webserver/pinap
sonar.typescript.lcov.reportPaths=coverage/IPA_NIP/lcov.info
sonar.python.coveragePlugin=cobertura
stage ('Test/Sonar') {
steps {
// This specific examples expects that you have a Dockerfile.test that you build, then run to generate test results.
// Since different projects can vary however, you should make sure you use the solution that works best for you.
sh "docker build . -f Dockerfile.test -t python-test:${BUILD_ID}"
sh '''docker run -u 50001255:25 -v "$(pwd)":/app python-test:${BUILD_ID}'''
sh '''sed -i 's|filename="|filename="'"$(pwd)"'/|' coverage.xml'''
sonarScan('Sonar')
}
// Make test results visible in Jenkins UI if the install step completed successfully
post {
success {
junit testResults: 'nosetests.xml', allowEmptyResults: true
}
}
}
I couldn't able to find why I'm getting 0% coverage at sonarqube.
dockerfile.test is executing without any error. I'm getting status about tests (Unit test) as OK. But I'm getting a warning
WARN: The report '/apps/dftjenkins/jenkins_node/workspace/v_AutomationAuthenticationScript/coverage.xml' seems to be empty, ignoring. '{}'
org.sonar.plugins.python.EmptyReportException: null
Could anyone help me out with my queries?

Docker Image-pip3 Not Found

I'm trying to build a Docker image on Ubuntu 20.04 WSL for Windows 10 and keep running into the following error when Docker gets to the step to run pip3 install:
/bin/sh: 1: pip3: not found
The command '/bin/sh -c pip3 install -r /tmp/requirements.txt' returned a non-zero code: 127
The Dockerfile is:
FROM ubuntu:20.04
COPY bots/art_print.py /bots/
COPY requirements.txt /tmp/
RUN pip3 install -r /tmp/requirements.txt
WORKDIR /bots
CMD ["python3", "art-print-bot"]
I've uninstalled and reinstalled pip3 and verified that it is there with $ which pip3
/usr/bin/pip3
Any ideas as to why the Docker build is not recognizing pip3?
Looks like you may have an issue with your PATH environment variable. Try changing the pip RUN line to:
RUN python3 -m pip install -r /tmp/requirements.txt

Activate conda env and run pip install requirements in the Dockfile

I can create my virtual environment dev1 successfully, but I can not activate it and switch into in during the Docker building.
All I want is to switch the venv and install my dependencies in requirements.txt.
My code:
WORKDIR /APP
ADD . /APP
ARG CONDA_VENV=dev1
RUN conda create -y --name ${CONDA_VENV} python=3.7
RUN conda activate ${CONDA_VENV}
RUN pip install -r requirements.txt
Error:
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run
$ conda init <SHELL_NAME>
Currently supported shells are:
- bash
- fish
- tcsh
- xonsh
- zsh
- powershell
See 'conda init --help' for more information and options.
IMPORTANT: You may need to close and restart your shell after running 'conda init'.
The command '/bin/sh -c conda activate ${CONDA_VENV}' returned a non-zero code: 1

docker build failed at 'Downloading mariadb'

Executing 'docker build -t $name .' failed at following issue. It shows 'mariadb_config not found', but i already installed mariadb on this suse15 linux server.
Collecting mariadb==1.0.4
Downloading mariadb-1.0.4.tar.gz (66 kB)
ERROR: Command errored out with exit status 1:
command: /usr/local/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-lxx0giq5/mariadb/setup.py'"'"'; __file__='"'"'/tmp/pip-install-lxx0giq5/mariadb/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-hicsuruq
cwd: /tmp/pip-install-lxx0giq5/mariadb/
Complete output (17 lines):
/bin/sh: 1: mariadb_config: not found
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-install-lxx0giq5/mariadb/setup.py", line 26, in <module>
cfg = get_config(options)
File "/tmp/pip-install-lxx0giq5/mariadb/mariadb_posix.py", line 59, in get_config
cc_version = mariadb_config(config_prg, "cc_version")
File "/tmp/pip-install-lxx0giq5/mariadb/mariadb_posix.py", line 29, in mariadb_config
"mariadb_config not found.\n\nPlease make sure, that MariaDB Connector/C is installed on your system.\n"
OSError: mariadb_config not found.
Please make sure, that MariaDB Connector/C is installed on your system.
Either set the environment variable MARIADB_CONFIG or edit the configuration
file 'site.cfg' and set the 'mariadb_config option, which should point
to the mariadb_config utility.
The MariaDB Download website at <https://downloads.mariadb.com/Connectors/c/>
provides latest stable releease of Connector/C.
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
The command '/bin/sh -c pip3 install -r requirements.txt' returned a non-zero code: 1
And related Dockerfile content is as follows.
FROM python:3.6.5
WORKDIR /slic-scripts
COPY requirements.txt .
RUN pip install --upgrade pip
RUN pip3 install -r requirements.txt
COPY . .
CMD ["python3", "/slic-scripts/run_cmd.sh"]
As #Jonathan Jacobson wrote, you need to have the MariaDB Connector installed in your Docker image before proceeding with pip install.
Since python:3.6.5 is based on debian stretch, the connector offered there is 2.3.2 which is not supported by the mariadb module (as stated in the prerequisites). To fix this, you might want to switch to a different image (e.g. 3.6-buster).
Here's a working test:
FROM python:3.6-buster
RUN apt-get update \
&& apt-get -yy install libmariadb-dev
WORKDIR /slic-scripts
COPY requirements.txt .
RUN pip install --upgrade pip
RUN pip3 install -r requirements.txt
COPY . .
CMD ["python3", "/slic-scripts/run_cmd.sh"]
You need to install MariaDB Connector/C inside the Dockerfile, before running pip3 install. It doesn't help that you installed it on your host.
Install MariaDB Connector/C using the below command, which is a dependency.
sudo apt-get install libmariadb3 libmariadb-dev
RUN pip3 install -r requirements.txt

Jenkinsfile- virtualenv command not found

I have a local jenkinsserver thats running on http://localhost:8080 in my personal MAC machine.
Now, I have created a sample Jenkinsfile and trying to run through Jenkins job.
stage ('Install_Requirements') {
steps {
sh """
echo ${SHELL}
[ -d venv ] && rm -rf venv
#virtualenv --python=python2.7 venv
virtualenv venv
#. venv/bin/activate
export PATH=${VIRTUAL_ENV}/bin:${PATH}
pip install --upgrade pip
pip install -r requirements.txt -r dev-requirements.txt
make clean
"""
}
}
There are multiple stages in the projects but when I execute this 'Install_Requirements' stage I get a error :-
[python-jenkinsfile-testing] Running shell script
+ echo /bin/bash
/bin/bash
+ '[' -d venv ']'
+ virtualenv venv
/Users/Shared/Jenkins/Home/workspace/python-jenkinsfile-testing#tmp/durable-4363725f/script.sh: line 6: virtualenv: command not found
When I try to execute virtualenv venv command on my terminal it creates the venv and I'm also able to activate the environment.
Not sure why I get this error.

Resources