Skip to content

Commit

Permalink
feat: add --python-binary-name flag to specify Python name to install…
Browse files Browse the repository at this point in the history
… libraries (#485)

* feat: add --python-binary-name flag to specify Python name to install libraries

* refactor: rename files and functions

* test: add tests for install_python_libraries
  • Loading branch information
artemrys authored Aug 2, 2022
1 parent 3392625 commit bc46170
Show file tree
Hide file tree
Showing 4 changed files with 242 additions and 89 deletions.
10 changes: 9 additions & 1 deletion docs/how_to_use.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ Example of globalConfig.json and package folder can be found at
Steps
-----

- Install `splunk-add-on-ucc-framework` if it is not installed.
- Use Python virtual environment:
- `python3 -m venv .venv`
- `source .venv/bin/activate`
- Install `splunk-add-on-ucc-framework`.
- Run the `ucc-gen` command.
- The final addon package will be generated, in the `output` folder.

Expand All @@ -28,6 +31,8 @@ ucc-gen supports the following params:
- ta-version - [optional] override current version of TA, default
version is version specified in `globalConfig.json`. Splunkbase
compatible version of SEMVER will be used by default.
- python-binary-name - [optional] Python binary name to use when
installing Python libraries.

```
pip install splunk-packaging-toolkit
Expand All @@ -51,6 +56,9 @@ What ucc-gen does
following table:
- `lib/requirements.txt` - install Python3 compatible packages into
`output/<package_ID>/lib`
- Removes `setuptools*`, `bin*`, `pip*`, `distribute*`, `wheel*` if
they exist from `output/<package_ID>/lib`
- Removes execute bit from every file under `output/<package_ID>/lib`
- Replace tokens in views.
- Copy addon's `package/*` to `output/<package_ID>/*` directory.
- If an addon requires some additional configurations in packaging
Expand Down
115 changes: 27 additions & 88 deletions splunk_add_on_ucc_framework/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@
import logging
import os
import shutil
import stat
import sys
from pathlib import Path

from defusedxml import ElementTree as defused_et
from dunamai import Style, Version
Expand All @@ -41,6 +39,9 @@
GlobalConfigValidator,
GlobalConfigValidatorException,
)
from splunk_add_on_ucc_framework.install_python_libraries import (
install_python_libraries,
)
from splunk_add_on_ucc_framework.meta_conf import MetaConf
from splunk_add_on_ucc_framework.start_alert_build import alert_build
from splunk_add_on_ucc_framework.uccrestbuilder import build
Expand Down Expand Up @@ -297,86 +298,6 @@ def replace_token(ta_name, outputdir):
f.write(s)


def install_libs(path, ucc_lib_target):
"""
Install 3rd Party libraries in addon.
Args:
parent_path (str): Path of parent directory.
ucc_lib_target (str): Target path to install libraries.
"""

def _install_libs(requirements, ucc_target, installer="python3"):
"""
Install 3rd Party libraries using pip2/pip3
Args:
requirements (str): Path to requirements file.
ucc_target (str): Target path to install libraries.
installer (str): Pip version(pip2/pip3).
"""
if not os.path.exists(requirements):
logger.warning(f"Unable to find requirements file. {requirements}")
else:
if not os.path.exists(ucc_target):
os.makedirs(ucc_target)
install_cmd = (
installer
+ ' -m pip install -r "'
+ requirements
+ '" --no-compile --prefer-binary --ignore-installed --use-deprecated=legacy-resolver --target "'
+ ucc_target
+ '"'
)
os.system(installer + " -m pip install pip --upgrade")
os.system(install_cmd)

logger.info(f" Checking for requirements in {path}")
if os.path.exists(os.path.join(path, "lib", "requirements.txt")):
logger.info(" Uses common requirements")
_install_libs(
requirements=os.path.join(path, "lib", "requirements.txt"),
ucc_target=ucc_lib_target,
)
elif os.path.exists(
os.path.join(os.path.abspath(os.path.join(path, os.pardir)), "requirements.txt")
):
logger.info(" Uses common requirements")
_install_libs(
requirements=os.path.join(
os.path.abspath(os.path.join(path, os.pardir)), "requirements.txt"
),
ucc_target=ucc_lib_target,
)
else:
logger.info(" Not using common requirements")

# Prevent certain packages from being included pip could be dangerous others are just wasted space
noshipdirs = ["setuptools", "bin", "pip", "distribute", "wheel"]
p = Path(ucc_lib_target)
for nsd in noshipdirs:
try:
# Glob can return FileNotFoundError exception if no match
for o in p.glob(nsd + "*"):
if o.is_dir():
logging.info(f" removing directory {o} from output must not ship")
shutil.rmtree(o)
except FileNotFoundError:
pass

# Remove execute bit from any object in lib
NO_USER_EXEC = ~stat.S_IEXEC
NO_GROUP_EXEC = ~stat.S_IXGRP
NO_OTHER_EXEC = ~stat.S_IXOTH
NO_EXEC = NO_USER_EXEC & NO_GROUP_EXEC & NO_OTHER_EXEC

for o in p.rglob("*"):
if not o.is_dir() and os.access(o, os.X_OK):
logging.info(f" fixing {o} execute bit")
current_permissions = stat.S_IMODE(os.lstat(o).st_mode)
os.chmod(o, current_permissions & NO_EXEC)


def generate_rest(ta_name, scheme, import_declare_name, outputdir):
"""
Build REST for Add-on.
Expand Down Expand Up @@ -683,8 +604,9 @@ def _removeinput(path):
pass


def _generate(source, config, ta_version, outputdir=None):
def _generate(source, config, ta_version, outputdir=None, python_binary_name="python3"):
logger.info(f"ucc-gen version {__version__} is used")
logger.info(f"Python binary name to use: {python_binary_name}")
if outputdir is None:
outputdir = os.path.join(os.getcwd(), "output")
if not ta_version:
Expand Down Expand Up @@ -782,7 +704,7 @@ def _generate(source, config, ta_version, outputdir=None):
)
ucc_lib_target = os.path.join(outputdir, ta_name, "lib")
logger.info(f"Install add-on requirements into {ucc_lib_target} from {source}")
install_libs(source, ucc_lib_target)
install_python_libraries(logger, source, ucc_lib_target, python_binary_name)

replace_token(ta_name, outputdir)

Expand All @@ -806,7 +728,7 @@ def _generate(source, config, ta_version, outputdir=None):
ucc_lib_target = os.path.join(outputdir, ta_name, "lib")

logger.info(f"Install add-on requirements into {ucc_lib_target} from {source}")
install_libs(source, ucc_lib_target=ucc_lib_target)
install_python_libraries(logger, source, ucc_lib_target, python_binary_name)

ignore_list = get_ignore_list(
ta_name, os.path.abspath(os.path.join(source, PARENT_DIR, ".uccignore"))
Expand Down Expand Up @@ -861,8 +783,14 @@ def _generate(source, config, ta_version, outputdir=None):
additional_packaging(ta_name)


def generate(source="package", config=None, ta_version=None, outputdir=None):
_generate(source, config, ta_version, outputdir)
def generate(
source="package",
config=None,
ta_version=None,
outputdir=None,
python_binary_name="python3",
):
_generate(source, config, ta_version, outputdir, python_binary_name)


def main():
Expand All @@ -888,5 +816,16 @@ def main():
"package such as app.manifest, app.conf, and globalConfig.json",
default=None,
)
parser.add_argument(
"--python-binary-name",
type=str,
help="Python binary name to use to install requirements",
default="python3",
)
args = parser.parse_args()
_generate(args.source, args.config, args.ta_version)
_generate(
args.source,
args.config,
args.ta_version,
python_binary_name=args.python_binary_name,
)
109 changes: 109 additions & 0 deletions splunk_add_on_ucc_framework/install_python_libraries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
#
# Copyright 2021 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging
import os
import shutil
import stat
from pathlib import Path
from typing import Sequence


def install_python_libraries(
logger: logging.Logger, path: str, ucc_lib_target: str, python_binary_name: str
):
logger.info(f" Checking for requirements in {path}")
if os.path.exists(os.path.join(path, "lib", "requirements.txt")):
logger.info(" Uses common requirements")
install_libraries(
logger,
os.path.join(path, "lib", "requirements.txt"),
ucc_lib_target,
python_binary_name,
)
elif os.path.exists(
os.path.join(os.path.abspath(os.path.join(path, os.pardir)), "requirements.txt")
):
logger.info(" Uses common requirements")
install_libraries(
logger,
os.path.join(
os.path.abspath(os.path.join(path, os.pardir)), "requirements.txt"
),
ucc_lib_target,
python_binary_name,
)
else:
logger.info(" Not using common requirements")

packages_to_remove = ["setuptools", "bin", "pip", "distribute", "wheel"]
remove_package_from_installed_path(
logger,
ucc_lib_target,
packages_to_remove,
)

remove_execute_bit(logger, ucc_lib_target)


def install_libraries(
logger: logging.Logger,
requirements_file_path: str,
installation_path: str,
installer: str,
):
if not os.path.exists(requirements_file_path):
logger.warning(f"Unable to find requirements file: {requirements_file_path}")
else:
if not os.path.exists(installation_path):
os.makedirs(installation_path)
install_cmd = (
installer
+ ' -m pip install -r "'
+ requirements_file_path
+ '" --no-compile --prefer-binary --ignore-installed --use-deprecated=legacy-resolver --target "'
+ installation_path
+ '"'
)
os.system(installer + " -m pip install pip --upgrade")
os.system(install_cmd)


def remove_package_from_installed_path(
logger: logging.Logger, installation_path: str, package_names: Sequence[str]
):
p = Path(installation_path)
try:
for package_name in package_names:
for o in p.glob(f"{package_name}*"):
if o.is_dir():
logger.info(f" removing directory {o} from {installation_path}")
shutil.rmtree(o)
except FileNotFoundError:
pass


def remove_execute_bit(logger: logging.Logger, installation_path: str):
p = Path(installation_path)
no_user_exec = ~stat.S_IEXEC
no_group_exec = ~stat.S_IXGRP
no_other_exec = ~stat.S_IXOTH
no_exec = no_user_exec & no_group_exec & no_other_exec

for o in p.rglob("*"):
if not o.is_dir() and os.access(o, os.X_OK):
logger.info(f" fixing {o} execute bit")
current_permissions = stat.S_IMODE(os.lstat(o).st_mode)
os.chmod(o, current_permissions & no_exec)
Loading

0 comments on commit bc46170

Please sign in to comment.