3 # COPYRIGHT NOTICE STARTS HERE
5 # Copyright 2018-2019 © Samsung Electronics Co., Ltd.
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
11 # http://www.apache.org/licenses/LICENSE-2.0
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
19 # COPYRIGHT NOTICE ENDS HERE
21 ### This script prepares Nexus repositories data blobs for ONAP
23 ## The script requires following dependencies are installed: nodejs, jq, docker, twine
24 ## All required resources are expected in the upper directory created during
25 ## download procedure as DATA_DIR or in the directory given as --input-directory
26 ## All lists used must be in project data_lists directory or in the directory given
27 ## as --resource-list-directory
32 TIMESTAMP="date +'%Y-%m-%d_%H-%M-%S'"
33 SCRIPT_LOG="/tmp/$(basename $0)_$(eval ${TIMESTAMP}).log"
36 exec &> >(tee -a "${SCRIPT_LOG}")
38 # Nexus repository location
41 NEXUS_DOCKER_PORT="8082"
42 NPM_REGISTRY="http://${NEXUS_DOMAIN}:${NEXUS_PORT}/repository/npm-private/"
43 PYPI_REGISTRY="http://${NEXUS_DOMAIN}:${NEXUS_PORT}/repository/pypi-private/"
44 DOCKER_REGISTRY="${NEXUS_DOMAIN}:${NEXUS_DOCKER_PORT}"
45 DEFAULT_REGISTRY="docker.io"
47 # Nexus repository credentials
49 NEXUS_PASSWORD=admin123
50 NEXUS_EMAIL=admin@example.org
53 LOCAL_PATH="$(readlink -f $(dirname ${0}))"
57 DATA_DIR="$(realpath ${LOCAL_PATH}/../../resources)"
58 NEXUS_DATA_DIR="${DATA_DIR}/nexus_data"
59 LISTS_DIR="${LOCAL_PATH}/data_lists"
62 echo " Example usage: build_nexus_blob.sh --input-directory </path/to/downloaded/files/dir> --output-directory
63 </path/to/output/dir> --resource-list-directory </path/to/dir/with/resource/list> [--load-docker-images]
65 -i | --input-directory directory containing file needed to create nexus blob. The structure of this directory must organized as described in build guide
66 -ld | --load-docker-images load docker images from stored files in the input directory
67 -o | --output-directory
68 -rl | --resource-list-directory directory with files containing docker, pypi and npm lists
73 load_docker_images () {
74 for ARCHIVE in $(sed $'s/\r// ; /^#/d ; s/\:/\_/g ; s/\//\_/g ; s/$/\.tar/g' ${1} | awk '{ print $1 }'); do
75 docker load -i ${NXS_SRC_DOCKER_IMG_DIR}/${ARCHIVE}
79 while [ "${1}" != "" ]; do
81 -i | --input-directory ) shift
84 -ld | --load-docker-images ) DOCKER_LOAD="true"
86 -o | --output-directory ) shift
89 -rl | --resource-list-directory ) shift
99 # Setup directories with resources for docker, npm and pypi
100 NXS_SRC_DOCKER_IMG_DIR="${DATA_DIR}/offline_data/docker_images_for_nexus"
101 NXS_SRC_NPM_DIR="${DATA_DIR}/offline_data/npm_tar"
102 NXS_SRC_PYPI_DIR="${DATA_DIR}/offline_data/pypi"
104 # Setup specific resources lists
105 NXS_DOCKER_IMG_LIST="${LISTS_DIR}/onap_docker_images.list"
106 NXS_NPM_LIST="${LISTS_DIR}/onap_npm.list"
107 NXS_PYPI_LIST="${LISTS_DIR}/onap_pip_packages.list"
109 # Setup Nexus image used for build and install infra
110 INFRA_LIST="${LISTS_DIR}/infra_docker_images.list"
111 NEXUS_IMAGE="$(grep sonatype/nexus3 ${INFRA_LIST})"
112 NEXUS_IMAGE_TAR="${DATA_DIR}/offline_data/docker_images_infra/$(sed 's/\//\_/ ; s/$/\.tar/ ; s/\:/\_/' <<< ${NEXUS_IMAGE})"
114 # Setup default ports published to host as docker registry
115 PUBLISHED_PORTS="-p ${NEXUS_PORT}:${NEXUS_PORT} -p ${NEXUS_DOCKER_PORT}:${NEXUS_DOCKER_PORT}"
117 # Setup additional ports published to host based on simulated docker registries
118 for REGISTRY in $(sed -n '/\.[^/].*\//p' ${NXS_DOCKER_IMG_LIST} | sed -e 's/\/.*$//' | sort -u | grep -v ${DEFAULT_REGISTRY} || true); do
119 if [[ ${REGISTRY} != *":"* ]]; then
120 if [[ ${PUBLISHED_PORTS} != *"80:${NEXUS_DOCKER_PORT}"* ]]; then
121 PUBLISHED_PORTS="${PUBLISHED_PORTS} -p 80:${NEXUS_DOCKER_PORT}"
124 REGISTRY_PORT="$(sed 's/^.*\:\([[:digit:]]*\)$/\1/' <<< ${REGISTRY})"
125 if [[ ${PUBLISHED_PORTS} != *"${REGISTRY_PORT}:${NEXUS_DOCKER_PORT}"* ]]; then
126 PUBLISHED_PORTS="${PUBLISHED_PORTS} -p ${REGISTRY_PORT}:${NEXUS_DOCKER_PORT}"
131 # Setup simulated domain names to be able to push all to private Nexus repository
132 SIMUL_HOSTS="$(sed -n '/\.[^/].*\//p' ${NXS_DOCKER_IMG_LIST} | sed -e 's/\/.*$// ; s/:.*$//' | sort -u | grep -v ${DEFAULT_REGISTRY} || true) ${NEXUS_DOMAIN}"
134 # Nexus repository configuration setup
135 NEXUS_CONFIG_GROOVY='import org.sonatype.nexus.security.realm.RealmManager
136 import org.sonatype.nexus.repository.attributes.AttributesFacet
137 import org.sonatype.nexus.security.user.UserManager
138 import org.sonatype.nexus.repository.manager.RepositoryManager
139 import org.sonatype.nexus.security.user.UserNotFoundException
140 /* Use the container to look up some services. */
141 realmManager = container.lookup(RealmManager.class)
142 userManager = container.lookup(UserManager.class, "default") //default user manager
143 repositoryManager = container.lookup(RepositoryManager.class)
144 /* Managers are used when scripting api cannot. Note that scripting api can only create mostly, and that creation methods return objects of created entities. */
145 /* Perform cleanup by removing all repos and users. Realms do not need to be re-disabled, admin and anonymous user will not be removed. */
146 userManager.listUserIds().each({ id ->
147 if (id != "anonymous" && id != "admin")
148 userManager.deleteUser(id)
150 repositoryManager.browse().each {
151 repositoryManager.delete(it.getName())
153 /* Add bearer token realms at the end of realm lists... */
154 realmManager.enableRealm("NpmToken")
155 realmManager.enableRealm("DockerToken")
156 realmManager.enableRealm("PypiToken")
157 /* Create the docker user. */
158 security.addUser("docker", "docker", "docker", "docker@example.com", true, "docker", ["nx-anonymous"])
159 /* Create docker, npm and pypi repositories. Their default configuration should be compliant with our requirements, except the docker registry creation. */
160 repository.createNpmHosted("npm-private")
161 repository.createPyPiHosted("pypi-private")
162 def r = repository.createDockerHosted("onap", 8082, 0)
163 /* force basic authentication true by default, must set to false for docker repo. */
164 conf=r.getConfiguration()
165 conf.attributes("docker").set("forceBasicAuth", false)
166 repositoryManager.update(conf)'
168 # Prepare the Nexus configuration
169 NEXUS_CONFIG=$(echo "${NEXUS_CONFIG_GROOVY}" | jq -Rsc '{"name":"configure", "type":"groovy", "content":.}')
171 #################################
172 # Prepare the local environment #
173 #################################
175 # Add simulated domain names to /etc/hosts
176 HOSTS_BACKUP="$(eval ${TIMESTAMP}_hosts.bk)"
177 cp /etc/hosts "/etc/${HOSTS_BACKUP}"
178 for DNS in ${SIMUL_HOSTS}; do
179 echo "127.0.0.1 ${DNS}" >> /etc/hosts
182 # Backup the current docker registry settings
183 if [ -f ~/.docker/config.json ]; then
184 DOCKER_CONF_BACKUP="$(eval ${TIMESTAMP}_config.json.bk)"
185 mv ~/.docker/config.json "~/.docker/${DOCKER_CONF_BACKUP}"
188 #################################
189 # Docker repository preparation #
190 #################################
192 if [ "${DOCKER_LOAD}" == "true" ]; then
193 # Load predefined Nexus image
194 docker load -i ${NEXUS_IMAGE_TAR}
195 # Load all necessary images
196 load_docker_images ${NXS_DOCKER_IMG_LIST}
199 ################################
200 # Nexus repository preparation #
201 ################################
203 # Prepare nexus-data directory
204 if [ -d ${NEXUS_DATA_DIR} ]; then
205 if [ "$(docker ps -q -f name="${NEXUS_DOMAIN}")" ]; then
206 echo "Removing container ${NEXUS_DOMAIN}"
207 docker rm -f $(docker ps -aq -f name="${NEXUS_DOMAIN}")
209 pushd ${NEXUS_DATA_DIR}/..
210 NXS_BACKUP="$(eval ${TIMESTAMP})_$(basename ${NEXUS_DATA_DIR})_bk"
211 mv ${NEXUS_DATA_DIR} "${NXS_BACKUP}"
212 echo "${NEXUS_DATA_DIR} already exists - backing up to ${NXS_BACKUP}"
216 mkdir -p ${NEXUS_DATA_DIR}
217 chown 200:200 ${NEXUS_DATA_DIR}
218 chmod 777 ${NEXUS_DATA_DIR}
220 # Save Nexus version to prevent/catch data incompatibility
221 docker images --no-trunc | grep sonatype/nexus3 | awk '{ print $1":"$2" "$3}' > ${NEXUS_DATA_DIR}/nexus.ver
224 NEXUS_CONT_ID=$(docker run -d --rm -v ${NEXUS_DATA_DIR}:/nexus-data:rw --name ${NEXUS_DOMAIN} ${PUBLISHED_PORTS} ${NEXUS_IMAGE})
225 echo "Waiting for Nexus to fully start"
226 until curl -su ${NEXUS_USERNAME}:${NEXUS_PASSWORD} http://${NEXUS_DOMAIN}:${NEXUS_PORT}/service/metrics/healthcheck | grep '"healthy":true' > /dev/null ; do
230 echo -e "\nNexus started"
232 # Configure the nexus repository
233 curl -sX POST --header 'Content-Type: application/json' --data-binary "${NEXUS_CONFIG}" http://${NEXUS_USERNAME}:${NEXUS_PASSWORD}@${NEXUS_DOMAIN}:${NEXUS_PORT}/service/rest/v1/script
234 curl -sX POST --header "Content-Type: text/plain" http://${NEXUS_USERNAME}:${NEXUS_PASSWORD}@${NEXUS_DOMAIN}:${NEXUS_PORT}/service/rest/v1/script/configure/run > /dev/null
236 ###########################
237 # Populate NPM repository #
238 ###########################
240 # Configure NPM registry to our Nexus repository
241 echo "Configure NPM registry to ${NPM_REGISTRY}"
242 npm config set registry "${NPM_REGISTRY}"
244 # Login to NPM registry
245 /usr/bin/expect <<EOF
248 send "${NEXUS_USERNAME}\n"
250 send "${NEXUS_PASSWORD}\n"
252 send "${NEXUS_EMAIL}\n"
256 # Patch problematic package
257 pushd ${NXS_SRC_NPM_DIR}
258 PATCHED_NPM="$(grep tsscmp ${NXS_NPM_LIST} | sed $'s/\r// ; s/\\@/\-/ ; s/$/\.tgz/')"
259 if [[ ! -z "${PATCHED_NPM}" ]] && ! zgrep -aq "${NPM_REGISTRY}" "${PATCHED_NPM}" 2>/dev/null; then
260 tar xzf "${PATCHED_NPM}"
261 rm -f "${PATCHED_NPM}"
262 sed -i 's|\"registry\":\ \".*\"|\"registry\":\ \"'"${NPM_REGISTRY}"'\"|g' package/package.json
263 tar -zcf "${PATCHED_NPM}" package
267 # Push NPM packages to Nexus repository
268 for ARCHIVE in $(sed $'s/\r// ; s/\\@/\-/g ; s/$/\.tgz/g' ${NXS_NPM_LIST});do
269 npm publish --access public ${ARCHIVE} > /dev/null
270 echo "NPM ${ARCHIVE} pushed to Nexus"
274 ###############################
275 ## Populate PyPi repository #
276 ###############################
278 pushd ${NXS_SRC_PYPI_DIR}
279 for PACKAGE in $(sed $'s/\r//; s/==/-/' ${NXS_PYPI_LIST}); do
280 twine upload -u "${NEXUS_USERNAME}" -p "${NEXUS_PASSWORD}" --repository-url ${PYPI_REGISTRY} ${PACKAGE}*
281 echo "PYPI ${PACKAGE} pushed to Nexus"
285 ###############################
286 ## Populate Docker repository #
287 ###############################
289 # Login to simulated docker registries
290 for REGISTRY in $(sed -n '/\.[^/].*\//p' ${NXS_DOCKER_IMG_LIST} | sed -e 's/\/.*$//' | sort -u | grep -v ${DEFAULT_REGISTRY}) ${DOCKER_REGISTRY}; do
291 echo "Docker login to ${REGISTRY}"
292 docker login -u "${NEXUS_USERNAME}" -p "${NEXUS_PASSWORD}" ${REGISTRY} > /dev/null
295 # Push images to private nexus based on the list
296 # Images from default registry need to be tagged to private registry
297 # and those without defined repository in tag uses default repository 'library'
298 for IMAGE in $(sed $'s/\r// ; /^#/d' ${NXS_DOCKER_IMG_LIST} | awk '{ print $1 }'); do
300 if [[ ${IMAGE} != *"/"* ]]; then
301 PUSH="${DOCKER_REGISTRY}/library/${IMAGE}"
302 elif [[ ${IMAGE} == *"${DEFAULT_REGISTRY}"* ]]; then
303 if [[ ${IMAGE} == *"/"*"/"* ]]; then
304 PUSH="$(sed 's/'"${DEFAULT_REGISTRY}"'/'"${DOCKER_REGISTRY}"'/' <<< ${IMAGE})"
306 PUSH="$(sed 's/'"${DEFAULT_REGISTRY}"'/'"${DOCKER_REGISTRY}"'\/library/' <<< ${IMAGE})"
308 elif [[ -z $(sed -n '/\.[^/].*\//p' <<< ${IMAGE}) ]]; then
309 PUSH="${DOCKER_REGISTRY}/${IMAGE}"
311 if [[ ! -z ${PUSH} ]]; then
312 docker tag ${IMAGE} ${PUSH}
317 echo "${IMAGE} pushed as ${PUSH} to Nexus"
320 ##############################
321 # Stop the Nexus and cleanup #
322 ##############################
324 echo "Stopping Nexus and returning backups"
327 docker stop ${NEXUS_CONT_ID} > /dev/null
329 # Return backed up configuration files
330 mv -f "/etc/${HOSTS_BACKUP}" /etc/hosts
332 if [ -f "~/.docker/${DOCKER_CONF_BACKUP}" ]; then
333 mv -f "~/.docker/${DOCKER_CONF_BACKUP}" ~/.docker/config.json
336 # Return default settings
337 npm config set registry "https://registry.npmjs.org"
339 echo "Nexus blob is built"