Updated on 2023-10-30 GMT+08:00

upgrade.sh Description

Script Content

Replace the parameters in the script with the actual parameters in your environment.

#!/bin/bash
#Project ID
project_id='{Project ID}'
#Application ID
application_id='{Application ID}'
#Component ID
component_id='{Component ID}'
#Batch information
rolling_release_batches=1
#Deployment type
deploy_type="package"


### Description:
### 1. Search for a string, as shown in key in the following code. If no string is found, defaultValue is returned.
### 2. Search for the nearest colon (:). The content following the colon is the value.
### 3. If there are multiple keys with the same name, only the first value is printed.
###
### 4. params: json, key, defaultValue
function getJsonValuesByAwk() {
    awk -v json="$1" -v key="$2" -v defaultValue="$3" 'BEGIN{
        foundKeyCount = 0
        pos = match(json, "\""key"\"[ \\t]*?:[ \\t]*");
        if (pos == 0) {if (foundKeyCount == 0) {print defaultValue;} exit 0;}

        ++foundKeyCount;
        start = 0; stop = 0; layer = 0;
        for (i = pos + length(key) + 1; i <= length(json); ++i) {
            lastChar = substr(json, i - 1, 1)
            currChar = substr(json, i, 1)

            if (start <= 0) {
                if (lastChar == ":") {
                    start = currChar == " " ? i + 1: i;
                    if (currChar == "{" || currChar == "[") {
                        layer = 1;
                    }
                }
            } else {
                if (currChar == "{" || currChar == "[") {
                    ++layer;
                }
                if (currChar == "}" || currChar == "]") {
                    --layer;
                }
                if ((currChar == "," || currChar == "}" || currChar == "]") && layer <= 0) {
                    stop = currChar == "," ? i : i + 1 + layer;
                    break;
                }
            }
        }

        if (start <= 0 || stop <= 0 || start > length(json) || stop > length(json) || start >= stop) {
            if (foundKeyCount == 0) {print defaultValue;} exit 0;
        } else {
            print substr(json, start, stop-start);
        }
    }'
}

#Query component information.
function getComponentInfo() {
    #Query component information.
    component_detials=`hcloud ServiceStage ShowComponentInfo/v3 --project_id="$project_id" --application_id="$application_id" --component_id="$component_id"`

    #Print component information.
    echo "$component_detials"

    #Obtain the component name.
    test_name=`getJsonValuesByAwk  "$component_detials" "name" "defaultValue"`
    lenj=${#test_name}
    component_name=${test_name:1:lenj-2}
    echo "name : $component_name"


    data_time=$(date +%Y.%m%d.%H%M)
    seconds=$(date +%S)
    component_version="${data_time}${seconds:1:1}"
    echo "version: $component_version"
}

#Image deployment scenario
function swr_image_upgrade() {

      #Image generated after project packaging: Image name:Version name
      machine_image_name='java-test:v1'
      #Path of the SWR image repository to which the image is uploaded
      swr_image_url='{Image repository address}/{Organization name}/{Image name}:{Version}'
      #AK, which is used to log in to the SWR image repository.
      AK='BMCKUPO9HZMI6BRDJGBD'
      #SWR login key, which is used to log in to the SWR image repository
      SK='{SWR login key}'
      #SWR image repository address
      swr_url='{SWR image repository address}'
      #Region
      region="{Region}"

      echo "upload image to swr"
      docker tag "$machine_image_name" "$swr_image_url"

      login_secret=`printf "$AK" | openssl dgst -binary -sha256 -hmac "$SK" | od -An -vtx1 | sed 's/[ \n]//g' | sed 'N;s/\n//'`

      login_result=`docker login -u "$region"@"$AK" -p "$login_secret" "$swr_url"`
      #Print the result of logging in to the SWR image repository.
      echo "$login_result"
      push_result=`docker push "$swr_image_url"`
      #Print the image push result.
      #echo "$push_result"
      logout_result=`docker logout "$swr_url"`
      #Print the result of logging out of the SWR image repository.
      echo "$logout_result"
      #Clear all historical records. They may contain SWR login key information.
      #history -c

    echo "upgrade component"

    action_result=`hcloud ServiceStage ModifyComponent/v3 --project_id="$project_id" --application_id="$application_id" --component_id="$component_id" --version="$component_version" --runtime_stack.name="Docker" --runtime_stack.type="Docker" --source.kind="image" --source.storage="swr" --source.url="$swr_image_url" --name="$component_name" --deploy_strategy.rolling_release.batches=$rolling_release_batches --deploy_strategy.type="RollingRelease" `

}

#JAR package deployment scenario
function obs_jar_upgrade() {

    #Absolute path of the executable file for installing obsutil
    obsutil='/root/tools/obsutil/obsutil_linux_amd64_5.4.6/obsutil'
    #OBS bucket name
    bucket='obs://{OBS bucket name}'
    echo "upload jar to obs"
    #Upload the JAR package generated in the project to OBS.
    obs_result=`"$obsutil" cp ./target/*.jar "$bucket"`
    #Print the upload result.
    echo "$obs_result"
    #Link of the JAR package uploaded to OBS
    obs_jar_url='obs://{OBS bucket name}/{Jar package name}'

    echo "upgrade component"

    action_result=`hcloud ServiceStage ModifyComponent/v3 --project_id="$project_id" --application_id="$application_id" --component_id="$component_id" --version="$component_version" --runtime_stack.name="OpenJDK8" --runtime_stack.type="Java" --source.kind="package" --source.storage="obs" --source.url="$obs_jar_url" --name="$component_name" --deploy_strategy.rolling_release.batches=$rolling_release_batches --deploy_strategy.type="RollingRelease" `

}

#Query the job status every 15 seconds until the job is complete.
function waitDeployFinish() {
    sleep 10s
    id="$1"
    leni=${#id}
    id=${id:1:leni-2}
    echo "job_id= $id"
    job_status=""
    while [[ "$job_status" != "SUCCEEDED" ]]; do
        job_status_result=`hcloud ServiceStage ShowJobDetail/v2 --project_id="$project_id" --job_id="$id"`
        job_status=`getJsonValuesByAwk  "$job_status_result" "EXECUTION_STATUS" "defaultValue"`
        lenj=${#job_status}
        job_status=${job_status:1:lenj-2}
        echo "$job_status"
        if [[ "$job_status" != "RUNNING" && "$job_status" != "SUCCEEDED" ]]; then
            echo'Deployment failed.'
            echo "$job_status_result"
            return
        fi
        sleep 15s
    done
    echo'Deployment succeeded.'
}

function upgradeTask() {

    if [[ "$deploy_type" == "package" ]]; then
        obs_jar_upgrade
    elif [[ "$deploy_type" == "image" ]]; then
        swr_image_upgrade
    else
        return
    fi
    #Print the component upgrade result.
    echo "$action_result"
    #Obtain the job_id in the result.
    job_id=`getJsonValuesByAwk  "$action_result" "job_id" "defaultValue"`
    echo "$job_id"
    #Wait until the upgrade is complete.
    waitDeployFinish "$job_id"
}
function main() {
    getComponentInfo
    upgradeTask
}
main

Script Parameters

Parameter

Mandatory

Type

Description

region

Yes

String

Region name. For details, see Obtaining Values.

project_id

Yes

String

Project ID. For details, see Obtaining Values.

application_id

Yes

String

Application ID. For details, see Obtaining Values.

component_id

Yes

String

Component ID. For details, see Obtaining Values.

rolling_release_batches

Yes

int

Deployment batches.

deploy_type

Yes

String

Deployment type.

  • package
  • image

obsutil

No

String

Absolute path for uploading JAR packages to OBS. This parameter is mandatory when software packages, such as JAR packages, are used for deployment. For example, /root/tools/obsutil/obsutil_linux_amd64_5.4.6/obsutil.

bucket

No

String

Path of the OBS bucket to which the package is uploaded. This parameter is mandatory when software packages are used for deployment. The format is obs://{Bucket name}. For example, obs://obs-mzc.

obs_jar_url

No

String

Link after the software package is uploaded to OBS. This parameter is mandatory when software packages are used for deployment. The format is obs://{Bucket name}/{Software package name}. For example: obs://obs-mzc/spring-demo-0.0.1-SNAPSHOT.jar

machine_image_name

No

String

Image generated after Jenkins packaging and build. This parameter is mandatory when images are used for deployment. The format is {Image name}:{Version}. For example, java-test:v1.

swr_image_url

No

String

Path of the image package uploaded to the SWR image repository. This parameter is mandatory when images are used for deployment. The format is {Image repository address}/{Organization name}/{Image package name}:{Version}. The format of SWR image repository address is swr.{Project name of the region}.myhuaweicloud.com.

AK

No

String

AK, which is used to log in to the SWR image repository. This parameter is mandatory when images are used for deployment. For details, see Access Keys.

SK

No

String

SK, which is used together with AK to log in to the SWR image repository. This parameter is mandatory when images are used for deployment. For details, see Access Keys.

login_secret

No

String

Key for logging in to the SWR image repository. This parameter is mandatory when images are used for deployment. Run the following command. The returned result is the login key.

printf "{AK}" | openssl dgst -binary -sha256 -hmac "{SK}" | od -An -vtx1 | sed 's/[ \n]//g' | sed 'N;s/\n//'

Replace {AK} and {SK} with the obtained AK and SK.

swr_url

No

String

SWR image repository address. This parameter is mandatory when images are used for deployment. The format is swr.{Project name of the region}.myhuaweicloud.com.

Obtaining Values

  • Obtain region and project_id.
    1. Log in to ServiceStage.
    2. Move the cursor to the username in the upper right corner and select My Credentials from the drop-down list.
    3. View the project and project ID of the region, that is, the values of region and project_id.
  • Obtain application_id and component_id.
    1. Log in to ServiceStage.
    2. Choose Component Management.
    3. Click the corresponding component.
    4. In the Configurations area of the Overview page, click Component Configuration.

      View CAS_APP_ID and CAS_APPLICATION_ID, that is, the values of application_id and component_id.