diff --git a/README.md b/README.md index 4ffd17f..45a66ee 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Hello World Python App +# Python Hello World App ## Disclaimer @@ -7,813 +7,8 @@ > **already have full access** to the EIAP Ecosystem. > If you do not have this access, **please do not proceed.** +Python Hello World App Documentation [Here](https://developer.intelligentautomationplatform.ericsson.net/#tutorials/sample-app-in-python). + **Note:** If you need help accessing the EIAP Ecosystem, contact support at this **email address:** - -## Introduction - -This is a simple Hello World Python App with the following three endpoints: - -- **/sample-app/python/hello** is a sample endpoint. - -- **/sample-app/python/health** is an endpoint for an external agent to - monitor the App liveliness. - -- **/sample-app/python/metrics** is an endpoint that presents - the number of successful and failed invocations of - the '/sample-app/python/hello' endpoint. - -**Note:** X.509 certificates are used for authentication, and - mTLS uses them to secure communication between the App and the platform. - -## Build Docker - -Extract the downloaded sample App package. Using a command line tool, - go inside the extracted `eric-oss-hello-world-python-app-` directory. - -```bash -cd /eric-oss-hello-world-python-app- -``` - -Rename the `Dockerfile-template` file to `Dockerfile`. - -```bash -mv Dockerfile-template Dockerfile -``` - -Replace `` in the Dockerfile with a slim Python base image. -Refer to: [Python on Dockerâ„¢ Hub](https://hub.docker.com/_/python) - -Run the following command to build the image. - -```bash -docker build . -t proj-eric-oss-drop/eric-oss-hello-world-python-app: --build-arg APP_VERSION= -``` - -## Run Docker Image - -A port binding on port 8050 is done to expose the endpoints. - -```bash -docker run -p 8050:8050 --rm --name python-sample-app proj-eric-oss-drop/eric-oss-hello-world-python-app: -``` - -Run a curl request to the /sample-app/python/hello endpoint of the app. -The request should return a "Hello World!!" response. - -```bash -curl -is localhost:8050/sample-app/python/hello -``` - -Example Output: - -```http -HTTP/1.1 200 OK -Date: Thu, 17 Jun 2021 14:46:46 GMT -Content-Length: 13 -Content-Type: text/plain; charset=utf-8 - -Hello World!! -``` - -## Build the CSAR package - -For this step, install the [App Package Tool](https://developer.intelligentautomationplatform.ericsson.net/#capabilities/app-administration/tutorial-package-app). - -Once installed, the tool will be available as a Docker image -named `armdocker.rnd.ericsson.se/proj-eric-oss-dev-test/releases/eric-oss-app-package-tool:latest` - -**Note:** In the commands below, make sure to replace `` -with the correct Python Sample App version. Run the following commands -from within your project directory -`eric-oss-hello-world-python-app-`. - -```bash -mkdir -p helloworldAppPackage -``` - -The zip file includes a `csar` directory, which has the structure of the -CSAR package. - -```bash -cp -r ./csar/* ./helloworldAppPackage/ -``` - -Run the following command to generate an archive of the chart. - -```bash -helm package ./charts/eric-oss-hello-world-python-app/ -``` - -Move the created .tgz file to the OtherDefinitions/ASD directory. - -```bash -mv eric-oss-hello-world-python-app-.tgz ./helloworldAppPackage/OtherDefinitions/ASD/ -``` - -Create a folder where the CSAR App package will be stored into. - -```bash -mkdir csar-output -``` - -Generate an archive of the Docker image and store it temporarily in the `csar-output` -directory. - -```bash -docker save proj-eric-oss-drop/eric-oss-hello-world-python-app: -o csar-output/docker.tar -``` - -Run the following command locally to create a CSAR App package using the -eric-oss-app-package-tool. - -```bash -docker run --init --rm \ - --volume $PWD/csar-output/:/tmp/csar/ \ - --volume $HOME/.docker:/root/.docker \ - --volume /var/run/docker.sock:/var/run/docker.sock \ - --workdir /target \ - --volume $PWD/helloworldAppPackage:/target \ - armdocker.rnd.ericsson.se/proj-eric-oss-dev-test/releases/eric-oss-app-package-tool:latest \ - generate --tosca /target/Metadata/Tosca.meta \ - --name helloworldAppPackage \ - --images /tmp/csar/docker.tar \ - --helm3 \ - --output /tmp/csar -``` - -Run the following command to verify if the CSAR Package was created successfully. - -```bash -ls ./csar-output -``` - -`helloworldAppPackage.csar` is visible in the directory. - -## Onboard the App - -### Prerequisites for Onboarding - -Contact the platform administrator to request the following: - -- A Client certificate, Client key and platform CA certificate, - needed for secure communication with the platform APIs. -- Client ID to access the platform with the required roles, needed for authorized -communication with the platform APIs used to *onboard and instantiate* the -Hello World App. Include the required roles listed below in the request. - -| Role | Role Description | -| --------------------------------------------------------------- | ----------------------------------------------------------------------------- | -| AppMgr_Application_Administrator | Administrator access to App Administration onboarding and instantiating Apps. | -| AppMgr_Application_Operator | Operator access to App Administration onboarding and instantiating Apps. | -| Exposure_Application_Administrator | Access to Service Exposure Onboarding APIs for the Apps. | -| UserAdministration_ExtAppRbac_Application_SecurityAdministrator | Access to Service Exposure Access control APIs for the Apps. | - -See [Client Access to REST APIs](https://developer.intelligentautomationplatform.ericsson.net/#tutorials/client-access) - for further details on client authentication. - -**Note:** Replace `` with the valid `R1 host` provided by platform administrator. - -Use the following command to generate a valid access token: - -```bash -curl --cert --key --cacert --request POST \ -https:///auth/realms/master/protocol/openid-connect/token \ ---header 'content-type: application/x-www-form-urlencoded' \ ---data "grant_type=client_credentials&client_id=" -``` - -This command returns an access token, which is used in the commands in the -following steps. See the following example of a response containing the -access token: - -```bash - "access_token": "eyJhbGciOiJSUze168rQBwD4....", - "expires_in": 300, - "refresh_expires_in": 0, - "token_type": "Bearer", - "not-before-policy": 0, - "scope": "profile" -``` - -### Steps for Onboarding - -Onboard the **Hello World CSAR App Package** using [App Administration](https://developer.intelligentautomationplatform.ericsson.net/#capabilities/app-administration/developer-guide-manage?chapter=onboard). - -Run the following command. - -```bash -curl --cert --key --cacert --location --request POST 'https:///app-onboarding/v2/app-packages' \ ---header 'Authorization: Bearer ' \ ---header 'accept: application/json' \ ---form 'file=@"/helloworldAppPackage.csar"' -``` - -Example of command result: - -```json -{ - "fileName": "helloworldAppPackage.csar", - "onboardingJob": { - "id": "af036040-a732-4af9-b65a-8103da56c35c", - "href": "/onboarding-jobs/af036040-a732-4af9-b65a-8103da56c35c" - } -} -``` - -An onboarding-job `id` is shown in the command result -(af036040-a732-4af9-b65a-8103da56c35c in the example). -This is the `JOB_ID`. Use the `JOB_ID` to get the -status of the onboarding process in the following commands: - -```bash -curl --cert --key --cacert --location --request GET 'https:///app-onboarding/v2/onboarding-jobs/' \ ---header 'Authorization: Bearer ' \ ---header 'accept: application/json' -``` - -It can take several minutes for the status to change to `ONBOARDED`. -Repeat the command until the status is changed to `ONBOARDED`. - -Example of command result: - -```json -{ - "id": "af036040-a732-4af9-b65a-8103da56c35c", - "fileName": "helloworldAppPackage.csar", - "packageVersion": "4.0.0-0", - "packageSize": "51.7659MiB", - "vendor": "Ericsson", - "type": "rApp", - "onboardStartedAt": "2025-05-31T13:51:56.616Z", - "status": "ONBOARDED", - "onboardEndedAt": "2025-05-31T13:51:59.955Z", - "events": [ - { - "type": "INFO", - "title": "Stored 1 out of 4 artifacts", - "detail": "Uploaded eric-oss-hello-world-python-appASD.yaml", - "occurredAt": "2025-05-31T13:51:58.042Z" - }, - { - "type": "INFO", - "title": "Stored 2 out of 4 artifacts", - "detail": "Uploaded eric-oss-hello-world-python-app", - "occurredAt": "2025-05-31T13:51:58.043Z" - }, - { - "type": "INFO", - "title": "Stored 3 out of 4 artifacts", - "detail": "Uploaded docker.tar", - "occurredAt": "2025-05-31T13:51:59.792Z" - }, - { - "type": "INFO", - "title": "Stored 4 out of 4 artifacts", - "detail": "Uploaded security-metadata.json", - "occurredAt": "2025-05-31T13:51:59.812Z" - } - ], - "self": { - "href": "/onboarding-jobs/af036040-a732-4af9-b65a-8103da56c35c" - }, - "app": { - "id": "rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0", - "href": "app-lifecycle-management/v3/apps/rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0" - } -} -``` - -The `APP_ID` is the `id` of the `app` returned in the previous -command (rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0 in the example). -Run the following command to initialize the App. - -```bash -curl --cert --key --cacert --location --request POST 'https:///app-lifecycle-management/v3/apps//initialization-actions' \ ---header 'Content-Type: application/json' \ ---header 'Authorization: Bearer ' \ --d '{"action": "INITIALIZE"}' -``` - -Example of command result: - -```json -{ - "app": { - "status": "INITIALIZING", - "id": "rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0", - "href": "/apps/rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0" - } -} -``` - -Repeat the following command until the status is changed to `INITIALIZED`. - -```shell -curl --cert --key --cacert --location --request GET 'https:///app-lifecycle-management/v3/apps/' \ ---header 'Content-Type: application/json' \ ---header 'Authorization: Bearer ' -``` - -Example of command result: - -```json -{ - "id": "rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0", - "type": "rApp", - "provider": "Ericsson", - "name": "eric-oss-hello-world-python-app", - "version": "4.0.0-0", - "mode": "DISABLED", - "status": "INITIALIZED", - "createdAt": "2025-05-31T13:51:59.931Z", - "components": [ - { - "type": "ASD", - "name": "eric-oss-hello-world-python-app", - "version": "4.0.0-0", - "artifacts": [ - { - "name": "docker.tar", - "type": "IMAGE" - }, - { - "name": "eric-oss-hello-world-python-appASD.yaml", - "type": "OPAQUE" - }, - { - "name": "eric-oss-hello-world-python-app", - "type": "HELM" - } - ] - }, - { - "type": "SECURITYMANAGEMENT", - "name": "security-mgmt", - "version": "1.0.0", - "artifacts": [ - { - "name": "security-metadata.json", - "type": "OPAQUE" - } - ] - } - ], - "permissions": [ - { - "resource": "kafka", - "scope": "GLOBAL" - } - ], - "roles": [], - "events": [ - { - "type": "INITIALIZE", - "title": "SUCCEEDED", - "detail": "INITIALIZE has successfully completed", - "createdAt": "2025-05-31T13:55:50.421Z" - }, - { - "type": "INITIALIZE", - "title": "STARTED", - "detail": "INITIALIZE has started", - "createdAt": "2025-05-31T13:55:34.171Z" - }, - { - "type": "CREATE", - "title": "SUCCEEDED", - "detail": "CREATE has successfully completed", - "createdAt": "2025-05-31T13:51:59.945Z" - } - ], - "self": { - "href": "/apps/rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0" - } -} -``` - -Run the following command to switch the App mode from 'DISABLED' to 'ENABLED'. - -```bash -curl --cert --key --cacert --location --request PUT 'https:///app-lifecycle-management/v3/apps//mode' \ ---header 'Content-Type: application/json' \ ---header 'Authorization: Bearer ' \ --d '{"mode": "ENABLED"}' -``` - -Example of command result: - -```json -{ - "mode": "ENABLED", - "app": { - "id": "rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0", - "href": "/apps/rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0" - } -} -``` - -## Instantiate the App - -This section describes how the App can communicate with IAM and produce logs to - the platform. The App is instantiated using App Administration and the API is - exposed and secured by the Service Exposure capability. - -### Prerequisites for Instantiation - -- You need the access token generated in **Onboard the App** prerequisite to - access the App Manager for instantiating the Hello World CSAR App Package. -- Contact your platform administrator to generate the required App key, - certificates key, certificates, and the secrets which store them. The - details of the secrets, keys, certs and EIC endpoint details will be passed - to App Administration through the `userDefinedHelmParameters` when - instantiating the App. Refer to - [App Certificate Provisioning Developer Guide](https://developer.intelligentautomationplatform.ericsson.net/#capabilities/app-cert-provisioning/developer-guide) - to understand how certificates are loaded into the App during - instantiation for secure communication. The required parameters are: - - - The `iamBaseUrl` must point to the `R1 host`, as the `/sample-app/python/hello` - endpoint in this sample app first communicates with IAM to obtain a - client token (login) before returning the "Hello World!!" string response. - - The`appSecretName`, `appKeyFileName`, `appCertFileName`, - `platformCaCertSecretName` and `platformCaCertFileName` to enable - secure communication between the App and the platform. - - The `logEndpoint` which facilitates streaming App logs to platform, - supports only mTLS communication. For more information on the variable - values required, see [App Logging Developer Guide to Produce logs](https://developer.intelligentautomationplatform.ericsson.net/#capabilities/app-logging/how-to-produce-logs?chapter=identify-environment-and-secret-variables-names). - -### Steps for Instantiation - -Use the App Administration capability to instantiate the - **Hello World CSAR App**. For more details on instantiating an App, see - [App Administration](https://developer.intelligentautomationplatform.ericsson.net/#capabilities/app-administration/developer-guide-manage?chapter=instantiate). -Run the following commands to start the instantiation process using the - `APP_ID` from **Onboard the App**. - -#### Create App Instance - -```shell -curl --cert --key --cacert --location --request POST 'https:///app-lifecycle-management/v3/app-instances' \ ---header 'accept: application/json' \ ---header 'Content-Type: application/json' \ ---header 'Authorization: Bearer ' \ --d '{ - "appId": "" -}' -``` - -Example command result: - -```json -{ - "id": "rapp-ericsson-eric-oss-hello-world-python-app-68129972", - "appId": "rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0", - "status": "UNDEPLOYED", - "credentials": { - "clientId": "rapp-ericsson-eric-oss-hello-world-python-app-68129972" - }, - "componentInstances": [ - { - "name": "eric-oss-hello-world-python-app", - "version": "4.0.0-0", - "type": "ASD", - "deployState": "UNDEPLOYED", - "properties": { - "userDefinedHelmParameters": {}, - "namespace": "", - "timeout": 5 - } - }, - { - "name": "security-mgmt", - "version": "1.0.0", - "type": "SECURITYMANAGEMENT", - "properties": { - "authenticatorType": "client-x509" - } - } - ], - "self": { - "href": "/app-instances/rapp-ericsson-eric-oss-hello-world-python-app-68129972" - }, - "app": { - "href": "/apps/rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0" - } -} -``` - -An app-instance `id` is shown in the command result - (rapp-ericsson-eric-oss-hello-world-python-app-68129972 in the example). This - is the `APP_INSTANCE_ID` used in the following commands. - -#### Deploy App Instance - -> All `userDefinedHelmParameters` are required for successful instantiation - of your App. - -```shell -curl --cert --key --cacert --location --request POST 'https:///app-lifecycle-management/v3/app-instances//deployment-actions' \ - --header 'accept: application/json' \ - --header 'Content-Type: application/json' \ - --header 'Authorization: Bearer ' \ - -d '{ - "type": "DEPLOY", - "additionalData": { - "componentInstances": [ - { - "name": "eric-oss-hello-world-python-app", - "properties": { - "timeout": 5, - "userDefinedHelmParameters": { - "iamBaseUrl": "https://", - "logEndpoint": "", - "platformCaCertSecretName": "", - "appSecretName": "", - "platformCaCertFileName": "", - "appKeyFileName": "", - "appCertFileName": "", - } - } - } - ] - } -}' -``` - -See the following example command result: - -```json -{ - "type": "DEPLOY", - "additionalData": { - "componentInstances": [ - { - "name": "eric-oss-hello-world-python-app", - "properties": { - "timeout": 5, - "userDefinedHelmParameters": { - "platformCaCertSecretName": "", - "platformCaCertFileName": "", - "iamBaseUrl": "https://", - "appSecretName": "", - "logEndpoint": "", - "appKeyFileName": "", - "appCertFileName": "", - } - } - } - ] - }, - "appInstance": { - "status": "DEPLOYING", - "href": "/app-instances/rapp-ericsson-eric-oss-hello-world-python-app-68129972" - } -} -``` - -Use the App instance ID in the following command to check the instantiation - status. Repeat the command until the health status is changed - to `"status":"DEPLOYED"`. - -```shell -curl --cert --key --cacert --location --request GET 'https:///app-lifecycle-management/v3/app-instances/' \ ---header 'accept: application/json' \ ---header 'Content-Type: application/json' \ ---header 'Authorization: Bearer ' -``` - -```json -{ - "id": "rapp-ericsson-eric-oss-hello-world-python-app-68129972", - "appId": "rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0", - "status": "DEPLOYED", - "createdAt": "2025-05-31T14:01:01.741Z", - "updatedAt": "2025-05-31T14:04:16.300Z", - "credentials": { - "clientId": "rapp-ericsson-eric-oss-hello-world-python-app-68129972" - }, - "componentInstances": [ - { - "name": "eric-oss-hello-world-python-app", - "version": "4.0.0-0", - "type": "ASD", - "deployState": "DEPLOYED", - "properties": { - "userDefinedHelmParameters": { - "iamBaseUrl": "https://", - "logEndpoint": "", - "platformCaCertSecretName": "", - "appSecretName": "", - "platformCaCertFileName": "", - "appKeyFileName": "", - "appCertFileName": "", - }, - "namespace": "", - "timeout": 5 - } - }, - { - "name": "security-mgmt", - "version": "1.0.0", - "type": "SECURITYMANAGEMENT", - "properties": { - "authenticatorType": "client-x509" - } - } - ], - "events": [ - { - "type": "DEPLOY", - "title": "SUCCEEDED", - "detail": "DEPLOY has successfully completed", - "createdAt": "2025-05-31T14:04:16.297Z" - }, - { - "type": "DEPLOY", - "title": "STARTED", - "detail": "DEPLOY has started", - "createdAt": "2025-05-31T14:04:15.609Z" - }, - { - "type": "CREATE", - "title": "SUCCEEDED", - "detail": "CREATE has successfully completed", - "createdAt": "2025-05-31T14:01:01.753Z" - } - ], - "self": { - "href": "/app-instances/rapp-ericsson-eric-oss-hello-world-python-app-68129972" - }, - "app": { - "href": "/apps/rapp-ericsson-eric-oss-hello-world-python-app-4-0-0-0" - } -} -``` - -To view your logs, access EIC and open your log viewer. -Within the log viewer, you can filter for App Logging and view the results. - -#### Onboard the Hello World Python App APIs - -Use Service Exposure to expose the Hello World App API. -For details, see [Service Exposure - Developer Guide](https://developer.intelligentautomationplatform.ericsson.net/#capabilities/service-exposure/api-exposure-developer-guide). - -To create an API to be onboarded, run the following commands: - -```bash -curl --cert --key --cacert --location --request POST 'https:///hub/apiprovisioning/v1/admin/v3/apis' \ ---header 'Authorization: Bearer ' \ ---header 'Content-Type: application/json' \ ---data '{ - "serviceCapabilityId": "hello-world-python-route-001", - "status": "active", - "apiPrefix": "/app/ericsson-helloWorldPythonApp", - "apiName": "hello-world-python-route", - "apiVersion": "v1", - "apiCategory": "/APIGM/category/api", - "apiDefinition": [ - { - "operationName": "/sample-app/python/hello/GET", - "urlPattern": "/sample-app/python/hello", - "methods": [ - "GET" - ] - } - ] -}' -``` - -To create an endpoint for the previously generated API, run the -following command: - -```bash -curl --cert --key --cacert --location --request POST 'https:///hub/apiprovisioning/v1/admin/v3/apis/hello-world-python-route-001/endpoints' \ ---header 'Authorization: Bearer ' \ ---header 'Content-Type: application/json' \ ---data '{ - "endpointId": "python-hello-001", - "serverUrl": "http://eric-oss-hello-world-python-app:8050" -}' -``` - -To bind the plugin for authorization of the previously -generated API, run the following command: - -```bash -curl --cert --key --cacert --location --request PUT 'https:///hub/apiprovisioning/v1/admin/v3/apis/hello-world-python-route-001/phases/auth/plugin-list' \ ---header 'Authorization: Bearer ' \ ---header 'Content-Type: application/json' \ ---data '[ - { - "name": "requestPartyTokenInterceptor" - } -]' -``` - -To configure the binded plugin for authorization, -run the following command: - -```bash -curl --cert --key --cacert --location --request PUT 'https:///hub/apiprovisioning/v1/admin/v3/apis/hello-world-python-route-001/plugins/requestPartyTokenInterceptor/configuration' \ ---header 'Authorization: Bearer ' \ ---header 'Content-Type: application/json' \ ---data '{ - "configurationSchemaVersion": "v0", - "configuration": { - "defaultResourceServer": "eo" - } -}' -``` - -#### Manage access control for the Hello World Python App APIs - -To allow access to the API endpoints provided by the 'Hello World' App, -Role-Based Access Control (RBAC) configuration is required. To add the -RBAC policy run the following curl command: - -```bash -curl --cert --key --cacert --location --request POST 'https:///idm/rolemgmt/v1/extapp/rbac' \ ---header 'Content-Type: application/json' \ ---header 'Authorization: Bearer ' \ ---data '{ - "tenant": "master", - "roles": [ - { - "name": "Python_SampleApp_Application_Administrator" - } - ], - "authorization": { - "resources": [ - { - "name": "python_sample_app_hello", - "type": "urn:eo:resources:extrapp", - "ownerManagedAccess": false, - "uris": [ - "/app/ericsson-helloWorldPythonApp/hello-world-python-route/v1/sample-app/python/hello" - ], - "scopes": [ - { - "name": "PATCH" - }, - { - "name": "DELETE" - }, - { - "name": "GET" - }, - { - "name": "POST" - }, - { - "name": "PUT" - } - ] - } - ], - "policies": [ - { - "name": "Python Sample App Hello Policy", - "type": "role", - "logic": "POSITIVE", - "decisionStrategy": "UNANIMOUS", - "config": { - "roles": "[{\"id\":\"Python_SampleApp_Application_Administrator\",\"required\":false}]" - } - }, - { - "name": "Python Sample App Hello Permission", - "type": "scope", - "logic": "POSITIVE", - "decisionStrategy": "AFFIRMATIVE", - "config": { - "resources": "[\"python_sample_app_hello\"]", - "scopes": "[\"GET\",\"PUT\",\"POST\",\"DELETE\",\"PATCH\"]", - "applyPolicies": "[\"Python Sample App Hello Policy\"]" - } - } - ], - "scopes": [ - { - "name": "GET" - }, - { - "name": "POST" - }, - { - "name": "DELETE" - }, - { - "name": "PUT" - }, - { - "name": "PATCH" - } - ] - } -}' -``` - -To access the `/sample-app/python/hello` endpoint, the new role -`Python_SampleApp_Application_Administrator` must be assigned to any -client accessing the endpoint. diff --git a/eric-oss-hello-world-python-app/main.py b/eric-oss-hello-world-python-app/main.py index acd3adb..eda2a0d 100755 --- a/eric-oss-hello-world-python-app/main.py +++ b/eric-oss-hello-world-python-app/main.py @@ -62,7 +62,7 @@ def health(): indicate that the application is healthy. """ self.update_session() - self.logger.log("200 OK: Health check", Severity.INFO) + self.logger.log("200 OK: Health check", Severity.DEBUG) return "Ok\n" def update_session(self): diff --git a/set_app_name.sh b/set_app_name.sh index d002c2c..d0030db 100755 --- a/set_app_name.sh +++ b/set_app_name.sh @@ -2,6 +2,15 @@ set -e +# Defining ANSI color codes for terminal output +RED='\e[0;31m' +LIGHT_RED='\e[0;91m' +ORANGE='\e[38;5;208m' +YELLOW='\e[0;33m' +GREEN='\e[38;5;10m' +BLUE='\e[38;5;81m' +DEFAULT='\e[0m' + # More reliable than `sed -i` if we're on WSL and handling Windows paths wsl_safe_sed_replace() { local pattern=$1 @@ -12,54 +21,74 @@ wsl_safe_sed_replace() { sed "$pattern" "$file" > "$tmpfile" && mv -f "$tmpfile" "$file" } -if [[ -z "$APP_NAME_SUFFIX" ]]; then - echo "Error: APP_NAME_SUFFIX environment variable must be set." +echo -e "\n${ORANGE}=================Executing renaming script=================${DEFAULT}" + +if [[ -z "$APP_NAME" ]]; then + echo -e "${RED}\n===========================================================${DEFAULT}" + echo -e "${RED}Error${DEFAULT}: ${BLUE}APP_NAME${DEFAULT} environment variable must be set. Exiting..." + echo -e "${RED}===========================================================\n${DEFAULT}" exit 1 fi -PATTERN="^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" - -if [[ "$APP_NAME_SUFFIX" != "APP_NAME_SUFFIX" ]]; then - if ! [[ "$APP_NAME_SUFFIX" =~ $PATTERN ]]; then - echo "Error: New app name '$APP_NAME_SUFFIX' is not a valid Helm chart name." - echo "It must:" - echo " - Use only lowercase letters, numbers, and dashes (-)" - echo " - Start and end with an alphanumeric character" +if [[ "$APP_NAME" != "APP_NAME" ]]; then + if ! [[ "$APP_NAME" =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ ]]; then + echo -e "${RED}\n===========================================================${DEFAULT}" + echo -e "${RED}Error${DEFAULT}: New App name '$APP_NAME' is not a valid Helm chart name." + echo -e "It must:" + echo -e " - Use only lowercase letters, numbers, and dashes (-)" + echo -e " - Start and end with an alphanumeric character" + echo -e "Exiting..." + echo -e "${RED}===========================================================\n${DEFAULT}" exit 1 fi else - echo "WARNING: APP_NAME_SUFFIX can be set only as a placeholder. APP_NAME_SUFFIX is not valid for development purposes" + echo -e "\n${LIGHT_RED}WARNING${DEFAULT}: APP_NAME can be set only as a placeholder. APP_NAME is not a valid name for development purposes." fi -APP_NAME_PREFIX="eric-oss-hello-world-python-" -NEW_APP_NAME="$APP_NAME_PREFIX$APP_NAME_SUFFIX" - -if [[ ${#NEW_APP_NAME} -gt 53 ]]; then - echo "$NEW_APP_NAME exceeds 53 characters. Helm chart name must be at most 53 characters." +if [[ ${#APP_NAME} -gt 53 ]]; then + echo -e "${RED}\n===========================================================${DEFAULT}" + echo -e "The ${BLUE}APP_NAME${DEFAULT} exceeds 53 characters. Helm chart name must be at most 53 characters. ${RED}Exiting...${DEFAULT}" + echo -e "${RED}===========================================================\n${DEFAULT}" exit 1 fi -# Accept list of target paths as arguments in case we want to limit to specific paths -INPUT_PATHS=("$@") +# Setting target directory +if [[ -z "$1" ]]; then + TARGET_DIR="${TARGET_DIR:-$(pwd)}" +else + TARGET_DIR=$1 +fi +echo -e "\nUsing ${BLUE}TARGET_DIR${DEFAULT} as: $TARGET_DIR" + +# List of target paths +INPUT_PATHS=("charts/" "csar/" "eric-oss-hello-world-python-app/") + +# Print directories if [[ ${#INPUT_PATHS[@]} -gt 0 ]]; then - echo "Using provided paths as targets:" + echo -e "\nExecuting the script in the following directories:" for path in "${INPUT_PATHS[@]}"; do - if [[ ! -e "$path" ]]; then - echo "Error: '$path' does not exist." + if [[ ! -e "${TARGET_DIR}/${path}" ]]; then + echo -e "${RED}\n===========================================================${DEFAULT}" + echo -e "${RED}Error${DEFAULT}: directory '$path' does not exist. Exiting..." + echo -e "${RED}===========================================================\n${DEFAULT}" exit 1 fi echo " - $path" done + + count=0 + for path in "${INPUT_PATHS[@]}"; do + INPUT_PATHS[$count]="${TARGET_DIR}/${path}" + count=$((count + 1)) + done else - TARGET_DIR="${TARGET_DIR:-$(pwd)}" - echo "Using TARGET_DIR as: $TARGET_DIR" INPUT_PATHS=("$TARGET_DIR") fi chart_dirs=() -# Collect the app's chart(s) +# Collect the App's chart(s) for path in "${INPUT_PATHS[@]}"; do if [[ -d "$path" && -d "$path/charts" ]]; then chart_dirs+=("$path/charts"/*) @@ -69,44 +98,46 @@ for path in "${INPUT_PATHS[@]}"; do fi done -# Expect only one chart present and assume we can use its name as our current APP_NAME +# Expect only one chart present and assume we can use its name as our APP_NAME if [[ ! -d "${chart_dirs[0]}" || ${#chart_dirs[@]} -ne 1 ]]; then - echo "Error: No valid subdirectories found in provided paths' charts/ directories." + echo -e "${RED}\n===========================================================${DEFAULT}" + echo -e "${RED}Error${DEFAULT}: No valid subdirectories found in provided paths' charts/ directories." + echo -e "${RED}===========================================================\n${DEFAULT}" exit 1 fi CURRENT_APP_NAME=$(basename "${chart_dirs[0]}") -echo "Detected CURRENT_APP_NAME as '$CURRENT_APP_NAME'" +echo -e "\nDetected ${BLUE}CURRENT_APP_NAME${DEFAULT} as '$CURRENT_APP_NAME'" -if [[ "$CURRENT_APP_NAME" == "$NEW_APP_NAME" ]]; then - echo "Provided NEW_APP_NAME is the same as CURRENT_APP_NAME. Exiting..." +if [[ "$CURRENT_APP_NAME" == "$APP_NAME" ]]; then + echo -e "\n${RED}Provided ${BLUE}APP_NAME${RED} is the same as ${BLUE}CURRENT_APP_NAME${RED}. Exiting...${DEFAULT}" exit 1 fi script_file=$(basename "$0") -echo "Replacing '$CURRENT_APP_NAME' with '$NEW_APP_NAME' in provided paths..." +echo -e "\nReplacing '$CURRENT_APP_NAME' with '$APP_NAME'...\n" -echo "Updating file contents..." +echo -e "${YELLOW}Updating file contents...${DEFAULT}" for path in "${INPUT_PATHS[@]}"; do grep -rl "$CURRENT_APP_NAME" "$path" | while read -r file; do if [[ $(basename "$file") != "$script_file" && $(basename "$file") != docker.tar* ]]; then - wsl_safe_sed_replace "s/$CURRENT_APP_NAME/$NEW_APP_NAME/g" "$file" + wsl_safe_sed_replace "s/$CURRENT_APP_NAME/$APP_NAME/g" "$file" fi done done -echo "Renaming files..." +echo -e "${YELLOW}Renaming files...${DEFAULT}" for path in "${INPUT_PATHS[@]}"; do find "$path" -depth -type f -name "*$CURRENT_APP_NAME*" | while read -r file; do if [[ $(basename "$file") != "$script_file" ]]; then - newfile="$(dirname "$file")/$(basename "$file" | sed "s/$CURRENT_APP_NAME/$NEW_APP_NAME/g")" + newfile="$(dirname "$file")/$(basename "$file" | sed "s/$CURRENT_APP_NAME/$APP_NAME/g")" mv -f "$file" "$newfile" fi done done -echo "Renaming directories..." +echo -e "${YELLOW}Renaming directories...${DEFAULT}" for path in "${INPUT_PATHS[@]}"; do find "$path" -depth -type d -name "*$CURRENT_APP_NAME*" | while read -r dir; do # Skip renaming the outermost directory itself @@ -114,9 +145,11 @@ for path in "${INPUT_PATHS[@]}"; do continue fi - newdir="$(dirname "$dir")/$(basename "$dir" | sed "s/$CURRENT_APP_NAME/$NEW_APP_NAME/g")" + newdir="$(dirname "$dir")/$(basename "$dir" | sed "s/$CURRENT_APP_NAME/$APP_NAME/g")" mv -f "$dir" "$newdir" done done -echo "Finished renaming." +echo -e "${GREEN}\n===========================================================${DEFAULT}" +echo -e "${GREEN}Finished renaming.${DEFAULT}" +echo -e "${GREEN}===========================================================\n${DEFAULT}" \ No newline at end of file