diff --git a/.asf.yaml b/.asf.yaml index 8ce43df00b2..4d979a18833 100644 --- a/.asf.yaml +++ b/.asf.yaml @@ -51,14 +51,15 @@ github: collaborators: - acs-robot - - kiranchavala - rajujith - - alexandremattioli - - vishesh92 - GaOrtiga - SadiJr - winterhazel - - rp- + - gpordeus + - hsato03 + - bernardodemarco + - abh1sar + - FelipeM525 protected_branches: ~ diff --git a/.github/linters/.flake8 b/.github/linters/.flake8 index f250719ca19..3364ad14f29 100644 --- a/.github/linters/.flake8 +++ b/.github/linters/.flake8 @@ -22,8 +22,11 @@ # E224 Tab after operator # E227 Missing whitespace around bitwise or shift operator # E242 Tab after ',' +# E271 Multiple spaces after keyword +# E272 Multiple spaces before keyword # E273 Tab after keyword # E274 Tab before keyword +# E713 Test for membership should be 'not in' # E742 Do not define classes named 'I', 'O', or 'l' # E743 Do not define functions named 'I', 'O', or 'l' # E901 SyntaxError or IndentationError @@ -37,4 +40,4 @@ exclude = .git, venv -select = E112,E113,E133,E223,E224,E227,E242,E273,E274,E742,E743,E901,E902,W291,W292,W293,W391 +select = E112,E113,E133,E223,E224,E227,E242,E271,E272,E273,E274,E713,E742,E743,E901,E902,W291,W292,W293,W391 diff --git a/.github/linters/.markdown-lint.yml b/.github/linters/.markdown-lint.yml new file mode 100644 index 00000000000..df1b1a2825e --- /dev/null +++ b/.github/linters/.markdown-lint.yml @@ -0,0 +1,100 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. + +# MD001/heading-increment Heading levels should only increment by one level at a time +MD001: false + +# MD003/heading-style Heading style +MD003: false + +# MD004/ul-style Unordered list style +MD004: false + +# MD007/ul-indent Unordered list indentation +MD007: false + +# MD009/no-trailing-spaces Trailing spaces +MD009: false + +# MD010/no-hard-tabs Hard tabs +MD010: false + +# MD012/no-multiple-blanks Multiple consecutive blank lines +MD012: false + +# MD013/line-length Line length +MD013: false + +# MD014/commands-show-output Dollar signs used before commands without showing output +MD014: false + +# MD018/no-missing-space-atx No space after hash on atx style heading +MD018: false + +# MD019/no-multiple-space-atx Multiple spaces after hash on atx style heading +MD019: false + +# MD022/blanks-around-headings Headings should be surrounded by blank lines +MD022: false + +# MD023/heading-start-left Headings must start at the beginning of the line +MD023: false + +# MD024/no-duplicate-heading Multiple headings with the same content +MD024: false + +# MD025/single-title/single-h1 Multiple top-level headings in the same document +MD025: false + +# MD026/no-trailing-punctuation Trailing punctuation in heading +MD026: false + +# MD028/no-blanks-blockquote Blank line inside blockquote +MD028: false + +# MD029/ol-prefix Ordered list item prefix +MD029: false + +# MD031/blanks-around-fences Fenced code blocks should be surrounded by blank lines +MD031: false + +# MD032/blanks-around-lists Lists should be surrounded by blank lines +MD032: false + +# MD033/no-inline-html Inline HTML +MD033: false + +# MD034/no-bare-urls Bare URL used +MD034: false + +# MD036/no-emphasis-as-heading Emphasis used instead of a heading +MD036: false + +# MD037/no-space-in-emphasis Spaces inside emphasis markers +MD037: false + +# MD040/fenced-code-language Fenced code blocks should have a language specified +MD040: false + +# MD041/first-line-heading/first-line-h1 First line in a file should be a top-level heading +MD041: false + +# MD046/code-block-style Code block style +MD046: false + +# MD052/reference-links-images Reference links and images should use a label that is defined +MD052: false diff --git a/.github/linters/codespell.txt b/.github/linters/codespell.txt new file mode 100644 index 00000000000..37b3e6de1cb --- /dev/null +++ b/.github/linters/codespell.txt @@ -0,0 +1,526 @@ +accouns +acheived +acount +actuall +acuiring +acumulate +addreess +addtion +adminstrator +afer +afrer +afterall +againt +ags +aktive +algoritm +allo +alloacate +allocted +alocation +alogrithm +alpha-numeric +alue +ammended +ammount +ans +anull +apche +aplication +apllication +applicatio +apporpriate +appropritate +aqcuire +aqcuired +aquire +aquiring +assiciate +assigne +assoication +assosiate +asssert +astroid +asynchroniously +asyncronous +atleast +atomation +attache +attch +attches +authenciation +authenitcation +authenitication +availiability +avialable +bais +beacause +beacuse +becase +becasue +becaues +behviour +birdge +bject +boardcast +bootstraper +bu +cant +capabilites +capablity +capcity +carrefully +cavaet +chaing +checkd +childs +choosen +chould +clenup +cliente +clinet +cluser +cna +collison +comman +commited +comparision +comparisions +complient +concious +conectix +confg +configruation +configuable +conneciton +connexion +constrait +constraits +containg +contex +continuesly +contro +controler +controles +controll +convienient +convinience +coputer +correcponding +correspoding +correspoonds +cosole +coudl +couldnt +craete +craeted +crate +crated +createa +createing +credentail +cros +crresponding +curren +currentl +datas +decalared +declatory +decocdes +decypher +defalut +defaut +defered +definiton +deleteable +dependancy +dependant +dependend +deployement +deply +deplying +dervied +descktop +descrption +deserialzed +desination +detination +detroy +detroying +dettach +dettached +dettaching +diabling +diasbled +dictonary +didnt +differnet +differnt +direcotry +directroy +disale +disbale +discrepency +disover +dissapper +dissassociated +divice +doesn' +doesnot +doesnt +dont' +doubleclick +dows +eanbled +earch +ect +elemnt +eles +elments +emmited +enble +encryted +enebled +enmpty +entires +enviornment +environmnet +equivalant +erro +erronous +everthing +everytime +excetion +excption +excute +execept +execption +execut +executeable +exeeded +exisitng +exisits +existin +existsing +exitting +expcted +expection +explaination +explicitely +faield +faild +failes +falied +fasion +feild +filenname +fillled +findout +fisrt +fo +folowing +fowarding +frist +fro +frontent +fuctionality +genarate +generallly +gernerate +get's +gloabal +gorry +gracefull +gradiant +handeling +hanling +happend +hasing +hasnt +hda +hostanme +hould +hsould +hte +identifers +identifyer +identifyers +igoring +immediatley +implememented +implementor +implementors +implemnt +implict +implmeneted +implmentation +incase +includeing +incosistency +indecates +indien +infor +informations +informaton +infrastrcuture +ingore +inital +initalize +initator +initilization +inspite +instace +instal +instnace +intefaces +intepret +intereface +interfer +interpretted +intialize +intializes +intializing +invlaid +invokation +isnt +ist +klunky +lable +leve +lief +limite +linke +listner +lokal +lokales +maintainence +maintenace +maintenence +mamagement +mambers +manaully +manuel +maxium +mehtod +mergable +mesage +messge +metatdata +milisecond +minumum +mis +modifers +mor +mot +mulitply +multipl +multple +mutliple +nast +nd +neccessary +necesary +netowrk +nin +nodel +nome +noone +nowe +numbe +numer +occured +occurence +occuring +offfering +ofthe +omited +onother +opeation +optin +orginal +otherwse +outter +overriden +overwritting +paramater +paramemeter +paramenter +paramete +parametrs +pararmeter +parms +parralels +particualr +passowrd +perfromed +permissble +physcial +plugable +pluging +polcies +policys +poluting +possiblity +potenial +prefered +preffered +pressenter +previleges +primay +priviledged +procuct +programatically +progres +properites +propertie +propertys +propogate +provison +psudo +pyhsical +readabilty +readd +reccuring +recevied +recieved +recursivelly +redunant +refference +releease +relese +remaning +remore +remvoing +renabling +repeatly +reponse +reqest +reqiured +requieres +requried +reserv +reserverd +reseted +reseting +resorce +responser +resposne +resturns +retreive +retreiving +retrive +retrived +retriving +retrun +retuned +returing +re-use +rever +rocessor +runing +runnign +sate +scalled +scipt +scirpt +scrip +seconadry +seconday +seesion +sepcified +sepcify +seprated +ser +servies +seting +settig +sevices +shoul +shoule +sie +signle +simplier +singature +skiping +snaphsot +snpashot +specied +specifed +specifiy +splitted +spped +standy +statics +stickyness +stil +stip +storeage +strat +streched +strutural +succesfull +successfull +suceessful +suces +sucessfully +suiteable +suppots +suppport +syncronous +syste +tage +te +tempdate +testng +tha +thats +ther +therefor +theres +theses +thi +thorugh +throught +ths +tipically +transction +tring +trough +tyoe +ue +ues +unavailibility +uncommited +uncompressible +uneccessarily +unexepected +unexpect +unknow +unkonw +unkown +unneccessary +unparseable +unrecoginized +unsupport +unxpected +updat +uptodate +usera +usign +usin +utlization +vaidate +valiate +valule +valus +varibles +verfy +verfying +verifing +virutal +visable +wakup +wil +wit +wll +wth diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index dc2bd9db2bd..fd3c8f8ac67 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -41,9 +41,9 @@ jobs: cache: maven - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: '3.8' + python-version: '3.10' architecture: 'x64' - name: Install Build Dependencies diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 314239424a3..1c64df86cba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,7 +29,7 @@ permissions: jobs: build: if: github.repository == 'apache/cloudstack' - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false @@ -87,7 +87,9 @@ jobs: smoke/test_migration smoke/test_multipleips_per_nic smoke/test_nested_virtualization - smoke/test_set_sourcenat", + smoke/test_set_sourcenat + smoke/test_webhook_lifecycle + smoke/test_purge_expunged_vms", "smoke/test_network smoke/test_network_acl smoke/test_network_ipv6 @@ -133,6 +135,7 @@ jobs: smoke/test_usage smoke/test_usage_events smoke/test_vm_deployment_planner + smoke/test_vm_strict_host_tags smoke/test_vm_schedule smoke/test_vm_life_cycle smoke/test_vm_lifecycle_unmanage_import @@ -181,7 +184,8 @@ jobs: "component/test_project_usage component/test_protocol_number_security_group component/test_public_ip - component/test_resource_limits", + component/test_resource_limits + component/test_resource_limit_tags", "component/test_regions_accounts component/test_routers component/test_snapshots @@ -228,7 +232,25 @@ jobs: - name: Install Build Dependencies run: | sudo apt-get update - sudo apt-get install -y git uuid-runtime genisoimage netcat ipmitool build-essential libgcrypt20 libgpg-error-dev libgpg-error0 libopenipmi0 ipmitool libpython3-dev libssl-dev libffi-dev python3-openssl python3-dev python3-setuptools + sudo apt-get install -y git uuid-runtime genisoimage netcat-openbsd ipmitool build-essential libgcrypt20 libgpg-error-dev libgpg-error0 libopenipmi0 ipmitool libpython3-dev libssl-dev libffi-dev python3-openssl python3-dev python3-setuptools + + - name: Setup IPMI Tool for CloudStack + run: | + # Create cloudstack-common directory if it doesn't exist + sudo mkdir -p /usr/share/cloudstack-common + + # Copy ipmitool to cloudstack-common directory if it doesn't exist + if [ ! -f /usr/share/cloudstack-common/ipmitool ]; then + sudo cp /usr/bin/ipmitool /usr/share/cloudstack-common/ipmitool + sudo chmod 755 /usr/share/cloudstack-common/ipmitool + fi + + # Create ipmitool-C3 wrapper script + sudo tee /usr/bin/ipmitool > /dev/null << 'EOF' + #!/bin/bash + /usr/share/cloudstack-common/ipmitool -C3 $@ + EOF + sudo chmod 755 /usr/bin/ipmitool - name: Install Python dependencies run: | @@ -267,7 +289,7 @@ jobs: - name: Setup Simulator Prerequisites run: | sudo python3 -m pip install --upgrade netaddr mysql-connector-python - python3 -m pip install --user --upgrade tools/marvin/dist/Marvin-*.tar.gz + python3 -m pip install --user --upgrade tools/marvin/dist/[mM]arvin-*.tar.gz mvn -q -Pdeveloper -pl developer -Ddeploydb mvn -q -Pdeveloper -pl developer -Ddeploydb-simulator @@ -280,7 +302,7 @@ jobs: - name: Start CloudStack Management Server with Simulator run: | - export MAVEN_OPTS="-Xmx4096m -XX:MaxPermSize=800m -Djava.security.egd=file:/dev/urandom -javaagent:jacoco/lib/jacocoagent.jar=address=*,port=36320,output=tcpserver" + export MAVEN_OPTS="-Xmx4096m -XX:MaxMetaspaceSize=800m -Djava.security.egd=file:/dev/urandom -javaagent:jacoco/lib/jacocoagent.jar=address=*,port=36320,output=tcpserver --add-opens=java.base/java.lang=ALL-UNNAMED --add-exports=java.base/sun.security.x509=ALL-UNNAMED --add-opens=java.base/jdk.internal.reflect=ALL-UNNAMED" echo -e "\nStarting simulator" set +e mvn -Dsimulator -Dorg.eclipse.jetty.annotations.maxWait=120 -pl :cloud-client-ui jetty:run 2>&1 > /tmp/jetty-log || true & diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index a8f923d708d..c77783746ca 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -36,11 +36,11 @@ jobs: with: fetch-depth: 0 - - name: Set up JDK11 + - name: Set up JDK 17 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: '11' + java-version: '17' cache: 'maven' - name: Build CloudStack with Quality Checks diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 784df0cf03c..b6c814a36f4 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -39,7 +39,7 @@ jobs: pip install pre-commit - name: Set PY run: echo "PY=$(python -VV | sha256sum | cut -d' ' -f1)" >> $GITHUB_ENV - - uses: actions/cache@v3 + - uses: actions/cache@v4 with: path: ~/.cache/pre-commit key: pre-commit|${{ env.PY }}|${{ hashFiles('.pre-commit-config.yaml') }} diff --git a/.github/workflows/main-sonar-check.yml b/.github/workflows/main-sonar-check.yml index 66bb1093e04..dccd7174e54 100644 --- a/.github/workflows/main-sonar-check.yml +++ b/.github/workflows/main-sonar-check.yml @@ -36,25 +36,25 @@ jobs: with: fetch-depth: 0 - - name: Set up JDK11 + - name: Set up JDK17 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: '11' + java-version: '17' cache: 'maven' - name: Cache SonarCloud packages - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~/.sonar/cache key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar - name: Cache local Maven repository - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~/.m2/repository - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + key: ${{ runner.os }}-m2-${{ hashFiles('pom.xml', '*/pom.xml', '*/*/pom.xml', '*/*/*/pom.xml') }} restore-keys: | ${{ runner.os }}-m2 diff --git a/.github/workflows/rat.yml b/.github/workflows/rat.yml index b8f83de8194..52ce343841b 100644 --- a/.github/workflows/rat.yml +++ b/.github/workflows/rat.yml @@ -31,10 +31,10 @@ jobs: runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 - - name: Set up JDK 11 + - name: Set up JDK 17 uses: actions/setup-java@v4 with: - java-version: '11' + java-version: '17' distribution: 'adopt' architecture: x64 cache: maven diff --git a/.github/workflows/sonar-check.yml b/.github/workflows/sonar-check.yml index 2ebcf1fb2db..d31f55980a8 100644 --- a/.github/workflows/sonar-check.yml +++ b/.github/workflows/sonar-check.yml @@ -38,25 +38,25 @@ jobs: ref: "refs/pull/${{ github.event.number }}/merge" fetch-depth: 0 - - name: Set up JDK11 + - name: Set up JDK17 uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: '11' + java-version: '17' cache: 'maven' - name: Cache SonarCloud packages - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~/.sonar/cache key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar - name: Cache local Maven repository - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~/.m2/repository - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + key: ${{ runner.os }}-m2-${{ hashFiles('pom.xml', '*/pom.xml', '*/*/pom.xml', '*/*/*/pom.xml') }} restore-keys: | ${{ runner.os }}-m2 diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 1c2d2c07fc0..88d4a70e4c2 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -36,7 +36,7 @@ jobs: - name: Set up Node uses: actions/setup-node@v3 with: - node-version: 14 + node-version: 16 - name: Env details run: | diff --git a/.gitignore b/.gitignore index e638a09ae21..648b93b0696 100644 --- a/.gitignore +++ b/.gitignore @@ -15,92 +15,92 @@ # specific language governing permissions and limitations # under the License. -build/build.number -.lock-wscript -.waf-* -waf-* -target/ -override/ -.metadata -dist/ *~ +*_flymake.js *.bak -cloud-*.tar.bz2 -*.log -*.pyc -*.patch +*.css.map *.egginfo/ *.egg-info/ -*.prefs -build.number -*.log.* -cloud.log.*.* -unittest -deps/cloud.userlibraries -.DS_Store -.idea *.iml -git-remote-https.exe.stackdump -*.swp -tools/devcloud/devcloudbox/.vagrant -tools/cli/cloudmonkey/marvin/ -tools/cli/cloudmonkey/precache.py -tools/marvin/marvin/cloudstackAPI/ -tools/marvin/build/ -tools/cli/build/ -tools/appliance/systemvmtemplate/packer_cache/ -*.jar -*.war -*.mar *.iso +*.jar +*.log +*.log.* +*.mar +*.orig +*.patch +*.prefs +*.pyc +*.qcow2 +*.raw +*.swp *.tar.gz *.tgz *.vscode -*.css.map +*.war +.DS_Store +.checkstyle +.classpath +.idea +.lock-wscript +.metadata +.pmd +.pmdruleset.xml +.project +.pydevproject +.reviewboardrc +.settings.xml +.settings/ +.vscode +.waf-* +Gemfile.lock +build/build.number +build.number +build-indep-stamp +cloud.log.*.* +cloud-*.tar.bz2 +configure-stamp +db.properties.override +debian/*.debhelper +debian/*.substvars +debian/cloudstack-*/* +debian/files +debian/tmp +deps/cloud.userlibraries +dist/ +docs/publish +docs/runbook/publish +docs/runbook/tmp +docs/tmp +engine/storage/integration-test/test-output +git-remote-https.exe.stackdump +node_modules +override/ +plugins/hypervisors/kvm/.pydevproject +plugins/network-elements/juniper-contrail/logs/ +replace.properties.override +replace.properties.tmp +scripts/.pydevproject +scripts/vm/hypervisor/xenserver/vhd-util +systemvm/.pydevproject +target/ +target-eclipse +test/.pydevprojec +tools/apidoc/log/ +tools/appliance/box/ +tools/appliance/systemvmtemplate/packer_cache/ +tools/cli/build/ +tools/cli/cloudmonkey/marvin/ +tools/cli/cloudmonkey/precache.py +tools/devcloud/devcloudbox/.vagrant +tools/marvin/build/ +tools/marvin/marvin/cloudstackAPI/ +tools/marvin/marvin/cloudstackAPI/* +unittest +venv +waf-* # this ignores _all files starting with '.'. Don't do that! #.* -target-eclipse !.gitignore -.classpath -.settings.xml -.settings/ -db.properties.override -replace.properties.override -tools/marvin/marvin/cloudstackAPI/* -docs/tmp -docs/publish -docs/runbook/tmp -docs/runbook/publish -.project -Gemfile.lock -debian/tmp -debian/files -debian/cloudstack-*/* -debian/*.substvars -debian/*.debhelper -replace.properties.tmp -build-indep-stamp -configure-stamp -*_flymake.js -engine/storage/integration-test/test-output -tools/apidoc/log/ -plugins/network-elements/juniper-contrail/logs/ -scripts/vm/hypervisor/xenserver/vhd-util -*.orig -tools/appliance/box/ -.reviewboardrc -.checkstyle -.pmd -.pmdruleset.xml -.pydevproject -systemvm/.pydevproject -test/.pydevprojec -plugins/hypervisors/kvm/.pydevproject -scripts/.pydevproject -*.qcow2 -*.raw -venv -node_modules -.vscode diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0848a124794..e8f3c6093a9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,7 +26,7 @@ repos: - id: identity - id: check-hooks-apply - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.6.0 hooks: #- id: check-added-large-files - id: check-case-conflict @@ -36,6 +36,8 @@ repos: - id: check-vcs-permalinks #- id: check-yaml - id: destroyed-symlinks + - id: detect-aws-credentials + args: [--allow-missing-credentials] - id: detect-private-key exclude: > (?x) @@ -53,11 +55,23 @@ repos: - id: end-of-file-fixer exclude: \.vhd$ #- id: fix-byte-order-marker + - id: forbid-submodules - id: mixed-line-ending exclude: \.(cs|xml)$ - # - id: trailing-whitespace + - id: trailing-whitespace + files: \.(header|in|java|md|properties|py|rb|sh|sql|txt|vue|xml|yaml|yml)$ + args: [--markdown-linebreak-ext=md] + exclude: ^services/console-proxy/rdpconsole/src/test/doc/freerdp-debug-log\.txt$ + - repo: https://github.com/codespell-project/codespell + rev: v2.2.6 + hooks: + - id: codespell + name: run codespell + description: Check spelling with codespell + args: [--ignore-words=.github/linters/codespell.txt] + exclude: ^ui/package\.json$|^ui/package-lock\.json$|^ui/public/js/less\.min\.js$|^ui/public/locales/.*[^n].*\.json$ - repo: https://github.com/pycqa/flake8 - rev: 6.1.0 + rev: 7.0.0 hooks: - id: flake8 args: [--config, .github/linters/.flake8] @@ -72,3 +86,12 @@ repos: ^scripts/vm/hypervisor/xenserver/vmopspremium$| ^setup/bindir/cloud-setup-encryption\.in$| ^venv/.*$ + - repo: https://github.com/igorshubovych/markdownlint-cli + rev: v0.40.0 + hooks: + - id: markdownlint + name: run markdownlint + description: check Markdown files with markdownlint + args: [--config=.github/linters/.markdown-lint.yml] + types: [markdown] + files: \.(md|mdown|markdown)$ diff --git a/.python-version b/.python-version index d70c8f8d89f..c8cfe395918 100644 --- a/.python-version +++ b/.python-version @@ -1 +1 @@ -3.6 +3.10 diff --git a/CHANGES.md b/CHANGES.md index ef498f8edf0..9544fc014c7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -430,11 +430,11 @@ Bug ID | Description [CLOUDSTACK-6099](https://issues.apache.org/jira/browse/CLOUDSTACK-6099) | live migration is failing for vm deployed using dynamic compute offerings with NPE [CLOUDSTACK-7528](https://issues.apache.org/jira/browse/CLOUDSTACK-7528) | More verbose logging when sending alert fails [CLOUDSTACK-6624](https://issues.apache.org/jira/browse/CLOUDSTACK-6624) | set specifyIpRanges to true if specifyVlan is set to true -[CLOUDSTACK-7404](https://issues.apache.org/jira/browse/CLOUDSTACK-7404) | Failed to start an instance when originating template has been deleted +[CLOUDSTACK-7404](https://issues.apache.org/jira/browse/CLOUDSTACK-7404) | Failed to start an instance when originating template has been deleted [CLOUDSTACK-6531](https://issues.apache.org/jira/browse/CLOUDSTACK-6531) | Stopping the router in case of command failures [CLOUDSTACK-6115](https://issues.apache.org/jira/browse/CLOUDSTACK-6115) | TravisCI configuration [CLOUDSTACK-7405](https://issues.apache.org/jira/browse/CLOUDSTACK-7405) | allowing VR meta-data to be accessed without trailing slash -[CLOUDSTACK-7260](https://issues.apache.org/jira/browse/CLOUDSTACK-7260) | Management server not responding after some time for Vmware due to Oom +[CLOUDSTACK-7260](https://issues.apache.org/jira/browse/CLOUDSTACK-7260) | Management server not responding after some time for Vmware due to Oom [CLOUDSTACK-7038](https://issues.apache.org/jira/browse/CLOUDSTACK-7038) | Add mysql client dependency for mgmt server pkg for debian [CLOUDSTACK-6892](https://issues.apache.org/jira/browse/CLOUDSTACK-6892) | Create separate package for the mysql HA component [CLOUDSTACK-7038](https://issues.apache.org/jira/browse/CLOUDSTACK-7038) | Add mysql client dependency for mgmt server/rpms @@ -449,12 +449,12 @@ Bug ID | Description [CLOUDSTACK-7006](https://issues.apache.org/jira/browse/CLOUDSTACK-7006) | Restore template ID in ROOT volume usages [CLOUDSTACK-6747](https://issues.apache.org/jira/browse/CLOUDSTACK-6747) | test to allow all cidrs on other end of vpc [CLOUDSTACK-6272](https://issues.apache.org/jira/browse/CLOUDSTACK-6272) | Fix recover/restore VM actions -[CLOUDSTACK-6927](https://issues.apache.org/jira/browse/CLOUDSTACK-6927) | store virsh list in list instead of querying libvirt +[CLOUDSTACK-6927](https://issues.apache.org/jira/browse/CLOUDSTACK-6927) | store virsh list in list instead of querying libvirt [CLOUDSTACK-6317](https://issues.apache.org/jira/browse/CLOUDSTACK-6317) | [VMware] Tagged VLAN support broken for Management/Control/Storage traffic [CLOUDSTACK-5891](https://issues.apache.org/jira/browse/CLOUDSTACK-5891) | [VMware] If a template has been registered and "cpu.corespersocket=X" , [CLOUDSTACK-6478](https://issues.apache.org/jira/browse/CLOUDSTACK-6478) | Failed to download Template when having 3 SSVM's in one [CLOUDSTACK-6464](https://issues.apache.org/jira/browse/CLOUDSTACK-6464) | if guest network type is vlan://untagged, and traffic label is used -[CLOUDSTACK-6816](https://issues.apache.org/jira/browse/CLOUDSTACK-6816) | bugfix: cloudstack-setup-management make /root directory's permission 0777 +[CLOUDSTACK-6816](https://issues.apache.org/jira/browse/CLOUDSTACK-6816) | bugfix: cloudstack-setup-management make /root directory's permission 0777 [CLOUDSTACK-6204](https://issues.apache.org/jira/browse/CLOUDSTACK-6204) | applying missed patch [CLOUDSTACK-6472](https://issues.apache.org/jira/browse/CLOUDSTACK-6472) | (4.3 specific) listUsageRecords: Pull information from removed items as well [CLOUDSTACK-5976](https://issues.apache.org/jira/browse/CLOUDSTACK-5976) | Typo in "ssh_keypairs" table's foreign key constraints on the Upgraded Setup @@ -657,11 +657,11 @@ Version 4.1.0 ------------- This is the second major release of CloudStack from within the Apache Software Foundation, and the -first major release as a Top-Level Project (TLP). +first major release as a Top-Level Project (TLP). Build Tool Changes: - * The project now uses Maven 3 exclusively to build. + * The project now uses Maven 3 exclusively to build. New Features: * CLOUDSTACK-101: OVS support in KVM @@ -976,14 +976,14 @@ Issues fixed in this release: * CLOUDSTACK-1845: KVM - storage migration often fails * CLOUDSTACK-1846: KVM - storage pools can silently fail to be unregistered, leading to failure to register later * CLOUDSTACK-2003: Deleting domain while deleted account is cleaning up leaves VMs expunging forever due to 'Failed to update resource count' -* CLOUDSTACK-2090: Upgrade from version 4.0.1 to version 4.0.2 triggers the 4.0.0 to 4.0.1. +* CLOUDSTACK-2090: Upgrade from version 4.0.1 to version 4.0.2 triggers the 4.0.0 to 4.0.1. * CLOUDSTACK-2091: Error in API documentation for 4.0.x. Version 4.0.1-incubating ------------------------ -This is a bugfix release for Apache CloudStack 4.0.0-incubating, with no new features. +This is a bugfix release for Apache CloudStack 4.0.0-incubating, with no new features. Security Fixes: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cdfbfe77b7e..bb84e4e91fb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,7 +3,7 @@ Contributing to Apache CloudStack (ACS) Summary ------- -This document covers how to contribute to the ACS project. ACS uses GitHub PRs to manage code contributions. +This document covers how to contribute to the ACS project. ACS uses GitHub PRs to manage code contributions. These instructions assume you have a GitHub.com account, so if you don't have one you will have to create one. Your proposed code changes will be published to your own fork of the ACS project and you will submit a Pull Request for your changes to be added. _Lets get started!!!_ @@ -11,17 +11,17 @@ _Lets get started!!!_ Bug fixes --------- -It's very important that we can easily track bug fix commits, so their hashes should remain the same in all branches. -Therefore, a pull request (PR) that fixes a bug, should be sent against a release branch. -This can be either the "current release" or the "previous release", depending on which ones are maintained. +It's very important that we can easily track bug fix commits, so their hashes should remain the same in all branches. +Therefore, a pull request (PR) that fixes a bug, should be sent against a release branch. +This can be either the "current release" or the "previous release", depending on which ones are maintained. Since the goal is a stable main, bug fixes should be "merged forward" to the next branch in order: "previous release" -> "current release" -> main (in other words: old to new) Developing new features ----------------------- -Development should be done in a feature branch, branched off of main. -Send a PR(steps below) to get it into main (2x LGTM applies). -PR will only be merged when main is open, will be held otherwise until main is open again. +Development should be done in a feature branch, branched off of main. +Send a PR(steps below) to get it into main (2x LGTM applies). +PR will only be merged when main is open, will be held otherwise until main is open again. No back porting / cherry-picking features to existing branches! PendingReleaseNotes file @@ -33,7 +33,7 @@ When adding information to the PendingReleaseNotes file make sure that you write Updating the PendingReleaseNotes file is preferably a part of the original Pull Request, but that is up to the developers' discretion. -Fork the code +Fork the code ------------- In your browser, navigate to: [https://github.com/apache/cloudstack](https://github.com/apache/cloudstack) @@ -136,4 +136,4 @@ $ git push origin :feature_x Release Principles ------------------ -Detailed information about ACS release principles is available at https://cwiki.apache.org/confluence/display/CLOUDSTACK/Release+principles+for+Apache+CloudStack+4.6+and+up +Detailed information about ACS release principles is available at https://cwiki.apache.org/confluence/display/CLOUDSTACK/Release+principles+for+Apache+CloudStack+4.6+and+up diff --git a/INSTALL.md b/INSTALL.md index 620fc1833a8..e133e7d7b91 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -15,7 +15,7 @@ was tested against a CentOS 7 x86_64 setup. Install tools and dependencies used for development: - # yum -y install git java-11-openjdk java-11-openjdk-devel \ + # yum -y install git java-17-openjdk java-17-openjdk-devel \ mysql mysql-server mkisofs git gcc python MySQL-python openssh-clients wget Set up Maven (3.6.0): @@ -78,7 +78,7 @@ Clear old database (if any) and deploy the database schema: Export the following variable if you need to run and debug the management server: - $ export MAVEN_OPTS="-Xmx1024m -XX:MaxPermSize=500m -Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n" + $ export MAVEN_OPTS="-Xmx1024m -XX:MaxMetaspaceSize=500m -Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n" Start the management server: diff --git a/README.md b/README.md index e193913612f..f66a4dc6f97 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ This distribution includes cryptographic software. The country in which you curr reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and -re-export of encryption software, to see if this is permitted. See [The Wassenaar Arrangement](http://www.wassenaar.org/) +re-export of encryption software, to see if this is permitted. See [The Wassenaar Arrangement](http://www.wassenaar.org/) for more information. The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS), has diff --git a/agent/bindir/cloud-setup-agent.in b/agent/bindir/cloud-setup-agent.in index 53c6c2f56aa..9927c22eebc 100755 --- a/agent/bindir/cloud-setup-agent.in +++ b/agent/bindir/cloud-setup-agent.in @@ -6,9 +6,9 @@ # to you 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 @@ -20,6 +20,19 @@ import os import logging import sys import socket + +# ---- This snippet of code adds the sources path and the waf configured PYTHONDIR to the Python path ---- +# ---- We do this so cloud_utils can be looked up in the following order: +# ---- 1) Sources directory +# ---- 2) waf configured PYTHONDIR +# ---- 3) System Python path +for pythonpath in ( + "@PYTHONDIR@", + os.path.join(os.path.dirname(__file__),os.path.pardir,os.path.pardir,"python","lib"), + ): + if os.path.isdir(pythonpath): sys.path.insert(0,pythonpath) +# ---- End snippet of code ---- + from cloudutils.cloudException import CloudRuntimeException, CloudInternalException from cloudutils.utilities import initLoging, bash from cloudutils.configFileOps import configFileOps diff --git a/agent/bindir/cloud-ssh.in b/agent/bindir/cloud-ssh.in index e4b3c141a97..a5ea975c2f3 100644 --- a/agent/bindir/cloud-ssh.in +++ b/agent/bindir/cloud-ssh.in @@ -6,9 +6,9 @@ # to you 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 diff --git a/agent/bindir/libvirtqemuhook.in b/agent/bindir/libvirtqemuhook.in index e17944d8353..4cc6ed7a1d2 100755 --- a/agent/bindir/libvirtqemuhook.in +++ b/agent/bindir/libvirtqemuhook.in @@ -20,6 +20,19 @@ import sys import os import subprocess from threading import Timer + +# ---- This snippet of code adds the sources path and the waf configured PYTHONDIR to the Python path ---- +# ---- We do this so cloud_utils can be looked up in the following order: +# ---- 1) Sources directory +# ---- 2) waf configured PYTHONDIR +# ---- 3) System Python path +for pythonpath in ( + "@PYTHONDIR@", + os.path.join(os.path.dirname(__file__),os.path.pardir,os.path.pardir,"python","lib"), + ): + if os.path.isdir(pythonpath): sys.path.insert(0,pythonpath) +# ---- End snippet of code ---- + from xml.dom.minidom import parse from cloudutils.configFileOps import configFileOps from cloudutils.networkConfig import networkConfig diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index e600e8f8f20..773ef963ef7 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -286,6 +286,7 @@ hypervisor.type=kvm # The model of Watchdog timer to present to the Guest. # For all models refer to the libvirt documentation. +# PLEASE NOTE: to disable the watchdogs definitions, use value: none #vm.watchdog.model=i6300esb # Action to take when the Guest/Instance is no longer notifying the Watchdog timer. @@ -430,3 +431,13 @@ iscsi.session.cleanup.enabled=false # If set to "true", the agent will register for libvirt domain events, allowing for immediate updates on crashed or # unexpectedly stopped. Experimental, requires agent restart. # libvirt.events.enabled=false + +# Implicit host tags managed by agent.properties +# host.tags= + +# Timeout(in seconds) for SSL handshake when agent connects to server. When no value is set then default value of 30s +# will be used +#ssl.handshake.timeout= + +# Wait(in seconds) during agent reconnections. When no value is set then default value of 5s will be used +#backoff.seconds= diff --git a/agent/conf/cloudstack-agent.logrotate.in b/agent/conf/cloudstack-agent.logrotate.in index 2b3dc87f253..9f22b4bab86 100644 --- a/agent/conf/cloudstack-agent.logrotate.in +++ b/agent/conf/cloudstack-agent.logrotate.in @@ -15,11 +15,13 @@ # specific language governing permissions and limitations # under the License. -/var/log/cloudstack/agent/security_group.log /var/log/cloudstack/agent/resizevolume.log /var/log/cloudstack/agent/rolling-maintenance.log { +/var/log/cloudstack/agent/security_group.log /var/log/cloudstack/agent/resizevolume.log /var/log/cloudstack/agent/rolling-maintenance.log /var/log/cloudstack/agent/agent.out /var/log/cloudstack/agent/agent.err { copytruncate daily rotate 5 compress missingok size 10M + dateext + dateformat -%Y-%m-%d } diff --git a/agent/conf/environment.properties.in b/agent/conf/environment.properties.in index 514161a13fc..b6cc5bbd987 100644 --- a/agent/conf/environment.properties.in +++ b/agent/conf/environment.properties.in @@ -5,9 +5,9 @@ # to you 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 diff --git a/agent/conf/log4j-cloud.xml.in b/agent/conf/log4j-cloud.xml.in index 9ed43e083e0..84957edca03 100644 --- a/agent/conf/log4j-cloud.xml.in +++ b/agent/conf/log4j-cloud.xml.in @@ -17,91 +17,60 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> - + + - + + + - - - + + + + + + + + - - - - - - - - - - - - - - - - + + + - - - + + + + + - - - - + - - - + + + - - - - - - - - - - - + - - - - + - - - - - - - + - - - - + - - - - + - - - + - - - + - - - - - + + + - + + + + + + + diff --git a/agent/pom.xml b/agent/pom.xml index 22173da73ce..92c836f10ef 100644 --- a/agent/pom.xml +++ b/agent/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT diff --git a/agent/src/main/java/com/cloud/agent/Agent.java b/agent/src/main/java/com/cloud/agent/Agent.java index e73a26beea1..c01f025c6a8 100644 --- a/agent/src/main/java/com/cloud/agent/Agent.java +++ b/agent/src/main/java/com/cloud/agent/Agent.java @@ -26,24 +26,25 @@ import java.net.Socket; import java.net.UnknownHostException; import java.nio.channels.ClosedChannelException; import java.nio.charset.Charset; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Timer; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import javax.naming.ConfigurationException; -import com.cloud.resource.AgentStatusUpdater; -import com.cloud.resource.ResourceStatusUpdater; -import com.cloud.agent.api.PingAnswer; -import com.cloud.utils.NumbersUtil; import org.apache.cloudstack.agent.lb.SetupMSListAnswer; import org.apache.cloudstack.agent.lb.SetupMSListCommand; import org.apache.cloudstack.ca.PostCertificateRenewalCommand; @@ -55,9 +56,11 @@ import org.apache.cloudstack.managed.context.ManagedContextTimerTask; import org.apache.cloudstack.utils.security.KeyStoreUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; -import org.apache.log4j.MDC; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.ThreadContext; import com.cloud.agent.api.AgentControlAnswer; import com.cloud.agent.api.AgentControlCommand; @@ -66,6 +69,7 @@ import com.cloud.agent.api.Command; import com.cloud.agent.api.CronCommand; import com.cloud.agent.api.MaintainAnswer; import com.cloud.agent.api.MaintainCommand; +import com.cloud.agent.api.PingAnswer; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.ShutdownCommand; @@ -75,9 +79,11 @@ import com.cloud.agent.transport.Request; import com.cloud.agent.transport.Response; import com.cloud.exception.AgentControlChannelException; import com.cloud.host.Host; +import com.cloud.resource.AgentStatusUpdater; +import com.cloud.resource.ResourceStatusUpdater; import com.cloud.resource.ServerResource; +import com.cloud.utils.NumbersUtil; import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.backoff.BackoffAlgorithm; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.NioConnectionException; @@ -87,7 +93,6 @@ import com.cloud.utils.nio.Link; import com.cloud.utils.nio.NioClient; import com.cloud.utils.nio.NioConnection; import com.cloud.utils.nio.Task; -import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; /** @@ -104,7 +109,7 @@ import com.cloud.utils.script.Script; * **/ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater { - protected static Logger s_logger = Logger.getLogger(Agent.class); + protected Logger logger = LogManager.getLogger(getClass()); public enum ExitStatus { Normal(0), // Normal status = 0. @@ -112,7 +117,7 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater Configuration(66), // Exiting due to configuration problems. Error(67); // Exiting because of error. - int value; + final int value; ExitStatus(final int value) { this.value = value; @@ -123,128 +128,162 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater } } - List _controlListeners = new ArrayList(); + CopyOnWriteArrayList controlListeners = new CopyOnWriteArrayList<>(); - IAgentShell _shell; - NioConnection _connection; - ServerResource _resource; - Link _link; - Long _id; + IAgentShell shell; + NioConnection connection; + ServerResource serverResource; + Link link; + Long id; + String _uuid; + String _name; - Timer _timer = new Timer("Agent Timer"); - Timer certTimer; - Timer hostLBTimer; + ScheduledExecutorService selfTaskExecutor; + ScheduledExecutorService certExecutor; + ScheduledExecutorService hostLbCheckExecutor; - List _watchList = new ArrayList(); - long _sequence = 0; - long _lastPingResponseTime = 0; - long _pingInterval = 0; - AtomicInteger _inProgress = new AtomicInteger(); + CopyOnWriteArrayList> watchList = new CopyOnWriteArrayList<>(); + AtomicLong sequence = new AtomicLong(0); + AtomicLong lastPingResponseTime = new AtomicLong(0L); + long pingInterval = 0; + AtomicInteger commandsInProgress = new AtomicInteger(0); - StartupTask _startup = null; - long _startupWaitDefault = 180000; - long _startupWait = _startupWaitDefault; - boolean _reconnectAllowed = true; - //For time sentitive task, e.g. PingTask - ThreadPoolExecutor _ugentTaskPool; - ExecutorService _executor; + private final AtomicReference startupTask = new AtomicReference<>(); + private static final long DEFAULT_STARTUP_WAIT = 180; + long startupWait = DEFAULT_STARTUP_WAIT; + boolean reconnectAllowed = true; - Thread _shutdownThread = new ShutdownThread(this); + //For time sensitive task, e.g. PingTask + ThreadPoolExecutor outRequestHandler; + ExecutorService requestHandler; - private String _keystoreSetupPath; - private String _keystoreCertImportPath; + Thread shutdownThread = new ShutdownThread(this); - // for simulator use only + private String keystoreSetupSetupPath; + private String keystoreCertImportScriptPath; + + private String hostname; + + protected String getLinkLog(final Link link) { + if (link == null) { + return ""; + } + StringBuilder str = new StringBuilder(); + if (logger.isTraceEnabled()) { + str.append(System.identityHashCode(link)).append("-"); + } + str.append(link.getSocketAddress()); + return str.toString(); + } + + protected String getAgentName() { + return (serverResource != null && serverResource.isAppendAgentNameToLogs() && + StringUtils.isNotBlank(serverResource.getName())) ? + serverResource.getName() : + "Agent"; + } + + protected void setupShutdownHookAndInitExecutors() { + logger.trace("Adding shutdown hook"); + Runtime.getRuntime().addShutdownHook(shutdownThread); + selfTaskExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Agent-SelfTask")); + outRequestHandler = new ThreadPoolExecutor(shell.getPingRetries(), 2 * shell.getPingRetries(), 10, TimeUnit.MINUTES, + new SynchronousQueue<>(), new NamedThreadFactory("AgentOutRequest-Handler")); + requestHandler = new ThreadPoolExecutor(shell.getWorkers(), 5 * shell.getWorkers(), 1, TimeUnit.DAYS, + new LinkedBlockingQueue<>(), new NamedThreadFactory("AgentRequest-Handler")); + } + + /** + * Constructor for the {@code Agent} class, intended for simulator use only. + * + *

This constructor initializes the agent with a provided {@link IAgentShell}. + * It sets up the necessary NIO client connection, establishes a shutdown hook, + * and initializes the thread executors. + * + * @param shell the {@link IAgentShell} instance that provides agent configuration and runtime information. + */ public Agent(final IAgentShell shell) { - _shell = shell; - _link = null; - - _connection = new NioClient("Agent", _shell.getNextHost(), _shell.getPort(), _shell.getWorkers(), this); - - Runtime.getRuntime().addShutdownHook(_shutdownThread); - - _ugentTaskPool = - new ThreadPoolExecutor(shell.getPingRetries(), 2 * shell.getPingRetries(), 10, TimeUnit.MINUTES, new SynchronousQueue(), new NamedThreadFactory( - "UgentTask")); - - _executor = - new ThreadPoolExecutor(_shell.getWorkers(), 5 * _shell.getWorkers(), 1, TimeUnit.DAYS, new LinkedBlockingQueue(), new NamedThreadFactory( - "agentRequest-Handler")); + this.shell = shell; + this.link = null; + this.connection = new NioClient( + getAgentName(), + this.shell.getNextHost(), + this.shell.getPort(), + this.shell.getWorkers(), + this.shell.getSslHandshakeTimeout(), + this + ); + setupShutdownHookAndInitExecutors(); } public Agent(final IAgentShell shell, final int localAgentId, final ServerResource resource) throws ConfigurationException { - _shell = shell; - _resource = resource; - _link = null; - + this.shell = shell; + serverResource = resource; + link = null; resource.setAgentControl(this); - - final String value = _shell.getPersistentProperty(getResourceName(), "id"); - _id = value != null ? Long.parseLong(value) : null; - s_logger.info("id is " + (_id != null ? _id : "")); + final String value = shell.getPersistentProperty(getResourceName(), "id"); + _uuid = shell.getPersistentProperty(getResourceName(), "uuid"); + _name = shell.getPersistentProperty(getResourceName(), "name"); + id = value != null ? Long.parseLong(value) : null; + logger.info("Initialising agent [id: {}, uuid: {}, name: {}]", ObjectUtils.defaultIfNull(id, ""), _uuid, _name); final Map params = new HashMap<>(); - // merge with properties from command line to let resource access command line parameters - for (final Map.Entry cmdLineProp : _shell.getCmdLineProperties().entrySet()) { + for (final Map.Entry cmdLineProp : this.shell.getCmdLineProperties().entrySet()) { params.put(cmdLineProp.getKey(), cmdLineProp.getValue()); } - - if (!_resource.configure(getResourceName(), params)) { - throw new ConfigurationException("Unable to configure " + _resource.getName()); + if (!serverResource.configure(getResourceName(), params)) { + throw new ConfigurationException("Unable to configure " + serverResource.getName()); } + ThreadContext.put("agentname", getAgentName()); + final String host = this.shell.getNextHost(); + connection = new NioClient(getAgentName(), host, this.shell.getPort(), this.shell.getWorkers(), + this.shell.getSslHandshakeTimeout(), this); + setupShutdownHookAndInitExecutors(); + logger.info("{} with host = {}, local id = {}", this, host, localAgentId); + } - final String host = _shell.getNextHost(); - _connection = new NioClient("Agent", host, _shell.getPort(), _shell.getWorkers(), this); - // ((NioClient)_connection).setBindAddress(_shell.getPrivateIp()); - - s_logger.debug("Adding shutdown hook"); - Runtime.getRuntime().addShutdownHook(_shutdownThread); - - _ugentTaskPool = - new ThreadPoolExecutor(shell.getPingRetries(), 2 * shell.getPingRetries(), 10, TimeUnit.MINUTES, new SynchronousQueue(), new NamedThreadFactory( - "UgentTask")); - - _executor = - new ThreadPoolExecutor(_shell.getWorkers(), 5 * _shell.getWorkers(), 1, TimeUnit.DAYS, new LinkedBlockingQueue(), new NamedThreadFactory( - "agentRequest-Handler")); - - s_logger.info("Agent [id = " + (_id != null ? _id : "new") + " : type = " + getResourceName() + " : zone = " + _shell.getZone() + " : pod = " + _shell.getPod() + - " : workers = " + _shell.getWorkers() + " : host = " + host + " : port = " + _shell.getPort()); + @Override + public String toString() { + return String.format("Agent [id = %s, uuid = %s, name = %s, type = %s, zone = %s, pod = %s, workers = %d, port = %d]", + ObjectUtils.defaultIfNull(id, "new"), + _uuid, + _name, + getResourceName(), + this.shell.getZone(), + this.shell.getPod(), + this.shell.getWorkers(), + this.shell.getPort()); } public String getVersion() { - return _shell.getVersion(); + return shell.getVersion(); } public String getResourceGuid() { - final String guid = _shell.getGuid(); + final String guid = shell.getGuid(); return guid + "-" + getResourceName(); } public String getZone() { - return _shell.getZone(); + return shell.getZone(); } public String getPod() { - return _shell.getPod(); + return shell.getPod(); } protected void setLink(final Link link) { - _link = link; + this.link = link; } public ServerResource getResource() { - return _resource; - } - - public BackoffAlgorithm getBackoffAlgorithm() { - return _shell.getBackoffAlgorithm(); + return serverResource; } public String getResourceName() { - return _resource.getClass().getSimpleName(); + return serverResource.getClass().getSimpleName(); } /** @@ -253,189 +292,211 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater * agent instances and its inner objects. */ private void scavengeOldAgentObjects() { - _executor.submit(new Runnable() { - @Override - public void run() { - try { - Thread.sleep(2000L); - } catch (final InterruptedException ignored) { - } finally { - System.gc(); - } + requestHandler.submit(() -> { + try { + Thread.sleep(2000L); + } catch (final InterruptedException ignored) { + } finally { + System.gc(); } }); } public void start() { - if (!_resource.start()) { - s_logger.error("Unable to start the resource: " + _resource.getName()); - throw new CloudRuntimeException("Unable to start the resource: " + _resource.getName()); + if (!serverResource.start()) { + String msg = String.format("Unable to start the resource: %s", serverResource.getName()); + logger.error(msg); + throw new CloudRuntimeException(msg); } - _keystoreSetupPath = Script.findScript("scripts/util/", KeyStoreUtils.KS_SETUP_SCRIPT); - if (_keystoreSetupPath == null) { + keystoreSetupSetupPath = Script.findScript("scripts/util/", KeyStoreUtils.KS_SETUP_SCRIPT); + if (keystoreSetupSetupPath == null) { throw new CloudRuntimeException(String.format("Unable to find the '%s' script", KeyStoreUtils.KS_SETUP_SCRIPT)); } - _keystoreCertImportPath = Script.findScript("scripts/util/", KeyStoreUtils.KS_IMPORT_SCRIPT); - if (_keystoreCertImportPath == null) { + keystoreCertImportScriptPath = Script.findScript("scripts/util/", KeyStoreUtils.KS_IMPORT_SCRIPT); + if (keystoreCertImportScriptPath == null) { throw new CloudRuntimeException(String.format("Unable to find the '%s' script", KeyStoreUtils.KS_IMPORT_SCRIPT)); } try { - _connection.start(); + connection.start(); } catch (final NioConnectionException e) { - s_logger.warn("NIO Connection Exception " + e); - s_logger.info("Attempted to connect to the server, but received an unexpected exception, trying again..."); + logger.warn("Attempt to connect to server generated NIO Connection Exception {}, trying again", e.getLocalizedMessage()); } - while (!_connection.isStartup()) { - final String host = _shell.getNextHost(); - _shell.getBackoffAlgorithm().waitBeforeRetry(); - _connection = new NioClient("Agent", host, _shell.getPort(), _shell.getWorkers(), this); - s_logger.info("Connecting to host:" + host); + while (!connection.isStartup()) { + final String host = shell.getNextHost(); + shell.getBackoffAlgorithm().waitBeforeRetry(); + connection = new NioClient(getAgentName(), host, shell.getPort(), shell.getWorkers(), + shell.getSslHandshakeTimeout(), this); + logger.info("Connecting to host: {}", host); try { - _connection.start(); + connection.start(); } catch (final NioConnectionException e) { - _connection.stop(); - try { - _connection.cleanUp(); - } catch (final IOException ex) { - s_logger.warn("Fail to clean up old connection. " + ex); - } - s_logger.info("Attempted to connect to the server, but received an unexpected exception, trying again...", e); + stopAndCleanupConnection(false); + logger.info("Attempted to connect to the server, but received an unexpected exception, trying again...", e); } } - _shell.updateConnectedHost(); + shell.updateConnectedHost(); scavengeOldAgentObjects(); } public void stop(final String reason, final String detail) { - s_logger.info("Stopping the agent: Reason = " + reason + (detail != null ? ": Detail = " + detail : "")); - _reconnectAllowed = false; - if (_connection != null) { + logger.info("Stopping the agent: Reason = {}{}", reason, (detail != null ? ": Detail = " + detail : "")); + reconnectAllowed = false; + if (connection != null) { final ShutdownCommand cmd = new ShutdownCommand(reason, detail); try { - if (_link != null) { - final Request req = new Request(_id != null ? _id : -1, -1, cmd, false); - _link.send(req.toBytes()); + if (link != null) { + final Request req = new Request(id != null ? id : -1, -1, cmd, false); + link.send(req.toBytes()); } } catch (final ClosedChannelException e) { - s_logger.warn("Unable to send: " + cmd.toString()); + logger.warn("Unable to send: {}", cmd.toString()); } catch (final Exception e) { - s_logger.warn("Unable to send: " + cmd.toString() + " due to exception: ", e); + logger.warn("Unable to send: {} due to exception: {}", cmd.toString(), e); } - s_logger.debug("Sending shutdown to management server"); + logger.debug("Sending shutdown to management server"); try { Thread.sleep(1000); } catch (final InterruptedException e) { - s_logger.debug("Who the heck interrupted me here?"); + logger.debug("Who the heck interrupted me here?"); } - _connection.stop(); - _connection = null; - _link = null; + connection.stop(); + connection = null; + link = null; } - if (_resource != null) { - _resource.stop(); - _resource = null; + if (serverResource != null) { + serverResource.stop(); + serverResource = null; } - if (_startup != null) { - _startup = null; + if (startupTask.get() != null) { + startupTask.set(null); } - if (_ugentTaskPool != null) { - _ugentTaskPool.shutdownNow(); - _ugentTaskPool = null; + if (outRequestHandler != null) { + outRequestHandler.shutdownNow(); + outRequestHandler = null; } - if (_executor != null) { - _executor.shutdown(); - _executor = null; + if (requestHandler != null) { + requestHandler.shutdown(); + requestHandler = null; } - if (_timer != null) { - _timer.cancel(); - _timer = null; + if (selfTaskExecutor != null) { + selfTaskExecutor.shutdown(); + selfTaskExecutor = null; } - if (hostLBTimer != null) { - hostLBTimer.cancel(); - hostLBTimer = null; + if (hostLbCheckExecutor != null) { + hostLbCheckExecutor.shutdown(); + hostLbCheckExecutor = null; } - if (certTimer != null) { - certTimer.cancel(); - certTimer = null; + if (certExecutor != null) { + certExecutor.shutdown(); + certExecutor = null; } } public Long getId() { - return _id; + return id; } public void setId(final Long id) { - s_logger.info("Set agent id " + id); - _id = id; - _shell.setPersistentProperty(getResourceName(), "id", Long.toString(id)); + logger.debug("Set agent id {}", id); + this.id = id; + shell.setPersistentProperty(getResourceName(), "id", Long.toString(id)); } - private synchronized void scheduleServicesRestartTask() { - if (certTimer != null) { - certTimer.cancel(); - certTimer.purge(); + public String getUuid() { + return _uuid; + } + + public void setUuid(String uuid) { + this._uuid = uuid; + shell.setPersistentProperty(getResourceName(), "uuid", uuid); + } + + public String getName() { + return _name; + } + + public void setName(String name) { + this._name = name; + shell.setPersistentProperty(getResourceName(), "name", name); + } + + private void scheduleCertificateRenewalTask() { + String name = "CertificateRenewalTask"; + if (certExecutor != null && !certExecutor.isShutdown()) { + certExecutor.shutdown(); + try { + if (!certExecutor.awaitTermination(1, TimeUnit.SECONDS)) { + certExecutor.shutdownNow(); + } + } catch (InterruptedException e) { + logger.debug("Forcing {} shutdown as it did not shutdown in the desired time due to: {}", + name, e.getMessage()); + certExecutor.shutdownNow(); + } } - certTimer = new Timer("Certificate Renewal Timer"); - certTimer.schedule(new PostCertificateRenewalTask(this), 5000L); + certExecutor = Executors.newSingleThreadScheduledExecutor((new NamedThreadFactory(name))); + certExecutor.schedule(new PostCertificateRenewalTask(this), 5, TimeUnit.SECONDS); } - private synchronized void scheduleHostLBCheckerTask(final long checkInterval) { - if (hostLBTimer != null) { - hostLBTimer.cancel(); + private void scheduleHostLBCheckerTask(final long checkInterval) { + String name = "HostLBCheckerTask"; + if (hostLbCheckExecutor != null && !hostLbCheckExecutor.isShutdown()) { + hostLbCheckExecutor.shutdown(); + try { + if (!hostLbCheckExecutor.awaitTermination(1, TimeUnit.SECONDS)) { + hostLbCheckExecutor.shutdownNow(); + } + } catch (InterruptedException e) { + logger.debug("Forcing {} shutdown as it did not shutdown in the desired time due to: {}", + name, e.getMessage()); + hostLbCheckExecutor.shutdownNow(); + } } if (checkInterval > 0L) { - s_logger.info("Scheduling preferred host timer task with host.lb.interval=" + checkInterval + "ms"); - hostLBTimer = new Timer("Host LB Timer"); - hostLBTimer.scheduleAtFixedRate(new PreferredHostCheckerTask(), checkInterval, checkInterval); + logger.info("Scheduling preferred host task with host.lb.interval={}ms", checkInterval); + hostLbCheckExecutor = Executors.newSingleThreadScheduledExecutor((new NamedThreadFactory(name))); + hostLbCheckExecutor.scheduleAtFixedRate(new PreferredHostCheckerTask(), checkInterval, checkInterval, + TimeUnit.MILLISECONDS); } } public void scheduleWatch(final Link link, final Request request, final long delay, final long period) { - synchronized (_watchList) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Adding a watch list"); - } - final WatchTask task = new WatchTask(link, request, this); - _timer.schedule(task, 0, period); - _watchList.add(task); - } + logger.debug("Adding a watch list"); + final WatchTask task = new WatchTask(link, request, this); + final ScheduledFuture future = selfTaskExecutor.scheduleAtFixedRate(task, delay, period, TimeUnit.MILLISECONDS); + watchList.add(future); } public void triggerUpdate() { - PingCommand command = _resource.getCurrentStatus(getId()); + PingCommand command = serverResource.getCurrentStatus(getId()); command.setOutOfBand(true); - s_logger.debug("Sending out of band ping"); - - final Request request = new Request(_id, -1, command, false); + logger.debug("Sending out of band ping"); + final Request request = new Request(id, -1, command, false); request.setSequence(getNextSequence()); try { - _link.send(request.toBytes()); + link.send(request.toBytes()); } catch (final ClosedChannelException e) { - s_logger.warn("Unable to send ping update: " + request.toString()); + logger.warn("Unable to send ping update: {}", request.toString()); } } protected void cancelTasks() { - synchronized (_watchList) { - for (final WatchTask task : _watchList) { - task.cancel(); - } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Clearing watch list: " + _watchList.size()); - } - _watchList.clear(); + for (final ScheduledFuture task : watchList) { + task.cancel(true); } + logger.debug("Clearing watch list: {}", () -> watchList.size()); + watchList.clear(); } /** @@ -446,61 +507,85 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater * when host is added back */ protected void cleanupAgentZoneProperties() { - _shell.setPersistentProperty(null, "zone", ""); - _shell.setPersistentProperty(null, "cluster", ""); - _shell.setPersistentProperty(null, "pod", ""); + shell.setPersistentProperty(null, "zone", ""); + shell.setPersistentProperty(null, "cluster", ""); + shell.setPersistentProperty(null, "pod", ""); } - public synchronized void lockStartupTask(final Link link) { - _startup = new StartupTask(link); - _timer.schedule(_startup, _startupWait); + public void lockStartupTask(final Link link) { + logger.debug("Creating startup task for link: {}", () -> getLinkLog(link)); + StartupTask currentTask = startupTask.get(); + if (currentTask != null) { + logger.warn("A Startup task is already locked or in progress, cannot create for link {}", + getLinkLog(link)); + return; + } + currentTask = new StartupTask(link); + if (startupTask.compareAndSet(null, currentTask)) { + selfTaskExecutor.schedule(currentTask, startupWait, TimeUnit.SECONDS); + return; + } + logger.warn("Failed to lock a StartupTask for link: {}", getLinkLog(link)); + } + + protected boolean cancelStartupTask() { + StartupTask task = startupTask.getAndSet(null); + if (task != null) { + task.cancel(); + return true; + } + return false; } public void sendStartup(final Link link) { - final StartupCommand[] startup = _resource.initialize(); + final StartupCommand[] startup = serverResource.initialize(); if (startup != null) { - final String msHostList = _shell.getPersistentProperty(null, "host"); + final String msHostList = shell.getPersistentProperty(null, "host"); final Command[] commands = new Command[startup.length]; for (int i = 0; i < startup.length; i++) { setupStartupCommand(startup[i]); startup[i].setMSHostList(msHostList); commands[i] = startup[i]; } - final Request request = new Request(_id != null ? _id : -1, -1, commands, false, false); + final Request request = new Request(id != null ? id : -1, -1, commands, false, false); request.setSequence(getNextSequence()); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Sending Startup: " + request.toString()); - } + logger.debug("Sending Startup: {}", request.toString()); lockStartupTask(link); try { link.send(request.toBytes()); } catch (final ClosedChannelException e) { - s_logger.warn("Unable to send request: " + request.toString()); + logger.warn("Unable to send request to {} due to '{}', request: {}", + getLinkLog(link), e.getMessage(), request); } - if (_resource instanceof ResourceStatusUpdater) { - ((ResourceStatusUpdater) _resource).registerStatusUpdater(this); + if (serverResource instanceof ResourceStatusUpdater) { + ((ResourceStatusUpdater) serverResource).registerStatusUpdater(this); } } } - protected void setupStartupCommand(final StartupCommand startup) { - InetAddress addr; + protected String retrieveHostname() { + logger.trace("Retrieving hostname with resource={}", () -> serverResource.getClass().getSimpleName()); + final String result = Script.runSimpleBashScript(Script.getExecutableAbsolutePath("hostname"), 500); + if (StringUtils.isNotBlank(result)) { + return result; + } try { - addr = InetAddress.getLocalHost(); + InetAddress address = InetAddress.getLocalHost(); + return address.toString(); } catch (final UnknownHostException e) { - s_logger.warn("unknown host? ", e); + logger.warn("unknown host? ", e); throw new CloudRuntimeException("Cannot get local IP address"); } + } - final Script command = new Script("hostname", 500, s_logger); - final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); - final String result = command.execute(parser); - final String hostname = result == null ? parser.getLine() : addr.toString(); - + protected void setupStartupCommand(final StartupCommand startup) { startup.setId(getId()); - if (startup.getName() == null) { + if (StringUtils.isBlank(startup.getName())) { + if (StringUtils.isBlank(hostname)) { + hostname = retrieveHostname(); + } startup.setName(hostname); } startup.setDataCenter(getZone()); @@ -508,6 +593,13 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater startup.setGuid(getResourceGuid()); startup.setResourceName(getResourceName()); startup.setVersion(getVersion()); + startup.setArch(getAgentArch()); + } + + protected String getAgentArch() { + String arch = Script.runSimpleBashScript(Script.getExecutableAbsolutePath("arch"), 2000); + logger.debug("Arch for agent: {} found: {}", _name, arch); + return arch; } @Override @@ -515,93 +607,94 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater return new ServerHandler(type, link, data); } - protected void reconnect(final Link link) { - if (!_reconnectAllowed) { + protected void closeAndTerminateLink(final Link link) { + if (link == null) { return; } - synchronized (this) { - if (_startup != null) { - _startup.cancel(); - _startup = null; - } - } + link.close(); + link.terminated(); + } - if (link != null) { - link.close(); - link.terminated(); + protected void stopAndCleanupConnection(boolean waitForStop) { + if (connection == null) { + return; } + connection.stop(); + try { + connection.cleanUp(); + } catch (final IOException e) { + logger.warn("Fail to clean up old connection. {}", e); + } + if (!waitForStop) { + return; + } + do { + shell.getBackoffAlgorithm().waitBeforeRetry(); + } while (connection.isStartup()); + } + protected void reconnect(final Link link) { + if (!reconnectAllowed) { + logger.debug("Reconnect requested but it is not allowed {}", () -> getLinkLog(link)); + return; + } + cancelStartupTask(); + closeAndTerminateLink(link); + closeAndTerminateLink(this.link); setLink(null); cancelTasks(); - - _resource.disconnected(); - - s_logger.info("Lost connection to host: " + _shell.getConnectedHost() + ". Attempting reconnection while we still have " + _inProgress.get() + " commands in progress."); - - _connection.stop(); - - try { - _connection.cleanUp(); - } catch (final IOException e) { - s_logger.warn("Fail to clean up old connection. " + e); - } - - while (_connection.isStartup()) { - _shell.getBackoffAlgorithm().waitBeforeRetry(); - } - + serverResource.disconnected(); + logger.info("Lost connection to host: {}. Attempting reconnection while we still have {} commands in progress.", shell.getConnectedHost(), commandsInProgress.get()); + stopAndCleanupConnection(true); do { - final String host = _shell.getNextHost(); - _connection = new NioClient("Agent", host, _shell.getPort(), _shell.getWorkers(), this); - s_logger.info("Reconnecting to host:" + host); + final String host = shell.getNextHost(); + connection = new NioClient(getAgentName(), host, shell.getPort(), shell.getWorkers(), shell.getSslHandshakeTimeout(), this); + logger.info("Reconnecting to host: {}", host); try { - _connection.start(); + connection.start(); } catch (final NioConnectionException e) { - s_logger.info("Attempted to re-connect to the server, but received an unexpected exception, trying again...", e); - _connection.stop(); - try { - _connection.cleanUp(); - } catch (final IOException ex) { - s_logger.warn("Fail to clean up old connection. " + ex); - } + logger.info("Attempted to re-connect to the server, but received an unexpected exception, trying again...", e); + stopAndCleanupConnection(false); } - _shell.getBackoffAlgorithm().waitBeforeRetry(); - } while (!_connection.isStartup()); - _shell.updateConnectedHost(); - s_logger.info("Connected to the host: " + _shell.getConnectedHost()); + shell.getBackoffAlgorithm().waitBeforeRetry(); + } while (!connection.isStartup()); + shell.updateConnectedHost(); + logger.info("Connected to the host: {}", shell.getConnectedHost()); } public void processStartupAnswer(final Answer answer, final Response response, final Link link) { - boolean cancelled = false; - synchronized (this) { - if (_startup != null) { - _startup.cancel(); - _startup = null; - } else { - cancelled = true; - } - } + boolean answerValid = cancelStartupTask(); final StartupAnswer startup = (StartupAnswer)answer; if (!startup.getResult()) { - s_logger.error("Not allowed to connect to the server: " + answer.getDetails()); + logger.error("Not allowed to connect to the server: {}", answer.getDetails()); + if (serverResource != null && !serverResource.isExitOnFailures()) { + logger.trace("{} does not allow exit on failure, reconnecting", + serverResource.getClass().getSimpleName()); + reconnect(link); + return; + } System.exit(1); } - if (cancelled) { - s_logger.warn("Threw away a startup answer because we're reconnecting."); + if (!answerValid) { + logger.warn("Threw away a startup answer because we're reconnecting."); return; } - s_logger.info("Process agent startup answer, agent id = " + startup.getHostId()); + logger.info("Process agent startup answer, agent [id: {}, uuid: {}, name: {}] connected to the server", + startup.getHostId(), startup.getHostUuid(), startup.getHostName()); setId(startup.getHostId()); - _pingInterval = (long)startup.getPingInterval() * 1000; // change to ms. + setUuid(startup.getHostUuid()); + setName(startup.getHostName()); + pingInterval = startup.getPingInterval() * 1000L; // change to ms. - setLastPingResponseTime(); - scheduleWatch(link, response, _pingInterval, _pingInterval); + updateLastPingResponseTime(); + scheduleWatch(link, response, pingInterval, pingInterval); - _ugentTaskPool.setKeepAliveTime(2 * _pingInterval, TimeUnit.MILLISECONDS); + outRequestHandler.setKeepAliveTime(2 * pingInterval, TimeUnit.MILLISECONDS); - s_logger.info("Startup Response Received: agent id = " + getId()); + logger.info("Startup Response Received: agent [id: {}, uuid: {}, name: {}]", + startup.getHostId(), startup.getHostUuid(), startup.getHostName()); } protected void processRequest(final Request request, final Link link) { @@ -615,62 +708,64 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater final Command cmd = cmds[i]; Answer answer; try { - if (cmd.getContextParam("logid") != null) { - MDC.put("logcontextid", cmd.getContextParam("logid")); - } - if (s_logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { if (!requestLogged) // ensures request is logged only once per method call { final String requestMsg = request.toString(); if (requestMsg != null) { - s_logger.debug("Request:" + requestMsg); + logger.debug("Request:{}",requestMsg); } requestLogged = true; } - s_logger.debug("Processing command: " + cmd.toString()); + logger.debug("Processing command: {}", cmd.toString()); } if (cmd instanceof CronCommand) { final CronCommand watch = (CronCommand)cmd; - scheduleWatch(link, request, (long)watch.getInterval() * 1000, watch.getInterval() * 1000); + scheduleWatch(link, request, watch.getInterval() * 1000L, watch.getInterval() * 1000L); answer = new Answer(cmd, true, null); } else if (cmd instanceof ShutdownCommand) { final ShutdownCommand shutdown = (ShutdownCommand)cmd; - s_logger.debug("Received shutdownCommand, due to: " + shutdown.getReason()); + logger.debug("Received shutdownCommand, due to: {}", shutdown.getReason()); cancelTasks(); if (shutdown.isRemoveHost()) { cleanupAgentZoneProperties(); } - _reconnectAllowed = false; + reconnectAllowed = false; answer = new Answer(cmd, true, null); } else if (cmd instanceof ReadyCommand && ((ReadyCommand)cmd).getDetails() != null) { - s_logger.debug("Not ready to connect to mgt server: " + ((ReadyCommand)cmd).getDetails()); + + logger.debug("Not ready to connect to mgt server: {}", ((ReadyCommand)cmd).getDetails()); + if (serverResource != null && !serverResource.isExitOnFailures()) { + logger.trace("{} does not allow exit on failure, reconnecting", + serverResource.getClass().getSimpleName()); + reconnect(link); + return; + } System.exit(1); return; } else if (cmd instanceof MaintainCommand) { - s_logger.debug("Received maintainCommand, do not cancel current tasks"); + logger.debug("Received maintainCommand, do not cancel current tasks"); answer = new MaintainAnswer((MaintainCommand)cmd); } else if (cmd instanceof AgentControlCommand) { answer = null; - synchronized (_controlListeners) { - for (final IAgentControlListener listener : _controlListeners) { - answer = listener.processControlRequest(request, (AgentControlCommand)cmd); - if (answer != null) { - break; - } + for (final IAgentControlListener listener : controlListeners) { + answer = listener.processControlRequest(request, (AgentControlCommand)cmd); + if (answer != null) { + break; } } if (answer == null) { - s_logger.warn("No handler found to process cmd: " + cmd.toString()); + logger.warn("No handler found to process cmd: {}", cmd.toString()); answer = new AgentControlAnswer(cmd); } } else if (cmd instanceof SetupKeyStoreCommand && ((SetupKeyStoreCommand) cmd).isHandleByAgent()) { answer = setupAgentKeystore((SetupKeyStoreCommand) cmd); } else if (cmd instanceof SetupCertificateCommand && ((SetupCertificateCommand) cmd).isHandleByAgent()) { answer = setupAgentCertificate((SetupCertificateCommand) cmd); - if (Host.Type.Routing.equals(_resource.getType())) { - scheduleServicesRestartTask(); + if (Host.Type.Routing.equals(serverResource.getType())) { + scheduleCertificateRenewalTask(); } } else if (cmd instanceof SetupMSListCommand) { answer = setupManagementServerList((SetupMSListCommand) cmd); @@ -678,19 +773,19 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater if (cmd instanceof ReadyCommand) { processReadyCommand(cmd); } - _inProgress.incrementAndGet(); + commandsInProgress.incrementAndGet(); try { - answer = _resource.executeRequest(cmd); + answer = serverResource.executeRequest(cmd); } finally { - _inProgress.decrementAndGet(); + commandsInProgress.decrementAndGet(); } if (answer == null) { - s_logger.debug("Response: unsupported command" + cmd.toString()); + logger.debug("Response: unsupported command {}", cmd.toString()); answer = Answer.createUnsupportedCommandAnswer(cmd); } } } catch (final Throwable th) { - s_logger.warn("Caught: ", th); + logger.warn("Caught: ", th); final StringWriter writer = new StringWriter(); th.printStackTrace(new PrintWriter(writer)); answer = new Answer(cmd, false, writer.toString()); @@ -706,10 +801,10 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater } response = new Response(request, answers); } finally { - if (s_logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { final String responseMsg = response.toString(); if (responseMsg != null) { - s_logger.debug(response.toString()); + logger.debug(response.toString()); } } @@ -717,7 +812,7 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater try { link.send(response.toBytes()); } catch (final ClosedChannelException e) { - s_logger.warn("Unable to send response: " + response.toString()); + logger.warn("Unable to send response: {}", response.toString()); } } } @@ -727,7 +822,7 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater final String keyStorePassword = cmd.getKeystorePassword(); final long validityDays = cmd.getValidityDays(); - s_logger.debug("Setting up agent keystore file and generating CSR"); + logger.debug("Setting up agent keystore file and generating CSR"); final File agentFile = PropertiesUtil.findConfigFile("agent.properties"); if (agentFile == null) { @@ -736,13 +831,13 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater final String keyStoreFile = agentFile.getParent() + "/" + KeyStoreUtils.KS_FILENAME; final String csrFile = agentFile.getParent() + "/" + KeyStoreUtils.CSR_FILENAME; - String storedPassword = _shell.getPersistentProperty(null, KeyStoreUtils.KS_PASSPHRASE_PROPERTY); + String storedPassword = shell.getPersistentProperty(null, KeyStoreUtils.KS_PASSPHRASE_PROPERTY); if (StringUtils.isEmpty(storedPassword)) { storedPassword = keyStorePassword; - _shell.setPersistentProperty(null, KeyStoreUtils.KS_PASSPHRASE_PROPERTY, storedPassword); + shell.setPersistentProperty(null, KeyStoreUtils.KS_PASSPHRASE_PROPERTY, storedPassword); } - Script script = new Script(_keystoreSetupPath, 300000, s_logger); + Script script = new Script(keystoreSetupSetupPath, 300000, logger); script.add(agentFile.getAbsolutePath()); script.add(keyStoreFile); script.add(storedPassword); @@ -767,7 +862,7 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater final String privateKey = cmd.getPrivateKey(); final String caCertificates = cmd.getCaCertificates(); - s_logger.debug("Importing received certificate to agent's keystore"); + logger.debug("Importing received certificate to agent's keystore"); final File agentFile = PropertiesUtil.findConfigFile("agent.properties"); if (agentFile == null) { @@ -781,13 +876,13 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater try { FileUtils.writeStringToFile(new File(certFile), certificate, Charset.defaultCharset()); FileUtils.writeStringToFile(new File(caCertFile), caCertificates, Charset.defaultCharset()); - s_logger.debug("Saved received client certificate to: " + certFile); + logger.debug("Saved received client certificate to: {}", certFile); } catch (IOException e) { throw new CloudRuntimeException("Unable to save received agent client and ca certificates", e); } - String ksPassphrase = _shell.getPersistentProperty(null, KeyStoreUtils.KS_PASSPHRASE_PROPERTY); - Script script = new Script(_keystoreCertImportPath, 300000, s_logger); + String ksPassphrase = shell.getPersistentProperty(null, KeyStoreUtils.KS_PASSPHRASE_PROPERTY); + Script script = new Script(keystoreCertImportScriptPath, 300000, logger); script.add(agentFile.getAbsolutePath()); script.add(ksPassphrase); script.add(keyStoreFile); @@ -809,10 +904,10 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater if (CollectionUtils.isNotEmpty(msList) && StringUtils.isNotEmpty(lbAlgorithm)) { try { final String newMSHosts = String.format("%s%s%s", com.cloud.utils.StringUtils.toCSVList(msList), IAgentShell.hostLbAlgorithmSeparator, lbAlgorithm); - _shell.setPersistentProperty(null, "host", newMSHosts); - _shell.setHosts(newMSHosts); - _shell.resetHostCounter(); - s_logger.info("Processed new management server list: " + newMSHosts); + shell.setPersistentProperty(null, "host", newMSHosts); + shell.setHosts(newMSHosts); + shell.resetHostCounter(); + logger.info("Processed new management server list: {}", newMSHosts); } catch (final Exception e) { throw new CloudRuntimeException("Could not persist received management servers list", e); } @@ -820,7 +915,7 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater if ("shuffle".equals(lbAlgorithm)) { scheduleHostLBCheckerTask(0); } else { - scheduleHostLBCheckerTask(_shell.getLbCheckerInterval(lbCheckInterval)); + scheduleHostLBCheckerTask(shell.getLbCheckerInterval(lbCheckInterval)); } } @@ -831,23 +926,19 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater public void processResponse(final Response response, final Link link) { final Answer answer = response.getAnswer(); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Received response: " + response.toString()); - } + logger.debug("Received response: {}", response.toString()); if (answer instanceof StartupAnswer) { processStartupAnswer(answer, response, link); } else if (answer instanceof AgentControlAnswer) { // Notice, we are doing callback while holding a lock! - synchronized (_controlListeners) { - for (final IAgentControlListener listener : _controlListeners) { - listener.processControlResponse(response, (AgentControlAnswer)answer); - } + for (final IAgentControlListener listener : controlListeners) { + listener.processControlResponse(response, (AgentControlAnswer)answer); } - } else if (answer instanceof PingAnswer && (((PingAnswer) answer).isSendStartup()) && _reconnectAllowed) { - s_logger.info("Management server requested startup command to reinitialize the agent"); + } else if (answer instanceof PingAnswer && (((PingAnswer) answer).isSendStartup()) && reconnectAllowed) { + logger.info("Management server requested startup command to reinitialize the agent"); sendStartup(link); } else { - setLastPingResponseTime(); + updateLastPingResponseTime(); } } @@ -859,98 +950,102 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater NumbersUtil.enableHumanReadableSizes = humanReadable; } - s_logger.info("Processing agent ready command, agent id = " + ready.getHostId()); + logger.info("Processing agent ready command, agent id = {}, uuid = {}, name = {}", ready.getHostId(), ready.getHostUuid(), ready.getHostName()); if (ready.getHostId() != null) { setId(ready.getHostId()); + setUuid(ready.getHostUuid()); + setName(ready.getHostName()); } + verifyAgentArch(ready.getArch()); processManagementServerList(ready.getMsHostList(), ready.getLbAlgorithm(), ready.getLbCheckInterval()); - s_logger.info("Ready command is processed for agent id = " + getId()); + logger.info("Ready command is processed for agent [id: {}, uuid: {}, name: {}]", getId(), getUuid(), getName()); + } + + private void verifyAgentArch(String arch) { + if (StringUtils.isNotBlank(arch)) { + String agentArch = getAgentArch(); + if (!arch.equals(agentArch)) { + logger.error("Unexpected arch {}, expected {}", agentArch, arch); + } + } } public void processOtherTask(final Task task) { final Object obj = task.get(); if (obj instanceof Response) { - if (System.currentTimeMillis() - _lastPingResponseTime > _pingInterval * _shell.getPingRetries()) { - s_logger.error("Ping Interval has gone past " + _pingInterval * _shell.getPingRetries() + ". Won't reconnect to mgt server, as connection is still alive"); + if (System.currentTimeMillis() - lastPingResponseTime.get() > pingInterval * shell.getPingRetries()) { + logger.error("Ping Interval has gone past {}. Won't reconnect to mgt server, as connection is still alive", + pingInterval * shell.getPingRetries()); return; } - final PingCommand ping = _resource.getCurrentStatus(getId()); - final Request request = new Request(_id, -1, ping, false); + final PingCommand ping = serverResource.getCurrentStatus(getId()); + final Request request = new Request(id, -1, ping, false); request.setSequence(getNextSequence()); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Sending ping: " + request.toString()); - } + logger.debug("Sending ping: {}", request.toString()); try { task.getLink().send(request.toBytes()); //if i can send pingcommand out, means the link is ok - setLastPingResponseTime(); + updateLastPingResponseTime(); } catch (final ClosedChannelException e) { - s_logger.warn("Unable to send request: " + request.toString()); + logger.warn("Unable to send request to {} due to '{}', request: {}", + getLinkLog(task.getLink()), e.getMessage(), request); } } else if (obj instanceof Request) { final Request req = (Request)obj; final Command command = req.getCommand(); if (command.getContextParam("logid") != null) { - MDC.put("logcontextid", command.getContextParam("logid")); + ThreadContext.put("logcontextid", command.getContextParam("logid")); } Answer answer = null; - _inProgress.incrementAndGet(); + commandsInProgress.incrementAndGet(); try { - answer = _resource.executeRequest(command); + answer = serverResource.executeRequest(command); } finally { - _inProgress.decrementAndGet(); + commandsInProgress.decrementAndGet(); } if (answer != null) { final Response response = new Response(req, answer); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Watch Sent: " + response.toString()); - } + logger.debug("Watch Sent: {}", response.toString()); try { task.getLink().send(response.toBytes()); } catch (final ClosedChannelException e) { - s_logger.warn("Unable to send response: " + response.toString()); + logger.warn("Unable to send response: {}", response.toString()); } } } else { - s_logger.warn("Ignoring an unknown task"); + logger.warn("Ignoring an unknown task"); } } - public synchronized void setLastPingResponseTime() { - _lastPingResponseTime = System.currentTimeMillis(); + public void updateLastPingResponseTime() { + lastPingResponseTime.set(System.currentTimeMillis()); } - protected synchronized long getNextSequence() { - return _sequence++; + protected long getNextSequence() { + return sequence.getAndIncrement(); } @Override public void registerControlListener(final IAgentControlListener listener) { - synchronized (_controlListeners) { - _controlListeners.add(listener); - } + controlListeners.add(listener); } @Override public void unregisterControlListener(final IAgentControlListener listener) { - synchronized (_controlListeners) { - _controlListeners.remove(listener); - } + controlListeners.remove(listener); } @Override public AgentControlAnswer sendRequest(final AgentControlCommand cmd, final int timeoutInMilliseconds) throws AgentControlChannelException { final Request request = new Request(getId(), -1, new Command[] {cmd}, true, false); request.setSequence(getNextSequence()); - final AgentControlListener listener = new AgentControlListener(request); - registerControlListener(listener); try { postRequest(request); @@ -958,10 +1053,9 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater try { listener.wait(timeoutInMilliseconds); } catch (final InterruptedException e) { - s_logger.warn("sendRequest is interrupted, exit waiting"); + logger.warn("sendRequest is interrupted, exit waiting"); } } - return listener.getAnswer(); } finally { unregisterControlListener(listener); @@ -976,11 +1070,11 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater } private void postRequest(final Request request) throws AgentControlChannelException { - if (_link != null) { + if (link != null) { try { - _link.send(request.toBytes()); + link.send(request.toBytes()); } catch (final ClosedChannelException e) { - s_logger.warn("Unable to post agent control request: " + request.toString()); + logger.warn("Unable to post agent control request: {}", request.toString()); throw new AgentControlChannelException("Unable to post agent control request due to " + e.getMessage()); } } else { @@ -1030,7 +1124,7 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater } } - public class WatchTask extends ManagedContextTimerTask { + public class WatchTask implements Runnable { protected Request _request; protected Agent _agent; protected Link _link; @@ -1043,52 +1137,45 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater } @Override - protected void runInContext() { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Scheduling " + (_request instanceof Response ? "Ping" : "Watch Task")); - } + public void run() { + logger.trace("Scheduling {}", (_request instanceof Response ? "Ping" : "Watch Task")); try { if (_request instanceof Response) { - _ugentTaskPool.submit(new ServerHandler(Task.Type.OTHER, _link, _request)); + outRequestHandler.submit(new ServerHandler(Task.Type.OTHER, _link, _request)); } else { _link.schedule(new ServerHandler(Task.Type.OTHER, _link, _request)); } } catch (final ClosedChannelException e) { - s_logger.warn("Unable to schedule task because channel is closed"); + logger.warn("Unable to schedule task because channel is closed"); } } } - public class StartupTask extends ManagedContextTimerTask { + public class StartupTask implements Runnable { protected Link _link; - protected volatile boolean cancelled = false; + private final AtomicBoolean cancelled = new AtomicBoolean(false); public StartupTask(final Link link) { - s_logger.debug("Startup task created"); + logger.debug("Startup task created"); _link = link; } - @Override - public synchronized boolean cancel() { + public boolean cancel() { // TimerTask.cancel may fail depends on the calling context - if (!cancelled) { - cancelled = true; - _startupWait = _startupWaitDefault; - s_logger.debug("Startup task cancelled"); - return super.cancel(); + if (cancelled.compareAndSet(false, true)) { + startupWait = DEFAULT_STARTUP_WAIT; + logger.debug("Startup task cancelled"); } return true; } @Override - protected synchronized void runInContext() { - if (!cancelled) { - if (s_logger.isInfoEnabled()) { - s_logger.info("The startup command is now cancelled"); - } - cancelled = true; - _startup = null; - _startupWait = _startupWaitDefault * 2; + public void run() { + if (cancelled.compareAndSet(false, true)) { + logger.info("The running startup command is now invalid. Attempting reconnect"); + startupTask.set(null); + startupWait = DEFAULT_STARTUP_WAIT * 2; + logger.debug("Executing reconnect from task - {}", () -> getLinkLog(_link)); reconnect(_link); } } @@ -1120,7 +1207,7 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater @Override public void doTask(final Task task) throws TaskExecutionException { if (task.getType() == Task.Type.CONNECT) { - _shell.getBackoffAlgorithm().reset(); + shell.getBackoffAlgorithm().reset(); setLink(task.getLink()); sendStartup(task.getLink()); } else if (task.getType() == Task.Type.DATA) { @@ -1133,22 +1220,23 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater } else { //put the requests from mgt server into another thread pool, as the request may take a longer time to finish. Don't block the NIO main thread pool //processRequest(request, task.getLink()); - _executor.submit(new AgentRequestHandler(getType(), getLink(), request)); + requestHandler.submit(new AgentRequestHandler(getType(), getLink(), request)); } } catch (final ClassNotFoundException e) { - s_logger.error("Unable to find this request "); + logger.error("Unable to find this request "); } catch (final Exception e) { - s_logger.error("Error parsing task", e); + logger.error("Error parsing task", e); } } else if (task.getType() == Task.Type.DISCONNECT) { try { - // an issue has been found if reconnect immediately after disconnecting. please refer to https://github.com/apache/cloudstack/issues/8517 + // an issue has been found if reconnect immediately after disconnecting. // wait 5 seconds before reconnecting + logger.debug("Wait for 5 secs before reconnecting, disconnect task - {}", () -> getLinkLog(task.getLink())); Thread.sleep(5000); } catch (InterruptedException e) { } + logger.debug("Executing disconnect task - {} and reconnecting", () -> getLinkLog(task.getLink())); reconnect(task.getLink()); - return; } else if (task.getType() == Task.Type.OTHER) { processOtherTask(task); } @@ -1171,38 +1259,36 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater protected void runInContext() { while (true) { try { - if (_inProgress.get() == 0) { - s_logger.debug("Running post certificate renewal task to restart services."); + if (commandsInProgress.get() == 0) { + logger.debug("Running post certificate renewal task to restart services."); // Let the resource perform any post certificate renewal cleanups - _resource.executeRequest(new PostCertificateRenewalCommand()); + serverResource.executeRequest(new PostCertificateRenewalCommand()); - IAgentShell shell = agent._shell; - ServerResource resource = agent._resource.getClass().newInstance(); + IAgentShell shell = agent.shell; + ServerResource resource = agent.serverResource.getClass().getDeclaredConstructor().newInstance(); // Stop current agent agent.cancelTasks(); - agent._reconnectAllowed = false; - Runtime.getRuntime().removeShutdownHook(agent._shutdownThread); + agent.reconnectAllowed = false; + Runtime.getRuntime().removeShutdownHook(agent.shutdownThread); agent.stop(ShutdownCommand.Requested, "Restarting due to new X509 certificates"); // Nullify references for GC - agent._shell = null; - agent._watchList = null; - agent._shutdownThread = null; - agent._controlListeners = null; + agent.shell = null; + agent.watchList = null; + agent.shutdownThread = null; + agent.controlListeners = null; agent = null; // Start a new agent instance shell.launchNewAgent(resource); return; } - if (s_logger.isTraceEnabled()) { - s_logger.debug("Other tasks are in progress, will retry post certificate renewal command after few seconds"); - } + logger.debug("Other tasks are in progress, will retry post certificate renewal command after few seconds"); Thread.sleep(5000); } catch (final Exception e) { - s_logger.warn("Failed to execute post certificate renewal command:", e); + logger.warn("Failed to execute post certificate renewal command:", e); break; } } @@ -1214,38 +1300,34 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater @Override protected void runInContext() { try { - final String[] msList = _shell.getHosts(); + final String[] msList = shell.getHosts(); if (msList == null || msList.length < 1) { return; } final String preferredHost = msList[0]; - final String connectedHost = _shell.getConnectedHost(); - if (s_logger.isTraceEnabled()) { - s_logger.trace("Running preferred host checker task, connected host=" + connectedHost + ", preferred host=" + preferredHost); + final String connectedHost = shell.getConnectedHost(); + logger.debug("Running preferred host checker task, connected host={}, preferred host={}", + connectedHost, preferredHost); + if (preferredHost == null || preferredHost.equals(connectedHost) || link == null) { + return; } - if (preferredHost != null && !preferredHost.equals(connectedHost) && _link != null) { - boolean isHostUp = true; - try (final Socket socket = new Socket()) { - socket.connect(new InetSocketAddress(preferredHost, _shell.getPort()), 5000); - } catch (final IOException e) { - isHostUp = false; - if (s_logger.isTraceEnabled()) { - s_logger.trace("Host: " + preferredHost + " is not reachable"); - } - } - if (isHostUp && _link != null && _inProgress.get() == 0) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Preferred host " + preferredHost + " is found to be reachable, trying to reconnect"); - } - _shell.resetHostCounter(); - reconnect(_link); + boolean isHostUp = false; + try (final Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(preferredHost, shell.getPort()), 5000); + isHostUp = true; + } catch (final IOException e) { + logger.debug("Host: {} is not reachable", preferredHost); + } + if (isHostUp && link != null && commandsInProgress.get() == 0) { + if (logger.isDebugEnabled()) { + logger.debug("Preferred host {} is found to be reachable, trying to reconnect", preferredHost); } + shell.resetHostCounter(); + reconnect(link); } } catch (Throwable t) { - s_logger.error("Error caught while attempting to connect to preferred host", t); + logger.error("Error caught while attempting to connect to preferred host", t); } } - } - } diff --git a/agent/src/main/java/com/cloud/agent/AgentShell.java b/agent/src/main/java/com/cloud/agent/AgentShell.java index ef042496a37..c5257b95b7c 100644 --- a/agent/src/main/java/com/cloud/agent/AgentShell.java +++ b/agent/src/main/java/com/cloud/agent/AgentShell.java @@ -16,28 +16,6 @@ // under the License. package com.cloud.agent; -import com.cloud.agent.Agent.ExitStatus; -import com.cloud.agent.dao.StorageComponent; -import com.cloud.agent.dao.impl.PropertiesStorage; -import com.cloud.agent.properties.AgentProperties; -import com.cloud.agent.properties.AgentPropertiesFileHandler; -import com.cloud.resource.ServerResource; -import com.cloud.utils.LogUtils; -import com.cloud.utils.ProcessUtil; -import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.backoff.BackoffAlgorithm; -import com.cloud.utils.backoff.impl.ConstantTimeBackoff; -import com.cloud.utils.exception.CloudRuntimeException; -import org.apache.commons.daemon.Daemon; -import org.apache.commons.daemon.DaemonContext; -import org.apache.commons.daemon.DaemonInitException; -import org.apache.commons.lang.math.NumberUtils; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; -import org.apache.log4j.xml.DOMConfigurator; - -import javax.naming.ConfigurationException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -52,8 +30,33 @@ import java.util.Map; import java.util.Properties; import java.util.UUID; +import javax.naming.ConfigurationException; + +import org.apache.commons.daemon.Daemon; +import org.apache.commons.daemon.DaemonContext; +import org.apache.commons.daemon.DaemonInitException; +import org.apache.commons.lang.math.NumberUtils; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.config.Configurator; + +import com.cloud.agent.Agent.ExitStatus; +import com.cloud.agent.dao.StorageComponent; +import com.cloud.agent.dao.impl.PropertiesStorage; +import com.cloud.agent.properties.AgentProperties; +import com.cloud.agent.properties.AgentPropertiesFileHandler; +import com.cloud.resource.ServerResource; +import com.cloud.utils.LogUtils; +import com.cloud.utils.ProcessUtil; +import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.backoff.BackoffAlgorithm; +import com.cloud.utils.backoff.impl.ConstantTimeBackoff; +import com.cloud.utils.exception.CloudRuntimeException; + public class AgentShell implements IAgentShell, Daemon { - private static final Logger s_logger = Logger.getLogger(AgentShell.class.getName()); + protected static Logger LOGGER = LogManager.getLogger(AgentShell.class); private final Properties _properties = new Properties(); private final Map _cmdLineProperties = new HashMap(); @@ -221,7 +224,7 @@ public class AgentShell implements IAgentShell, Daemon { throw new ConfigurationException("Unable to find agent.properties."); } - s_logger.info("agent.properties found at " + file.getAbsolutePath()); + LOGGER.info("agent.properties found at {}", file.getAbsolutePath()); try { PropertiesUtil.loadFromFile(_properties, file); @@ -349,7 +352,7 @@ public class AgentShell implements IAgentShell, Daemon { @Override public void init(DaemonContext dc) throws DaemonInitException { - s_logger.debug("Initializing AgentShell from JSVC"); + LOGGER.debug("Initializing AgentShell from JSVC"); try { init(dc.getArguments()); } catch (ConfigurationException ex) { @@ -369,11 +372,11 @@ public class AgentShell implements IAgentShell, Daemon { } if (null != file) { - DOMConfigurator.configureAndWatch(file.getAbsolutePath()); + Configurator.initialize(null, file.getAbsolutePath()); - s_logger.info("Agent started"); + LOGGER.info("Agent started"); } else { - s_logger.error("Could not start the Agent because the absolute path of the \"log4j-cloud.xml\" file cannot be determined."); + LOGGER.error("Could not start the Agent because the absolute path of the \"log4j-cloud.xml\" file cannot be determined."); } final Class c = this.getClass(); @@ -381,19 +384,19 @@ public class AgentShell implements IAgentShell, Daemon { if (_version == null) { throw new CloudRuntimeException("Unable to find the implementation version of this agent"); } - s_logger.info("Implementation Version is " + _version); + LOGGER.info("Implementation Version is {}", _version); loadProperties(); parseCommand(args); - if (s_logger.isDebugEnabled()) { + if (LOGGER.isDebugEnabled()) { List properties = Collections.list((Enumeration)_properties.propertyNames()); for (String property : properties) { - s_logger.debug("Found property: " + property); + LOGGER.debug("Found property: {}", property); } } - s_logger.info("Defaulting to using properties file for storage"); + LOGGER.info("Defaulting to using properties file for storage"); _storage = new PropertiesStorage(); _storage.configure("Storage", new HashMap()); @@ -403,14 +406,16 @@ public class AgentShell implements IAgentShell, Daemon { _properties.put(cmdLineProp.getKey(), cmdLineProp.getValue()); } - s_logger.info("Defaulting to the constant time backoff algorithm"); + LOGGER.info("Defaulting to the constant time backoff algorithm"); _backoff = new ConstantTimeBackoff(); - _backoff.configure("ConstantTimeBackoff", new HashMap()); + Map map = new HashMap<>(); + map.put("seconds", _properties.getProperty("backoff.seconds")); + _backoff.configure("ConstantTimeBackoff", map); } private void launchAgent() throws ConfigurationException { String resourceClassNames = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.RESOURCE); - s_logger.trace("resource=" + resourceClassNames); + LOGGER.trace("resource={}", resourceClassNames); if (resourceClassNames != null) { launchAgentFromClassInfo(resourceClassNames); return; @@ -440,10 +445,10 @@ public class AgentShell implements IAgentShell, Daemon { private void launchAgentFromTypeInfo() throws ConfigurationException { String typeInfo = getProperty(null, "type"); if (typeInfo == null) { - s_logger.error("Unable to retrieve the type"); + LOGGER.error("Unable to retrieve the type"); throw new ConfigurationException("Unable to retrieve the type of this agent."); } - s_logger.trace("Launching agent based on type=" + typeInfo); + LOGGER.trace("Launching agent based on type={}", typeInfo); } public void launchNewAgent(ServerResource resource) throws ConfigurationException { @@ -454,6 +459,11 @@ public class AgentShell implements IAgentShell, Daemon { agent.start(); } + @Override + public Integer getSslHandshakeTimeout() { + return AgentPropertiesFileHandler.getPropertyValue(AgentProperties.SSL_HANDSHAKE_TIMEOUT); + } + public synchronized int getNextAgentId() { return _nextAgentId++; } @@ -477,17 +487,17 @@ public class AgentShell implements IAgentShell, Daemon { } if (ipv6disabled) { - s_logger.info("Preferring IPv4 address family for agent connection"); + LOGGER.info("Preferring IPv4 address family for agent connection"); System.setProperty("java.net.preferIPv4Stack", "true"); if (ipv6prefer) { - s_logger.info("ipv6prefer is set to true, but ipv6disabled is false. Not preferring IPv6 for agent connection"); + LOGGER.info("ipv6prefer is set to true, but ipv6disabled is false. Not preferring IPv6 for agent connection"); } } else { if (ipv6prefer) { - s_logger.info("Preferring IPv6 address family for agent connection"); + LOGGER.info("Preferring IPv6 address family for agent connection"); System.setProperty("java.net.preferIPv6Addresses", "true"); } else { - s_logger.info("Using default Java settings for IPv6 preference for agent connection"); + LOGGER.info("Using default Java settings for IPv6 preference for agent connection"); } } @@ -505,7 +515,7 @@ public class AgentShell implements IAgentShell, Daemon { String pidDir = getProperty(null, "piddir"); final String run = "agent." + instance + "pid"; - s_logger.debug("Checking to see if " + run + " exists."); + LOGGER.debug("Checking to see if {} exists.", run); ProcessUtil.pidCheck(pidDir, run); launchAgent(); @@ -514,11 +524,11 @@ public class AgentShell implements IAgentShell, Daemon { while (!_exit) Thread.sleep(1000); } catch (InterruptedException e) { - s_logger.debug("[ignored] AgentShell was interrupted."); + LOGGER.debug("[ignored] AgentShell was interrupted."); } } catch (final Exception e) { - s_logger.error("Unable to start agent: ", e); + LOGGER.error("Unable to start agent: ", e); System.exit(ExitStatus.Error.value()); } } @@ -535,7 +545,7 @@ public class AgentShell implements IAgentShell, Daemon { public static void main(String[] args) { try { - s_logger.debug("Initializing AgentShell from main"); + LOGGER.debug("Initializing AgentShell from main"); AgentShell shell = new AgentShell(); shell.init(args); shell.start(); diff --git a/agent/src/main/java/com/cloud/agent/IAgentShell.java b/agent/src/main/java/com/cloud/agent/IAgentShell.java index 2dd08fffd45..7f04048795d 100644 --- a/agent/src/main/java/com/cloud/agent/IAgentShell.java +++ b/agent/src/main/java/com/cloud/agent/IAgentShell.java @@ -70,4 +70,6 @@ public interface IAgentShell { String getConnectedHost(); void launchNewAgent(ServerResource resource) throws ConfigurationException; + + Integer getSslHandshakeTimeout(); } diff --git a/agent/src/main/java/com/cloud/agent/dao/impl/PropertiesStorage.java b/agent/src/main/java/com/cloud/agent/dao/impl/PropertiesStorage.java index 87610c29f34..17e0ceeeede 100644 --- a/agent/src/main/java/com/cloud/agent/dao/impl/PropertiesStorage.java +++ b/agent/src/main/java/com/cloud/agent/dao/impl/PropertiesStorage.java @@ -24,7 +24,8 @@ import java.util.Map; import java.util.Properties; import org.apache.commons.io.IOUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.agent.dao.StorageComponent; import com.cloud.utils.PropertiesUtil; @@ -36,7 +37,7 @@ import com.cloud.utils.PropertiesUtil; * path to the properties _file | String | db/db.properties || * } **/ public class PropertiesStorage implements StorageComponent { - private static final Logger s_logger = Logger.getLogger(PropertiesStorage.class); + protected Logger logger = LogManager.getLogger(getClass()); Properties _properties = new Properties(); File _file; String _name; @@ -49,7 +50,7 @@ public class PropertiesStorage implements StorageComponent { @Override public synchronized void persist(String key, String value) { if (!loadFromFile(_file)) { - s_logger.error("Failed to load changes and then write to them"); + logger.error("Failed to load changes and then write to them"); } _properties.setProperty(key, value); FileOutputStream output = null; @@ -59,7 +60,7 @@ public class PropertiesStorage implements StorageComponent { output.flush(); output.close(); } catch (IOException e) { - s_logger.error("Uh-oh: ", e); + logger.error("Uh-oh: ", e); } finally { IOUtils.closeQuietly(output); } @@ -70,10 +71,10 @@ public class PropertiesStorage implements StorageComponent { PropertiesUtil.loadFromFile(_properties, file); _file = file; } catch (FileNotFoundException e) { - s_logger.error("How did we get here? ", e); + logger.error("How did we get here? ", e); return false; } catch (IOException e) { - s_logger.error("IOException: ", e); + logger.error("IOException: ", e); return false; } return true; @@ -92,14 +93,12 @@ public class PropertiesStorage implements StorageComponent { file = new File(path); try { if (!file.createNewFile()) { - s_logger.error(String.format("Unable to create _file: %s", file.getAbsolutePath())); + logger.error("Unable to create _file: {}", file.getAbsolutePath()); return false; } } catch (IOException e) { - s_logger.error(String.format("Unable to create file: %s", file.getAbsolutePath())); - if (s_logger.isDebugEnabled()) { - s_logger.debug(String.format("IOException while trying to create file: %s", file.getAbsolutePath()), e); - } + logger.error("Unable to create file: {}", file.getAbsolutePath()); + logger.debug("IOException while trying to create file: {}", file.getAbsolutePath(), e); return false; } } diff --git a/agent/src/main/java/com/cloud/agent/dhcp/DhcpProtocolParserServer.java b/agent/src/main/java/com/cloud/agent/dhcp/DhcpProtocolParserServer.java index 0ee9fd6860d..00488f94382 100644 --- a/agent/src/main/java/com/cloud/agent/dhcp/DhcpProtocolParserServer.java +++ b/agent/src/main/java/com/cloud/agent/dhcp/DhcpProtocolParserServer.java @@ -25,12 +25,13 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import org.apache.log4j.Logger; import com.cloud.utils.concurrency.NamedThreadFactory; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; public class DhcpProtocolParserServer extends Thread { - private static final Logger s_logger = Logger.getLogger(DhcpProtocolParserServer.class);; + protected Logger logger = LogManager.getLogger(DhcpProtocolParserServer.class);; protected ExecutorService _executor; private int dhcpServerPort = 67; private int bufferSize = 300; @@ -54,7 +55,7 @@ public class DhcpProtocolParserServer extends Thread { dhcpSocket.receive(dgp); } } catch (IOException e) { - s_logger.debug(e.getMessage()); + logger.debug(e.getMessage()); } } } diff --git a/agent/src/main/java/com/cloud/agent/mockvm/MockVmMgr.java b/agent/src/main/java/com/cloud/agent/mockvm/MockVmMgr.java index b155cb725b1..54fdde3d3d2 100644 --- a/agent/src/main/java/com/cloud/agent/mockvm/MockVmMgr.java +++ b/agent/src/main/java/com/cloud/agent/mockvm/MockVmMgr.java @@ -22,14 +22,15 @@ import java.util.Map; import java.util.Random; import java.util.Set; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VirtualMachine.State; public class MockVmMgr implements VmMgr { - private static final Logger s_logger = Logger.getLogger(MockVmMgr.class); + protected Logger logger = LogManager.getLogger(getClass()); private static final int DEFAULT_DOM0_MEM_MB = 128; private static final Random randSeed = new Random(); @@ -56,14 +57,14 @@ public class MockVmMgr implements VmMgr { public String startVM(String vmName, String vnetId, String gateway, String dns, String privateIP, String privateMac, String privateMask, String publicIP, String publicMac, String publicMask, int cpuCount, int cpuUtilization, long ramSize, String localPath, String vncPassword) { - if (s_logger.isInfoEnabled()) { + if (logger.isInfoEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("Start VM. name: " + vmName + ", vnet: " + vnetId + ", dns: " + dns); sb.append(", privateIP: " + privateIP + ", privateMac: " + privateMac + ", privateMask: " + privateMask); sb.append(", publicIP: " + publicIP + ", publicMac: " + publicMac + ", publicMask: " + publicMask); sb.append(", cpu count: " + cpuCount + ", cpuUtilization: " + cpuUtilization + ", ram : " + ramSize); sb.append(", localPath: " + localPath); - s_logger.info(sb.toString()); + logger.info(sb.toString()); } synchronized (this) { @@ -86,8 +87,7 @@ public class MockVmMgr implements VmMgr { @Override public String stopVM(String vmName, boolean force) { - if (s_logger.isInfoEnabled()) - s_logger.info("Stop VM. name: " + vmName); + logger.info("Stop VM. name: {}", vmName); synchronized (this) { MockVm vm = vms.get(vmName); @@ -102,8 +102,7 @@ public class MockVmMgr implements VmMgr { @Override public String rebootVM(String vmName) { - if (s_logger.isInfoEnabled()) - s_logger.info("Reboot VM. name: " + vmName); + logger.info("Reboot VM. name: {}", vmName); synchronized (this) { MockVm vm = vms.get(vmName); @@ -115,8 +114,7 @@ public class MockVmMgr implements VmMgr { @Override public boolean migrate(String vmName, String params) { - if (s_logger.isInfoEnabled()) - s_logger.info("Migrate VM. name: " + vmName); + logger.info("Migrate VM. name: {}", vmName); synchronized (this) { MockVm vm = vms.get(vmName); @@ -258,13 +256,13 @@ public class MockVmMgr implements VmMgr { vm = vms.get(vmName); if (vm == null) { if (ramSize > getHostFreeMemory()) { - s_logger.debug("host is out of memory"); + logger.debug("host is out of memory"); throw new CloudRuntimeException("Host is out of Memory"); } int vncPort = allocVncPort(); if (vncPort < 0) { - s_logger.debug("Unable to allocate VNC port"); + logger.debug("Unable to allocate VNC port"); throw new CloudRuntimeException("Unable to allocate vnc port"); } diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index cc0acfd18d3..c781c07c227 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -516,6 +516,7 @@ public class AgentProperties{ /** * The model of Watchdog timer to present to the Guest.
* For all models refer to the libvirt documentation.
+ * PLEASE NOTE: to disable the watchdogs definitions, use value: none * Data type: String.
* Default value: i6300esb */ @@ -803,12 +804,26 @@ public class AgentProperties{ */ public static final Property KEYSTORE_PASSPHRASE = new Property<>(KeyStoreUtils.KS_PASSPHRASE_PROPERTY, null, String.class); + /** + * Implicit host tags + * Data type: String.
+ * Default value: null + */ + public static final Property HOST_TAGS = new Property<>("host.tags", null, String.class); + + /** + * Timeout for SSL handshake in seconds + * Data type: Integer.
+ * Default value: null + */ + public static final Property SSL_HANDSHAKE_TIMEOUT = new Property<>("ssl.handshake.timeout", null, Integer.class); + public static class Property { private String name; private T defaultValue; private Class typeClass; - Property(String name, T value) { + public Property(String name, T value) { init(name, value); } diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java b/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java index 602aa1efcb0..b28018fcd94 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java @@ -22,7 +22,8 @@ import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.converters.IntegerConverter; import org.apache.commons.beanutils.converters.LongConverter; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; /** * This class provides a facility to read the agent's properties file and get @@ -31,7 +32,7 @@ import org.apache.log4j.Logger; */ public class AgentPropertiesFileHandler { - private static final Logger logger = Logger.getLogger(AgentPropertiesFileHandler.class); + protected static Logger LOGGER = LogManager.getLogger(AgentPropertiesFileHandler.class); /** * This method reads the property in the agent.properties file. @@ -47,7 +48,7 @@ public class AgentPropertiesFileHandler { File agentPropertiesFile = PropertiesUtil.findConfigFile(KeyStoreUtils.AGENT_PROPSFILE); if (agentPropertiesFile == null) { - logger.debug(String.format("File [%s] was not found, we will use default defined values. Property [%s]: [%s].", KeyStoreUtils.AGENT_PROPSFILE, name, defaultValue)); + LOGGER.debug("File [{}] was not found, we will use default defined values. Property [{}]: [{}].", KeyStoreUtils.AGENT_PROPSFILE, name, defaultValue); return defaultValue; } @@ -55,7 +56,7 @@ public class AgentPropertiesFileHandler { try { String configValue = PropertiesUtil.loadFromFile(agentPropertiesFile).getProperty(name); if (StringUtils.isBlank(configValue)) { - logger.debug(String.format("Property [%s] has empty or null value. Using default value [%s].", name, defaultValue)); + LOGGER.debug("Property [{}] has empty or null value. Using default value [{}].", name, defaultValue); return defaultValue; } @@ -67,11 +68,11 @@ public class AgentPropertiesFileHandler { ConvertUtils.register(new LongConverter(defaultValue), Long.class); } - logger.debug(String.format("Property [%s] was altered. Now using the value [%s].", name, configValue)); + LOGGER.debug("Property [{}] was altered. Now using the value [{}].", name, configValue); return (T)ConvertUtils.convert(configValue, property.getTypeClass()); } catch (IOException ex) { - logger.debug(String.format("Failed to get property [%s]. Using default value [%s].", name, defaultValue), ex); + LOGGER.debug("Failed to get property [{}]. Using default value [{}].", name, defaultValue, ex); } return defaultValue; diff --git a/agent/src/main/java/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java b/agent/src/main/java/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java index 5412c347012..ccd0d976e58 100644 --- a/agent/src/main/java/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java +++ b/agent/src/main/java/com/cloud/agent/resource/consoleproxy/ConsoleProxyResource.java @@ -34,7 +34,6 @@ import javax.naming.ConfigurationException; import com.cloud.agent.api.proxy.AllowConsoleAccessCommand; import org.apache.cloudstack.managed.context.ManagedContextRunnable; -import org.apache.log4j.Logger; import com.cloud.agent.Agent.ExitStatus; import com.cloud.agent.api.AgentControlAnswer; @@ -81,7 +80,6 @@ import com.google.gson.Gson; * */ public class ConsoleProxyResource extends ServerResourceBase implements ServerResource { - static final Logger s_logger = Logger.getLogger(ConsoleProxyResource.class); private final Properties properties = new Properties(); private Thread consoleProxyMain = null; @@ -101,7 +99,7 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe } else if (cmd instanceof WatchConsoleProxyLoadCommand) { return execute((WatchConsoleProxyLoadCommand)cmd); } else if (cmd instanceof ReadyCommand) { - s_logger.info("Receive ReadyCommand, response with ReadyAnswer"); + logger.info("Receive ReadyCommand, response with ReadyAnswer"); return new ReadyAnswer((ReadyCommand)cmd); } else if (cmd instanceof CheckHealthCommand) { return new CheckHealthAnswer((CheckHealthCommand)cmd, true); @@ -123,13 +121,13 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe return new Answer(cmd); } catch (SecurityException | NoSuchMethodException | ClassNotFoundException | InvocationTargetException | IllegalAccessException e) { String errorMsg = "Unable to add allowed session due to: " + e.getMessage(); - s_logger.error(errorMsg, e); + logger.error(errorMsg, e); return new Answer(cmd, false, errorMsg); } } private Answer execute(StartConsoleProxyAgentHttpHandlerCommand cmd) { - s_logger.info("Invoke launchConsoleProxy() in responding to StartConsoleProxyAgentHttpHandlerCommand"); + logger.info("Invoke launchConsoleProxy() in responding to StartConsoleProxyAgentHttpHandlerCommand"); launchConsoleProxy(cmd.getKeystoreBits(), cmd.getKeystorePassword(), cmd.getEncryptorPassword(), cmd.isSourceIpCheckEnabled()); return new Answer(cmd); } @@ -140,7 +138,7 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe { out.write("0"); } catch (IOException e) { - s_logger.warn("Unable to disable rp_filter"); + logger.warn("Unable to disable rp_filter"); } } @@ -177,12 +175,12 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe try { is.close(); } catch (final IOException e) { - s_logger.warn("Exception when closing , console proxy address : " + proxyManagementIp); + logger.warn("Exception when closing , console proxy address : {}", proxyManagementIp); success = false; } } } catch (final IOException e) { - s_logger.warn("Unable to open console proxy command port url, console proxy address : " + proxyManagementIp); + logger.warn("Unable to open console proxy command port url, console proxy address : {}", proxyManagementIp); success = false; } @@ -227,14 +225,14 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe if (eth1Ip != null) { params.put("private.network.device", "eth1"); } else { - s_logger.info("eth1ip parameter has not been configured, assuming that we are not inside a system vm"); + logger.info("eth1ip parameter has not been configured, assuming that we are not inside a system vm"); } String eth2ip = (String)params.get("eth2ip"); if (eth2ip != null) { params.put("public.network.device", "eth2"); } else { - s_logger.info("eth2ip parameter is not found, assuming that we are not inside a system vm"); + logger.info("eth2ip parameter is not found, assuming that we are not inside a system vm"); } super.configure(name, params); @@ -262,7 +260,7 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe } String internalDns1 = (String) params.get("internaldns1"); if (internalDns1 == null) { - s_logger.warn("No DNS entry found during configuration of ConsoleProxy"); + logger.warn("No DNS entry found during configuration of ConsoleProxy"); } else { addRouteToInternalIpOrCidr(localGateway, eth1Ip, eth1Mask, internalDns1); } @@ -280,20 +278,19 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe disableRpFilter(); } - if (s_logger.isInfoEnabled()) - s_logger.info("Receive proxyVmId in ConsoleProxyResource configuration as " + proxyVmId); + logger.info("Receive proxyVmId in ConsoleProxyResource configuration as {}", proxyVmId); return true; } private void addRouteToInternalIpOrCidr(String localgw, String eth1ip, String eth1mask, String destIpOrCidr) { - s_logger.debug("addRouteToInternalIp: localgw=" + localgw + ", eth1ip=" + eth1ip + ", eth1mask=" + eth1mask + ",destIp=" + destIpOrCidr); + logger.debug("addRouteToInternalIp: localgw={}, eth1ip={}, eth1mask={}, destIp={}", localgw, eth1ip, eth1mask, destIpOrCidr); if (destIpOrCidr == null) { - s_logger.debug("addRouteToInternalIp: destIp is null"); + logger.debug("addRouteToInternalIp: destIp is null"); return; } if (!NetUtils.isValidIp4(destIpOrCidr) && !NetUtils.isValidIp4Cidr(destIpOrCidr)) { - s_logger.warn(" destIp is not a valid ip address or cidr destIp=" + destIpOrCidr); + logger.warn(" destIp is not a valid ip address or cidr destIp={}", destIpOrCidr); return; } boolean inSameSubnet = false; @@ -301,27 +298,27 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe if (eth1ip != null && eth1mask != null) { inSameSubnet = NetUtils.sameSubnet(eth1ip, destIpOrCidr, eth1mask); } else { - s_logger.warn("addRouteToInternalIp: unable to determine same subnet: eth1ip=" + eth1ip + ", dest ip=" + destIpOrCidr + ", eth1mask=" + eth1mask); + logger.warn("addRouteToInternalIp: unable to determine same subnet: eth1ip={}, dest ip={}, eth1mask={}", eth1ip, destIpOrCidr, eth1mask); } } else { inSameSubnet = NetUtils.isNetworkAWithinNetworkB(destIpOrCidr, NetUtils.ipAndNetMaskToCidr(eth1ip, eth1mask)); } if (inSameSubnet) { - s_logger.debug("addRouteToInternalIp: dest ip " + destIpOrCidr + " is in the same subnet as eth1 ip " + eth1ip); + logger.debug("addRouteToInternalIp: dest ip {} is in the same subnet as eth1 ip {}", destIpOrCidr, eth1ip); return; } - Script command = new Script("/bin/bash", s_logger); + Script command = new Script("/bin/bash", logger); command.add("-c"); command.add("ip route delete " + destIpOrCidr); command.execute(); - command = new Script("/bin/bash", s_logger); + command = new Script("/bin/bash", logger); command.add("-c"); command.add("ip route add " + destIpOrCidr + " via " + localgw); String result = command.execute(); if (result != null) { - s_logger.warn("Error in configuring route to internal ip err=" + result); + logger.warn("Error in configuring route to internal ip err={}", result); } else { - s_logger.debug("addRouteToInternalIp: added route to internal ip=" + destIpOrCidr + " via " + localgw); + logger.debug("addRouteToInternalIp: added route to internal ip={} via {}", destIpOrCidr, localgw); } } @@ -332,36 +329,36 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe private void launchConsoleProxy(final byte[] ksBits, final String ksPassword, final String encryptorPassword, final Boolean isSourceIpCheckEnabled) { final Object resource = this; - s_logger.info("Building class loader for com.cloud.consoleproxy.ConsoleProxy"); + logger.info("Building class loader for com.cloud.consoleproxy.ConsoleProxy"); if (consoleProxyMain == null) { - s_logger.info("Running com.cloud.consoleproxy.ConsoleProxy with encryptor password=" + encryptorPassword); + logger.info("Running com.cloud.consoleproxy.ConsoleProxy with encryptor password={}", encryptorPassword); consoleProxyMain = new Thread(new ManagedContextRunnable() { @Override protected void runInContext() { try { Class consoleProxyClazz = Class.forName("com.cloud.consoleproxy.ConsoleProxy"); try { - s_logger.info("Invoke startWithContext()"); + logger.info("Invoke startWithContext()"); Method method = consoleProxyClazz.getMethod("startWithContext", Properties.class, Object.class, byte[].class, String.class, String.class, Boolean.class); method.invoke(null, properties, resource, ksBits, ksPassword, encryptorPassword, isSourceIpCheckEnabled); } catch (SecurityException e) { - s_logger.error("Unable to launch console proxy due to SecurityException", e); + logger.error("Unable to launch console proxy due to SecurityException", e); System.exit(ExitStatus.Error.value()); } catch (NoSuchMethodException e) { - s_logger.error("Unable to launch console proxy due to NoSuchMethodException", e); + logger.error("Unable to launch console proxy due to NoSuchMethodException", e); System.exit(ExitStatus.Error.value()); } catch (IllegalArgumentException e) { - s_logger.error("Unable to launch console proxy due to IllegalArgumentException", e); + logger.error("Unable to launch console proxy due to IllegalArgumentException", e); System.exit(ExitStatus.Error.value()); } catch (IllegalAccessException e) { - s_logger.error("Unable to launch console proxy due to IllegalAccessException", e); + logger.error("Unable to launch console proxy due to IllegalAccessException", e); System.exit(ExitStatus.Error.value()); } catch (InvocationTargetException e) { - s_logger.error("Unable to launch console proxy due to InvocationTargetException " + e.getTargetException().toString(), e); + logger.error("Unable to launch console proxy due to InvocationTargetException {}", e.getTargetException().toString(), e); System.exit(ExitStatus.Error.value()); } } catch (final ClassNotFoundException e) { - s_logger.error("Unable to launch console proxy due to ClassNotFoundException"); + logger.error("Unable to launch console proxy due to ClassNotFoundException"); System.exit(ExitStatus.Error.value()); } } @@ -369,7 +366,7 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe consoleProxyMain.setDaemon(true); consoleProxyMain.start(); } else { - s_logger.info("com.cloud.consoleproxy.ConsoleProxy is already running"); + logger.info("com.cloud.consoleproxy.ConsoleProxy is already running"); try { Class consoleProxyClazz = Class.forName("com.cloud.consoleproxy.ConsoleProxy"); @@ -378,22 +375,22 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe methodSetup = consoleProxyClazz.getMethod("setIsSourceIpCheckEnabled", Boolean.class); methodSetup.invoke(null, isSourceIpCheckEnabled); } catch (SecurityException e) { - s_logger.error("Unable to launch console proxy due to SecurityException", e); + logger.error("Unable to launch console proxy due to SecurityException", e); System.exit(ExitStatus.Error.value()); } catch (NoSuchMethodException e) { - s_logger.error("Unable to launch console proxy due to NoSuchMethodException", e); + logger.error("Unable to launch console proxy due to NoSuchMethodException", e); System.exit(ExitStatus.Error.value()); } catch (IllegalArgumentException e) { - s_logger.error("Unable to launch console proxy due to IllegalArgumentException", e); + logger.error("Unable to launch console proxy due to IllegalArgumentException", e); System.exit(ExitStatus.Error.value()); } catch (IllegalAccessException e) { - s_logger.error("Unable to launch console proxy due to IllegalAccessException", e); + logger.error("Unable to launch console proxy due to IllegalAccessException", e); System.exit(ExitStatus.Error.value()); } catch (InvocationTargetException e) { - s_logger.error("Unable to launch console proxy due to InvocationTargetException " + e.getTargetException().toString(), e); + logger.error("Unable to launch console proxy due to InvocationTargetException " + e.getTargetException().toString(), e); System.exit(ExitStatus.Error.value()); } catch (final ClassNotFoundException e) { - s_logger.error("Unable to launch console proxy due to ClassNotFoundException", e); + logger.error("Unable to launch console proxy due to ClassNotFoundException", e); System.exit(ExitStatus.Error.value()); } } @@ -420,10 +417,10 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe result.setTunnelUrl(authAnswer.getTunnelUrl()); result.setTunnelSession(authAnswer.getTunnelSession()); } else { - s_logger.error("Authentication failed for vm: " + vmId + " with sid: " + sid); + logger.error("Authentication failed for vm: {} with sid: {}", vmId, sid); } } catch (AgentControlChannelException e) { - s_logger.error("Unable to send out console access authentication request due to " + e.getMessage(), e); + logger.error("Unable to send out console access authentication request due to {}", e.getMessage(), e); } return new Gson().toJson(result); @@ -433,18 +430,15 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe ConsoleProxyLoadReportCommand cmd = new ConsoleProxyLoadReportCommand(proxyVmId, gsonLoadInfo); try { getAgentControl().postRequest(cmd); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Report proxy load info, proxy : " + proxyVmId + ", load: " + gsonLoadInfo); + logger.debug("Report proxy load info, proxy : {}, load: {}", proxyVmId, gsonLoadInfo); } catch (AgentControlChannelException e) { - s_logger.error("Unable to send out load info due to " + e.getMessage(), e); + logger.error("Unable to send out load info due to {}", e.getMessage(), e); } } public void ensureRoute(String address) { if (localGateway != null) { - if (s_logger.isDebugEnabled()) - s_logger.debug("Ensure route for " + address + " via " + localGateway); + logger.debug("Ensure route for {} via {}", address, localGateway); // this method won't be called in high frequency, serialize access // to script execution @@ -452,7 +446,7 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe try { addRouteToInternalIpOrCidr(localGateway, eth1Ip, eth1Mask, address); } catch (Throwable e) { - s_logger.warn("Unexpected exception while adding internal route to " + address, e); + logger.warn("Unexpected exception while adding internal route to {}", address, e); } } } diff --git a/agent/src/test/java/com/cloud/agent/AgentShellTest.java b/agent/src/test/java/com/cloud/agent/AgentShellTest.java index f7151779f58..6d9758cc3dc 100644 --- a/agent/src/test/java/com/cloud/agent/AgentShellTest.java +++ b/agent/src/test/java/com/cloud/agent/AgentShellTest.java @@ -350,4 +350,23 @@ public class AgentShellTest { Mockito.verify(agentShellSpy).setHosts(expected); } + + @Test + public void updateAndGetConnectedHost() { + String expected = "test"; + + AgentShell shell = new AgentShell(); + shell.setHosts("test"); + shell.getNextHost(); + shell.updateConnectedHost(); + + Assert.assertEquals(expected, shell.getConnectedHost()); + } + + @Test + public void testGetSslHandshakeTimeout() { + Integer expected = 1; + agentPropertiesFileHandlerMocked.when(() -> AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.SSL_HANDSHAKE_TIMEOUT))).thenReturn(expected); + Assert.assertEquals(expected, agentShellSpy.getSslHandshakeTimeout()); + } } diff --git a/agent/src/test/java/com/cloud/agent/AgentTest.java b/agent/src/test/java/com/cloud/agent/AgentTest.java new file mode 100644 index 00000000000..65dc030ebd7 --- /dev/null +++ b/agent/src/test/java/com/cloud/agent/AgentTest.java @@ -0,0 +1,257 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.agent; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.net.InetSocketAddress; + +import javax.naming.ConfigurationException; + +import org.apache.logging.log4j.Logger; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import com.cloud.resource.ServerResource; +import com.cloud.utils.backoff.impl.ConstantTimeBackoff; +import com.cloud.utils.nio.Link; +import com.cloud.utils.nio.NioConnection; + +@RunWith(MockitoJUnitRunner.class) +public class AgentTest { + Agent agent; + private AgentShell shell; + private ServerResource serverResource; + private Logger logger; + + @Before + public void setUp() throws ConfigurationException { + shell = mock(AgentShell.class); + serverResource = mock(ServerResource.class); + doReturn(true).when(serverResource).configure(any(), any()); + doReturn(1).when(shell).getWorkers(); + doReturn(1).when(shell).getPingRetries(); + agent = new Agent(shell, 1, serverResource); + logger = mock(Logger.class); + ReflectionTestUtils.setField(agent, "logger", logger); + } + + @Test + public void testGetLinkLogNullLinkReturnsEmptyString() { + Link link = null; + String result = agent.getLinkLog(link); + assertEquals("", result); + } + + @Test + public void testGetLinkLogLinkWithTraceEnabledReturnsLinkLogWithHashCode() { + Link link = mock(Link.class); + InetSocketAddress socketAddress = new InetSocketAddress("192.168.1.100", 1111); + when(link.getSocketAddress()).thenReturn(socketAddress); + when(logger.isTraceEnabled()).thenReturn(true); + + String result = agent.getLinkLog(link); + System.out.println(result); + assertTrue(result.startsWith(System.identityHashCode(link) + "-")); + assertTrue(result.contains("192.168.1.100")); + } + + @Test + public void testGetAgentNameWhenServerResourceIsNull() { + ReflectionTestUtils.setField(agent, "serverResource", null); + assertEquals("Agent", agent.getAgentName()); + } + + @Test + public void testGetAgentNameWhenAppendAgentNameIsTrue() { + when(serverResource.isAppendAgentNameToLogs()).thenReturn(true); + when(serverResource.getName()).thenReturn("TestAgent"); + + String agentName = agent.getAgentName(); + assertEquals("TestAgent", agentName); + } + + @Test + public void testGetAgentNameWhenAppendAgentNameIsFalse() { + when(serverResource.isAppendAgentNameToLogs()).thenReturn(false); + + String agentName = agent.getAgentName(); + assertEquals("Agent", agentName); + } + + @Test + public void testAgentInitialization() { + Runtime.getRuntime().removeShutdownHook(agent.shutdownThread); + when(shell.getPingRetries()).thenReturn(3); + when(shell.getWorkers()).thenReturn(5); + agent.setupShutdownHookAndInitExecutors(); + assertNotNull(agent.selfTaskExecutor); + assertNotNull(agent.outRequestHandler); + assertNotNull(agent.requestHandler); + } + + @Test + public void testAgentShutdownHookAdded() { + Runtime.getRuntime().removeShutdownHook(agent.shutdownThread); + agent.setupShutdownHookAndInitExecutors(); + verify(logger).trace("Adding shutdown hook"); + } + + @Test + public void testGetResourceGuidValidGuidAndResourceName() { + when(shell.getGuid()).thenReturn("12345"); + String result = agent.getResourceGuid(); + assertTrue(result.startsWith("12345-" + ServerResource.class.getSimpleName())); + } + + @Test + public void testGetZoneReturnsValidZone() { + when(shell.getZone()).thenReturn("ZoneA"); + String result = agent.getZone(); + assertEquals("ZoneA", result); + } + + @Test + public void testGetPodReturnsValidPod() { + when(shell.getPod()).thenReturn("PodA"); + String result = agent.getPod(); + assertEquals("PodA", result); + } + + @Test + public void testSetLinkAssignsLink() { + Link mockLink = mock(Link.class); + agent.setLink(mockLink); + assertEquals(mockLink, agent.link); + } + + @Test + public void testGetResourceReturnsServerResource() { + ServerResource mockResource = mock(ServerResource.class); + ReflectionTestUtils.setField(agent, "serverResource", mockResource); + ServerResource result = agent.getResource(); + assertSame(mockResource, result); + } + + @Test + public void testGetResourceName() { + String result = agent.getResourceName(); + assertTrue(result.startsWith(ServerResource.class.getSimpleName())); + } + + @Test + public void testUpdateLastPingResponseTimeUpdatesCurrentTime() { + long beforeUpdate = System.currentTimeMillis(); + agent.updateLastPingResponseTime(); + long updatedTime = agent.lastPingResponseTime.get(); + assertTrue(updatedTime >= beforeUpdate); + assertTrue(updatedTime <= System.currentTimeMillis()); + } + + @Test + public void testGetNextSequenceIncrementsSequence() { + long initialSequence = agent.getNextSequence(); + long nextSequence = agent.getNextSequence(); + assertEquals(initialSequence + 1, nextSequence); + long thirdSequence = agent.getNextSequence(); + assertEquals(nextSequence + 1, thirdSequence); + } + + @Test + public void testRegisterControlListenerAddsListener() { + IAgentControlListener listener = mock(IAgentControlListener.class); + agent.registerControlListener(listener); + assertTrue(agent.controlListeners.contains(listener)); + } + + @Test + public void testUnregisterControlListenerRemovesListener() { + IAgentControlListener listener = mock(IAgentControlListener.class); + agent.registerControlListener(listener); + assertTrue(agent.controlListeners.contains(listener)); + agent.unregisterControlListener(listener); + assertFalse(agent.controlListeners.contains(listener)); + } + + @Test + public void testCloseAndTerminateLinkLinkIsNullDoesNothing() { + agent.closeAndTerminateLink(null); + } + + @Test + public void testCloseAndTerminateLinkValidLinkCallsCloseAndTerminate() { + Link mockLink = mock(Link.class); + agent.closeAndTerminateLink(mockLink); + verify(mockLink).close(); + verify(mockLink).terminated(); + } + + @Test + public void testStopAndCleanupConnectionConnectionIsNullDoesNothing() { + agent.connection = null; + agent.stopAndCleanupConnection(false); + } + + @Test + public void testStopAndCleanupConnectionValidConnectionNoWaitStopsAndCleansUp() throws IOException { + NioConnection mockConnection = mock(NioConnection.class); + agent.connection = mockConnection; + agent.stopAndCleanupConnection(false); + verify(mockConnection).stop(); + verify(mockConnection).cleanUp(); + } + + @Test + public void testStopAndCleanupConnectionCleanupThrowsIOExceptionLogsWarning() throws IOException { + NioConnection mockConnection = mock(NioConnection.class); + agent.connection = mockConnection; + doThrow(new IOException("Cleanup failed")).when(mockConnection).cleanUp(); + agent.stopAndCleanupConnection(false); + verify(mockConnection).stop(); + verify(logger).warn(eq("Fail to clean up old connection. {}"), any(IOException.class)); + } + + @Test + public void testStopAndCleanupConnectionValidConnectionWaitForStopWaitsForStartupToStop() throws IOException { + NioConnection mockConnection = mock(NioConnection.class); + ConstantTimeBackoff mockBackoff = mock(ConstantTimeBackoff.class); + mockBackoff.setTimeToWait(0); + agent.connection = mockConnection; + when(shell.getBackoffAlgorithm()).thenReturn(mockBackoff); + when(mockConnection.isStartup()).thenReturn(true, true, false); + agent.stopAndCleanupConnection(true); + verify(mockConnection).stop(); + verify(mockConnection).cleanUp(); + verify(mockBackoff, times(3)).waitBeforeRetry(); + } +} diff --git a/agent/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/agent/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker deleted file mode 100644 index 1f0955d450f..00000000000 --- a/agent/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker +++ /dev/null @@ -1 +0,0 @@ -mock-maker-inline diff --git a/api/pom.xml b/api/pom.xml index 737f5768799..377b6e6e341 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT diff --git a/api/src/main/java/com/cloud/agent/api/Command.java b/api/src/main/java/com/cloud/agent/api/Command.java index c873139099c..eb979c0060b 100644 --- a/api/src/main/java/com/cloud/agent/api/Command.java +++ b/api/src/main/java/com/cloud/agent/api/Command.java @@ -20,6 +20,8 @@ import java.util.HashMap; import java.util.Map; import com.cloud.agent.api.LogLevel.Log4jLevel; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; /** * implemented by classes that extends the Command class. Command specifies @@ -27,6 +29,8 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; */ public abstract class Command { + protected transient Logger logger = LogManager.getLogger(getClass()); + public static enum OnError { Continue, Stop } diff --git a/api/src/main/java/com/cloud/agent/api/LogLevel.java b/api/src/main/java/com/cloud/agent/api/LogLevel.java index a8da272f39f..136cb6d7228 100644 --- a/api/src/main/java/com/cloud/agent/api/LogLevel.java +++ b/api/src/main/java/com/cloud/agent/api/LogLevel.java @@ -23,8 +23,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import org.apache.log4j.Level; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.Logger; /** */ @@ -41,7 +41,7 @@ public @interface LogLevel { } public boolean enabled(Logger logger) { - return _level != Level.OFF && logger.isEnabledFor(_level); + return _level != Level.OFF && logger.isEnabled(_level); } } diff --git a/api/src/main/java/com/cloud/agent/api/storage/OVFHelper.java b/api/src/main/java/com/cloud/agent/api/storage/OVFHelper.java index d4daf0e4270..6396e3deb72 100644 --- a/api/src/main/java/com/cloud/agent/api/storage/OVFHelper.java +++ b/api/src/main/java/com/cloud/agent/api/storage/OVFHelper.java @@ -39,7 +39,8 @@ import org.apache.cloudstack.utils.security.ParserUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -63,7 +64,7 @@ import com.cloud.utils.compression.CompressionUtil; import com.cloud.utils.exception.CloudRuntimeException; public class OVFHelper { - private static final Logger s_logger = Logger.getLogger(OVFHelper.class); + protected Logger logger = LogManager.getLogger(getClass()); private final OVFParser ovfParser; @@ -118,7 +119,7 @@ public class OVFHelper { boolean password = StringUtils.isNotBlank(passStr) && passStr.equalsIgnoreCase("true"); String label = ovfParser.getChildNodeValue(node, "Label"); String description = ovfParser.getChildNodeValue(node, "Description"); - s_logger.debug("Creating OVF property index " + index + (category == null ? "" : " for category " + category) + logger.debug("Creating OVF property index " + index + (category == null ? "" : " for category " + category) + " with key = " + key); return new OVFPropertyTO(key, type, value, qualifiers, userConfigurable, label, description, password, index, category); @@ -151,7 +152,7 @@ public class OVFHelper { if (child.getNodeName().equalsIgnoreCase("Category") || child.getNodeName().endsWith(":Category")) { lastCategoryFound = child.getTextContent(); - s_logger.info("Category found " + lastCategoryFound); + logger.info("Category found " + lastCategoryFound); } else if (child.getNodeName().equalsIgnoreCase("Property") || child.getNodeName().endsWith(":Property")) { OVFPropertyTO prop = createOVFPropertyFromNode(child, propertyIndex, lastCategoryFound); @@ -249,13 +250,13 @@ public class OVFHelper { int diskNumber = 0; for (OVFVirtualHardwareItemTO diskItem : diskHardwareItems) { if (StringUtils.isBlank(diskItem.getHostResource())) { - s_logger.error("Missing disk information for hardware item " + diskItem.getElementName() + " " + diskItem.getInstanceId()); + logger.error("Missing disk information for hardware item " + diskItem.getElementName() + " " + diskItem.getInstanceId()); continue; } String diskId = extractDiskIdFromDiskHostResource(diskItem.getHostResource()); OVFDisk diskDefinition = getDiskDefinitionFromDiskId(diskId, disks); if (diskDefinition == null) { - s_logger.error("Missing disk definition for disk ID " + diskId); + logger.error("Missing disk definition for disk ID " + diskId); } OVFFile fileDefinition = getFileDefinitionFromDiskDefinition(diskDefinition._fileRef, files); DatadiskTO datadiskTO = generateDiskTO(fileDefinition, diskDefinition, ovfParentPath, diskNumber, diskItem); @@ -277,7 +278,7 @@ public class OVFHelper { if (StringUtils.isNotBlank(path)) { File f = new File(path); if (!f.exists() || f.isDirectory()) { - s_logger.error("One of the attached disk or iso does not exists " + path); + logger.error("One of the attached disk or iso does not exists " + path); throw new InternalErrorException("One of the attached disk or iso as stated on OVF does not exists " + path); } } @@ -333,8 +334,8 @@ public class OVFHelper { od._controller = getControllerType(items, od._diskId); vd.add(od); } - if (s_logger.isTraceEnabled()) { - s_logger.trace(String.format("found %d disk definitions",vd.size())); + if (logger.isTraceEnabled()) { + logger.trace(String.format("found %d disk definitions",vd.size())); } return vd; } @@ -365,8 +366,8 @@ public class OVFHelper { vf.add(of); } } - if (s_logger.isTraceEnabled()) { - s_logger.trace(String.format("found %d file definitions in %s",vf.size(), ovfFile.getPath())); + if (logger.isTraceEnabled()) { + logger.trace(String.format("found %d file definitions in %s",vf.size(), ovfFile.getPath())); } return vf; } @@ -461,7 +462,7 @@ public class OVFHelper { Element disk = (Element)disks.item(i); String fileRef = ovfParser.getNodeAttribute(disk, "fileRef"); if (keepfile == null) { - s_logger.info("FATAL: OVA format error"); + logger.info("FATAL: OVA format error"); } else if (keepfile.equals(fileRef)) { keepdisk = ovfParser.getNodeAttribute(disk, "diskId"); } else { @@ -505,7 +506,7 @@ public class OVFHelper { outfile.write(writer.toString()); outfile.close(); } catch (IOException | TransformerException e) { - s_logger.info("Unexpected exception caught while rewriting OVF:" + e.getMessage(), e); + logger.info("Unexpected exception caught while rewriting OVF:" + e.getMessage(), e); throw new CloudRuntimeException(e); } } @@ -521,8 +522,8 @@ public class OVFHelper { public List getNetPrerequisitesFromDocument(Document doc) throws InternalErrorException { if (doc == null) { - if (s_logger.isTraceEnabled()) { - s_logger.trace("no document to parse; returning no prerequisite networks"); + if (logger.isTraceEnabled()) { + logger.trace("no document to parse; returning no prerequisite networks"); } return Collections.emptyList(); } @@ -539,8 +540,8 @@ public class OVFHelper { private void matchNicsToNets(Map nets, Node systemElement) { final DocumentTraversal traversal = (DocumentTraversal) systemElement; final NodeIterator iterator = traversal.createNodeIterator(systemElement, NodeFilter.SHOW_ELEMENT, null, true); - if (s_logger.isTraceEnabled()) { - s_logger.trace(String.format("starting out with %d network-prerequisites, parsing hardware",nets.size())); + if (logger.isTraceEnabled()) { + logger.trace(String.format("starting out with %d network-prerequisites, parsing hardware",nets.size())); } int nicCount = 0; for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) { @@ -549,8 +550,8 @@ public class OVFHelper { nicCount++; String name = e.getTextContent(); // should be in our nets if(nets.get(name) == null) { - if(s_logger.isInfoEnabled()) { - s_logger.info(String.format("found a nic definition without a network definition byname %s, adding it to the list.", name)); + if(logger.isInfoEnabled()) { + logger.info(String.format("found a nic definition without a network definition byname %s, adding it to the list.", name)); } nets.put(name, new OVFNetworkTO()); } @@ -560,8 +561,8 @@ public class OVFHelper { } } } - if (s_logger.isTraceEnabled()) { - s_logger.trace(String.format("ending up with %d network-prerequisites, parsed %d nics", nets.size(), nicCount)); + if (logger.isTraceEnabled()) { + logger.trace(String.format("ending up with %d network-prerequisites, parsed %d nics", nets.size(), nicCount)); } } @@ -584,7 +585,7 @@ public class OVFHelper { int addressOnParent = Integer.parseInt(addressOnParentStr); nic.setAddressOnParent(addressOnParent); } catch (NumberFormatException e) { - s_logger.warn("Encountered element of type \"AddressOnParent\", that could not be parse to an integer number: " + addressOnParentStr); + logger.warn("Encountered element of type \"AddressOnParent\", that could not be parse to an integer number: " + addressOnParentStr); } boolean automaticAllocation = StringUtils.isNotBlank(automaticAllocationStr) && Boolean.parseBoolean(automaticAllocationStr); @@ -596,7 +597,7 @@ public class OVFHelper { int instanceId = Integer.parseInt(instanceIdStr); nic.setInstanceID(instanceId); } catch (NumberFormatException e) { - s_logger.warn("Encountered element of type \"InstanceID\", that could not be parse to an integer number: " + instanceIdStr); + logger.warn("Encountered element of type \"InstanceID\", that could not be parse to an integer number: " + instanceIdStr); } nic.setResourceSubType(resourceSubType); @@ -608,7 +609,7 @@ public class OVFHelper { NodeList systemElements = ovfParser.getElementsFromOVFDocument(doc, "VirtualSystem"); if (systemElements.getLength() != 1) { String msg = "found " + systemElements.getLength() + " system definitions in OVA, can only handle exactly one."; - s_logger.warn(msg); + logger.warn(msg); throw new InternalErrorException(msg); } } @@ -629,8 +630,8 @@ public class OVFHelper { nets.put(networkName,network); } - if (s_logger.isTraceEnabled()) { - s_logger.trace(String.format("found %d networks in template", nets.size())); + if (logger.isTraceEnabled()) { + logger.trace(String.format("found %d networks in template", nets.size())); } return nets; } @@ -770,7 +771,7 @@ public class OVFHelper { try { return Long.parseLong(value); } catch (NumberFormatException e) { - s_logger.debug("Could not parse the value: " + value + ", ignoring it"); + logger.debug("Could not parse the value: " + value + ", ignoring it"); } } return null; @@ -781,7 +782,7 @@ public class OVFHelper { try { return Integer.parseInt(value); } catch (NumberFormatException e) { - s_logger.debug("Could not parse the value: " + value + ", ignoring it"); + logger.debug("Could not parse the value: " + value + ", ignoring it"); } } return null; @@ -819,7 +820,7 @@ public class OVFHelper { try { compressedLicense = compressOVFEula(eulaLicense); } catch (IOException e) { - s_logger.error("Could not compress the license for info " + eulaInfo); + logger.error("Could not compress the license for info " + eulaInfo); continue; } OVFEulaSectionTO eula = new OVFEulaSectionTO(eulaInfo, compressedLicense, eulaIndex); diff --git a/api/src/main/java/com/cloud/agent/api/storage/OVFParser.java b/api/src/main/java/com/cloud/agent/api/storage/OVFParser.java index b66fbe418d7..38f478d63cf 100644 --- a/api/src/main/java/com/cloud/agent/api/storage/OVFParser.java +++ b/api/src/main/java/com/cloud/agent/api/storage/OVFParser.java @@ -27,7 +27,8 @@ import javax.xml.parsers.ParserConfigurationException; import org.apache.cloudstack.utils.security.ParserUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -36,7 +37,7 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class OVFParser { - private static final Logger s_logger = Logger.getLogger(OVFParser.class); + protected Logger logger = LogManager.getLogger(getClass()); private static final String DEFAULT_OVF_SCHEMA = "http://schemas.dmtf.org/ovf/envelope/1"; private static final String VMW_SCHEMA = "http://www.vmware.com/schema/ovf"; @@ -53,7 +54,7 @@ public class OVFParser { documentBuilderFactory.setNamespaceAware(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { - s_logger.error("Cannot start the OVF parser: " + e.getMessage(), e); + logger.error("Cannot start the OVF parser: " + e.getMessage(), e); } } @@ -69,7 +70,7 @@ public class OVFParser { try { return documentBuilder.parse(new File(ovfFilePath)); } catch (SAXException | IOException e) { - s_logger.error("Error parsing " + ovfFilePath + " " + e.getMessage(), e); + logger.error("Error parsing " + ovfFilePath + " " + e.getMessage(), e); return null; } } diff --git a/api/src/main/java/com/cloud/agent/api/to/BucketTO.java b/api/src/main/java/com/cloud/agent/api/to/BucketTO.java new file mode 100644 index 00000000000..f7e4bfea80f --- /dev/null +++ b/api/src/main/java/com/cloud/agent/api/to/BucketTO.java @@ -0,0 +1,50 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.agent.api.to; + +import org.apache.cloudstack.storage.object.Bucket; + +public final class BucketTO { + + private String name; + + private String accessKey; + + private String secretKey; + + public BucketTO(Bucket bucket) { + this.name = bucket.getName(); + this.accessKey = bucket.getAccessKey(); + this.secretKey = bucket.getSecretKey(); + } + + public BucketTO(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public String getAccessKey() { + return this.accessKey; + } + + public String getSecretKey() { + return this.secretKey; + } +} diff --git a/api/src/main/java/com/cloud/agent/api/to/FirewallRuleTO.java b/api/src/main/java/com/cloud/agent/api/to/FirewallRuleTO.java index d08884d1cbe..25c75001a3c 100644 --- a/api/src/main/java/com/cloud/agent/api/to/FirewallRuleTO.java +++ b/api/src/main/java/com/cloud/agent/api/to/FirewallRuleTO.java @@ -155,9 +155,7 @@ public class FirewallRuleTO implements InternalIdentity { rule.getIcmpType(), rule.getIcmpCode()); this.trafficType = trafficType; - if (FirewallRule.Purpose.Ipv6Firewall.equals(purpose)) { - this.destCidrList = rule.getDestinationCidrList(); - } + this.destCidrList = rule.getDestinationCidrList(); } public FirewallRuleTO(FirewallRule rule, String srcVlanTag, String srcIp, FirewallRule.Purpose purpose, FirewallRule.TrafficType trafficType, diff --git a/api/src/main/java/com/cloud/agent/api/to/LoadBalancerTO.java b/api/src/main/java/com/cloud/agent/api/to/LoadBalancerTO.java index 966d24886fe..f395f26aeed 100644 --- a/api/src/main/java/com/cloud/agent/api/to/LoadBalancerTO.java +++ b/api/src/main/java/com/cloud/agent/api/to/LoadBalancerTO.java @@ -374,13 +374,15 @@ public class LoadBalancerTO { public static class CounterTO implements Serializable { private static final long serialVersionUID = 2L; private final Long id; + private final String uuid; private final String name; private final Counter.Source source; private final String value; private final String provider; - public CounterTO(Long id, String name, Counter.Source source, String value, String provider) { + public CounterTO(Long id, String uuid, String name, Counter.Source source, String value, String provider) { this.id = id; + this.uuid = uuid; this.name = name; this.source = source; this.value = value; @@ -391,6 +393,10 @@ public class LoadBalancerTO { return id; } + public String getUuid() { + return uuid; + } + public String getName() { return name; } @@ -411,12 +417,14 @@ public class LoadBalancerTO { public static class ConditionTO implements Serializable { private static final long serialVersionUID = 2L; private final Long id; + private final String uuid; private final long threshold; private final Condition.Operator relationalOperator; private final CounterTO counter; - public ConditionTO(Long id, long threshold, Condition.Operator relationalOperator, CounterTO counter) { + public ConditionTO(Long id, String uuid, long threshold, Condition.Operator relationalOperator, CounterTO counter) { this.id = id; + this.uuid = uuid; this.threshold = threshold; this.relationalOperator = relationalOperator; this.counter = counter; @@ -426,6 +434,10 @@ public class LoadBalancerTO { return id; } + public String getUuid() { + return uuid; + } + public long getThreshold() { return threshold; } @@ -442,6 +454,7 @@ public class LoadBalancerTO { public static class AutoScalePolicyTO implements Serializable { private static final long serialVersionUID = 2L; private final long id; + private final String uuid; private final int duration; private final int quietTime; private final Date lastQuietTime; @@ -449,8 +462,9 @@ public class LoadBalancerTO { boolean revoked; private final List conditions; - public AutoScalePolicyTO(long id, int duration, int quietTime, Date lastQuietTime, AutoScalePolicy.Action action, List conditions, boolean revoked) { + public AutoScalePolicyTO(long id, String uuid, int duration, int quietTime, Date lastQuietTime, AutoScalePolicy.Action action, List conditions, boolean revoked) { this.id = id; + this.uuid = uuid; this.duration = duration; this.quietTime = quietTime; this.lastQuietTime = lastQuietTime; @@ -463,6 +477,10 @@ public class LoadBalancerTO { return id; } + public String getUuid() { + return uuid; + } + public int getDuration() { return duration; } diff --git a/api/src/main/java/com/cloud/agent/api/to/NfsTO.java b/api/src/main/java/com/cloud/agent/api/to/NfsTO.java index 0f6511e8311..eeddbf649a7 100644 --- a/api/src/main/java/com/cloud/agent/api/to/NfsTO.java +++ b/api/src/main/java/com/cloud/agent/api/to/NfsTO.java @@ -17,6 +17,7 @@ package com.cloud.agent.api.to; import com.cloud.storage.DataStoreRole; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public class NfsTO implements DataStoreTO { @@ -41,6 +42,13 @@ public class NfsTO implements DataStoreTO { } + @Override + public String toString() { + return String.format("NfsTO %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "uuid", "_url", "_role", "nfsVersion")); + } + @Override public String getUrl() { return _url; diff --git a/api/src/main/java/com/cloud/agent/api/to/NicTO.java b/api/src/main/java/com/cloud/agent/api/to/NicTO.java index 3a616170d7e..573363c04fb 100644 --- a/api/src/main/java/com/cloud/agent/api/to/NicTO.java +++ b/api/src/main/java/com/cloud/agent/api/to/NicTO.java @@ -32,6 +32,9 @@ public class NicTO extends NetworkTO { Map details; boolean dpdkEnabled; Integer mtu; + Long networkId; + + String networkSegmentName; public NicTO() { super(); @@ -127,4 +130,20 @@ public class NicTO extends NetworkTO { public void setMtu(Integer mtu) { this.mtu = mtu; } + + public Long getNetworkId() { + return networkId; + } + + public void setNetworkId(Long networkId) { + this.networkId = networkId; + } + + public String getNetworkSegmentName() { + return networkSegmentName; + } + + public void setNetworkSegmentName(String networkSegmentName) { + this.networkSegmentName = networkSegmentName; + } } diff --git a/api/src/main/java/com/cloud/agent/api/to/S3TO.java b/api/src/main/java/com/cloud/agent/api/to/S3TO.java index 233238cf793..936f8168b1e 100644 --- a/api/src/main/java/com/cloud/agent/api/to/S3TO.java +++ b/api/src/main/java/com/cloud/agent/api/to/S3TO.java @@ -22,6 +22,7 @@ import com.cloud.agent.api.LogLevel; import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.storage.DataStoreRole; import com.cloud.utils.storage.S3.ClientOptions; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public final class S3TO implements ClientOptions, DataStoreTO { @@ -68,6 +69,13 @@ public final class S3TO implements ClientOptions, DataStoreTO { } + @Override + public String toString() { + return String.format("S3TO %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "bucketName")); + } + public Long getId() { return this.id; } diff --git a/api/src/main/java/com/cloud/agent/api/to/StorageFilerTO.java b/api/src/main/java/com/cloud/agent/api/to/StorageFilerTO.java index e361e7a141f..cbdb7922eb4 100644 --- a/api/src/main/java/com/cloud/agent/api/to/StorageFilerTO.java +++ b/api/src/main/java/com/cloud/agent/api/to/StorageFilerTO.java @@ -19,6 +19,7 @@ package com.cloud.agent.api.to; import com.cloud.agent.api.LogLevel; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StoragePool; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public class StorageFilerTO { long id; @@ -73,6 +74,6 @@ public class StorageFilerTO { @Override public String toString() { - return new StringBuilder("Pool[").append(id).append("|").append(host).append(":").append(port).append("|").append(path).append("]").toString(); + return String.format("Pool %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "uuid", "host", "port", "path")); } } diff --git a/api/src/main/java/com/cloud/agent/api/to/SwiftTO.java b/api/src/main/java/com/cloud/agent/api/to/SwiftTO.java index b89dfea40e0..14038566fbd 100644 --- a/api/src/main/java/com/cloud/agent/api/to/SwiftTO.java +++ b/api/src/main/java/com/cloud/agent/api/to/SwiftTO.java @@ -18,6 +18,7 @@ package com.cloud.agent.api.to; import com.cloud.storage.DataStoreRole; import com.cloud.utils.SwiftUtil; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public class SwiftTO implements DataStoreTO, SwiftUtil.SwiftClientCfg { Long id; @@ -41,6 +42,13 @@ public class SwiftTO implements DataStoreTO, SwiftUtil.SwiftClientCfg { this.storagePolicy = storagePolicy; } + @Override + public String toString() { + return String.format("SwiftTO %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "account", "userName")); + } + public Long getId() { return id; } diff --git a/api/src/main/java/com/cloud/agent/api/to/VirtualMachineTO.java b/api/src/main/java/com/cloud/agent/api/to/VirtualMachineTO.java index db6cba77548..6f24b1cd6ca 100644 --- a/api/src/main/java/com/cloud/agent/api/to/VirtualMachineTO.java +++ b/api/src/main/java/com/cloud/agent/api/to/VirtualMachineTO.java @@ -82,7 +82,10 @@ public class VirtualMachineTO { Map guestOsDetails = new HashMap(); Map extraConfig = new HashMap<>(); + Map networkIdToNetworkNameMap = new HashMap<>(); DeployAsIsInfoTO deployAsIsInfo; + String metadataManufacturer; + String metadataProductName; public VirtualMachineTO(long id, String instanceName, VirtualMachine.Type type, int cpus, Integer speed, long minRam, long maxRam, BootloaderType bootloader, String os, boolean enableHA, boolean limitCpuUse, String vncPassword) { @@ -392,6 +395,14 @@ public class VirtualMachineTO { return extraConfig; } + public Map getNetworkIdToNetworkNameMap() { + return networkIdToNetworkNameMap; + } + + public void setNetworkIdToNetworkNameMap(Map networkIdToNetworkNameMap) { + this.networkIdToNetworkNameMap = networkIdToNetworkNameMap; + } + public String getBootType() { return bootType; } @@ -420,6 +431,22 @@ public class VirtualMachineTO { this.deployAsIsInfo = deployAsIsInfo; } + public String getMetadataManufacturer() { + return metadataManufacturer; + } + + public void setMetadataManufacturer(String metadataManufacturer) { + this.metadataManufacturer = metadataManufacturer; + } + + public String getMetadataProductName() { + return metadataProductName; + } + + public void setMetadataProductName(String metadataProductName) { + this.metadataProductName = metadataProductName; + } + @Override public String toString() { return String.format("VM {id: \"%s\", name: \"%s\", uuid: \"%s\", type: \"%s\"}", id, name, uuid, type); diff --git a/api/src/main/java/com/cloud/bgp/ASNumber.java b/api/src/main/java/com/cloud/bgp/ASNumber.java new file mode 100644 index 00000000000..b0e5394df75 --- /dev/null +++ b/api/src/main/java/com/cloud/bgp/ASNumber.java @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.bgp; + +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +import java.util.Date; + +public interface ASNumber extends InfrastructureEntity, InternalIdentity, Identity { + + Long getAccountId(); + Long getDomainId(); + long getAsNumber(); + long getAsNumberRangeId(); + long getDataCenterId(); + Date getAllocatedTime(); + boolean isAllocated(); + Long getNetworkId(); + Long getVpcId(); + Date getCreated(); + Date getRemoved(); +} diff --git a/api/src/main/java/com/cloud/bgp/ASNumberRange.java b/api/src/main/java/com/cloud/bgp/ASNumberRange.java new file mode 100644 index 00000000000..ae877ee60db --- /dev/null +++ b/api/src/main/java/com/cloud/bgp/ASNumberRange.java @@ -0,0 +1,31 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.bgp; + +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +import java.util.Date; + +public interface ASNumberRange extends InfrastructureEntity, InternalIdentity, Identity { + + long getStartASNumber(); + long getEndASNumber(); + long getDataCenterId(); + Date getCreated(); +} diff --git a/api/src/main/java/com/cloud/bgp/BGPService.java b/api/src/main/java/com/cloud/bgp/BGPService.java new file mode 100644 index 00000000000..61d149f2847 --- /dev/null +++ b/api/src/main/java/com/cloud/bgp/BGPService.java @@ -0,0 +1,44 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.bgp; + +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.vpc.Vpc; +import com.cloud.utils.Pair; +import org.apache.cloudstack.api.command.user.bgp.ListASNumbersCmd; +import org.apache.cloudstack.network.BgpPeer; + +import java.util.List; + +public interface BGPService { + + ASNumberRange createASNumberRange(long zoneId, long startASNumber, long endASNumber); + List listASNumberRanges(Long zoneId); + Pair, Integer> listASNumbers(ListASNumbersCmd cmd); + boolean allocateASNumber(long zoneId, Long asNumber, Long networkId, Long vpcId); + Pair releaseASNumber(long zoneId, long asNumber, boolean isReleaseNetworkDestroy); + boolean deleteASRange(long id); + + boolean applyBgpPeers(Network network, boolean continueOnError) throws ResourceUnavailableException; + + boolean applyBgpPeers(Vpc vpc, boolean continueOnError) throws ResourceUnavailableException; + + List getBgpPeersForNetwork(Network network); + + List getBgpPeersForVpc(Vpc vpc); +} diff --git a/api/src/main/java/com/cloud/capacity/Capacity.java b/api/src/main/java/com/cloud/capacity/Capacity.java index 684490a605c..a4e2c2a7f05 100644 --- a/api/src/main/java/com/cloud/capacity/Capacity.java +++ b/api/src/main/java/com/cloud/capacity/Capacity.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.capacity; +import java.util.List; + import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; @@ -35,6 +37,11 @@ public interface Capacity extends InternalIdentity, Identity { public static final short CAPACITY_TYPE_CPU_CORE = 90; + public static final List STORAGE_CAPACITY_TYPES = List.of(CAPACITY_TYPE_STORAGE, + CAPACITY_TYPE_STORAGE_ALLOCATED, + CAPACITY_TYPE_SECONDARY_STORAGE, + CAPACITY_TYPE_LOCAL_STORAGE); + public Long getHostOrPoolId(); public Long getDataCenterId(); @@ -54,4 +61,6 @@ public interface Capacity extends InternalIdentity, Identity { public Float getUsedPercentage(); public Long getAllocatedCapacity(); + + public String getTag(); } diff --git a/api/src/main/java/com/cloud/configuration/Resource.java b/api/src/main/java/com/cloud/configuration/Resource.java index 32db2fcafea..bf8fca9d905 100644 --- a/api/src/main/java/com/cloud/configuration/Resource.java +++ b/api/src/main/java/com/cloud/configuration/Resource.java @@ -85,5 +85,6 @@ public interface Resource { long getOwnerId(); ResourceOwnerType getResourceOwnerType(); + String getTag(); } diff --git a/api/src/main/java/com/cloud/cpu/CPU.java b/api/src/main/java/com/cloud/cpu/CPU.java new file mode 100644 index 00000000000..3016e542db6 --- /dev/null +++ b/api/src/main/java/com/cloud/cpu/CPU.java @@ -0,0 +1,70 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.cpu; + +import org.apache.commons.lang3.StringUtils; + +public class CPU { + public enum CPUArch { + x86("i686", 32), + amd64("x86_64", 64), + arm64("aarch64", 64); + + private final String type; + private final int bits; + + CPUArch(String type, int bits) { + this.type = type; + this.bits = bits; + } + + public static CPUArch getDefault() { + return amd64; + } + + public String getType() { + return type; + } + + public int getBits() { + return bits; + } + + public static CPUArch fromType(String type) { + if (StringUtils.isBlank(type)) { + return getDefault(); + } + for (CPUArch arch : values()) { + if (arch.type.equals(type)) { + return arch; + } + } + throw new IllegalArgumentException("Unsupported arch type: " + type); + } + + public static String getTypesAsCSV() { + StringBuilder sb = new StringBuilder(); + for (CPUArch arch : values()) { + sb.append(arch.getType()).append(","); + } + if (sb.length() > 0) { + sb.setLength(sb.length() - 1); + } + return sb.toString(); + } + } +} diff --git a/api/src/main/java/com/cloud/dc/DedicatedResources.java b/api/src/main/java/com/cloud/dc/DedicatedResources.java index 63188ca0b0e..23e6cc88a1e 100644 --- a/api/src/main/java/com/cloud/dc/DedicatedResources.java +++ b/api/src/main/java/com/cloud/dc/DedicatedResources.java @@ -21,6 +21,10 @@ import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; public interface DedicatedResources extends InfrastructureEntity, InternalIdentity, Identity { + enum Type { + Zone, Pod, Cluster, Host + } + @Override long getId(); diff --git a/api/src/main/java/com/cloud/deploy/DeploymentClusterPlanner.java b/api/src/main/java/com/cloud/deploy/DeploymentClusterPlanner.java index a668b79187d..2697311d2b9 100644 --- a/api/src/main/java/com/cloud/deploy/DeploymentClusterPlanner.java +++ b/api/src/main/java/com/cloud/deploy/DeploymentClusterPlanner.java @@ -57,6 +57,17 @@ public interface DeploymentClusterPlanner extends DeploymentPlanner { false, ConfigKey.Scope.Global); + static final ConfigKey VmAllocationAlgorithm = new ConfigKey<>( + String.class, + "vm.allocation.algorithm", + "Advanced", + "random", + "Order in which hosts within a cluster will be considered for VM/volume allocation. The value can be 'random', 'firstfit', 'userdispersing', 'userconcentratedpod_random', 'userconcentratedpod_firstfit', or 'firstfitleastconsumed'.", + true, + ConfigKey.Scope.Global, null, null, null, null, null, + ConfigKey.Kind.Select, + "random,firstfit,userdispersing,userconcentratedpod_random,userconcentratedpod_firstfit,firstfitleastconsumed"); + /** * This is called to determine list of possible clusters where a virtual * machine can be deployed. diff --git a/api/src/main/java/com/cloud/deploy/DeploymentPlanner.java b/api/src/main/java/com/cloud/deploy/DeploymentPlanner.java index e9f706ac1ce..354f9cfaac5 100644 --- a/api/src/main/java/com/cloud/deploy/DeploymentPlanner.java +++ b/api/src/main/java/com/cloud/deploy/DeploymentPlanner.java @@ -21,8 +21,12 @@ import java.util.Collection; import java.util.HashSet; import java.util.Set; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; + import com.cloud.dc.DataCenter; import com.cloud.dc.Pod; +import com.cloud.exception.CloudException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientServerCapacityException; import com.cloud.exception.ResourceUnavailableException; @@ -75,7 +79,7 @@ public interface DeploymentPlanner extends Adapter { public static class ExcludeList implements Serializable { private static final long serialVersionUID = -482175549460148301L; - + protected static Logger LOGGER = LogManager.getLogger(ExcludeList.class); private Set _dcIds; private Set _podIds; private Set _clusterIds; @@ -104,13 +108,26 @@ public interface DeploymentPlanner extends Adapter { } } + private void logAvoid(Class scope, CloudException e) { + Long id = null; + if (e instanceof InsufficientCapacityException) { + id = ((InsufficientCapacityException) e).getId(); + } else if (e instanceof ResourceUnavailableException) { + id = ((ResourceUnavailableException) e).getResourceId(); + } else { + LOGGER.debug("Failed to log avoided component due to unexpected exception type [{}].", e.getMessage()); + return; + } + LOGGER.debug("Adding {} [{}] to the avoid set due to [{}].", scope.getSimpleName(), id, e.getMessage()); + } + public boolean add(InsufficientCapacityException e) { Class scope = e.getScope(); if (scope == null) { return false; } - + logAvoid(scope, e); if (Host.class.isAssignableFrom(scope)) { addHost(e.getId()); } else if (Pod.class.isAssignableFrom(scope)) { @@ -128,13 +145,14 @@ public interface DeploymentPlanner extends Adapter { return true; } + public boolean add(ResourceUnavailableException e) { Class scope = e.getScope(); if (scope == null) { return false; } - + logAvoid(scope, e); if (Host.class.isAssignableFrom(scope)) { addHost(e.getResourceId()); } else if (Pod.class.isAssignableFrom(scope)) { diff --git a/api/src/main/java/com/cloud/event/EventTypes.java b/api/src/main/java/com/cloud/event/EventTypes.java index 496d9f5b689..81ed185dae5 100644 --- a/api/src/main/java/com/cloud/event/EventTypes.java +++ b/api/src/main/java/com/cloud/event/EventTypes.java @@ -28,8 +28,12 @@ import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.config.Configuration; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; import org.apache.cloudstack.ha.HAConfig; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.Ipv4GuestSubnetNetworkMap; import org.apache.cloudstack.quota.QuotaTariff; +import org.apache.cloudstack.storage.sharedfs.SharedFS; import org.apache.cloudstack.storage.object.Bucket; import org.apache.cloudstack.storage.object.ObjectStore; import org.apache.cloudstack.usage.Usage; @@ -242,6 +246,8 @@ public class EventTypes { public static final String EVENT_ROLE_UPDATE = "ROLE.UPDATE"; public static final String EVENT_ROLE_DELETE = "ROLE.DELETE"; public static final String EVENT_ROLE_IMPORT = "ROLE.IMPORT"; + public static final String EVENT_ROLE_ENABLE = "ROLE.ENABLE"; + public static final String EVENT_ROLE_DISABLE = "ROLE.DISABLE"; public static final String EVENT_ROLE_PERMISSION_CREATE = "ROLE.PERMISSION.CREATE"; public static final String EVENT_ROLE_PERMISSION_UPDATE = "ROLE.PERMISSION.UPDATE"; public static final String EVENT_ROLE_PERMISSION_DELETE = "ROLE.PERMISSION.DELETE"; @@ -286,6 +292,7 @@ public class EventTypes { //register for user API and secret keys public static final String EVENT_REGISTER_FOR_SECRET_API_KEY = "REGISTER.USER.KEY"; + public static final String API_KEY_ACCESS_UPDATE = "API.KEY.ACCESS.UPDATE"; // Template Events public static final String EVENT_TEMPLATE_CREATE = "TEMPLATE.CREATE"; @@ -333,6 +340,7 @@ public class EventTypes { public static final String EVENT_SNAPSHOT_OFF_PRIMARY = "SNAPSHOT.OFF_PRIMARY"; public static final String EVENT_SNAPSHOT_DELETE = "SNAPSHOT.DELETE"; public static final String EVENT_SNAPSHOT_REVERT = "SNAPSHOT.REVERT"; + public static final String EVENT_SNAPSHOT_EXTRACT = "SNAPSHOT.EXTRACT"; public static final String EVENT_SNAPSHOT_POLICY_CREATE = "SNAPSHOTPOLICY.CREATE"; public static final String EVENT_SNAPSHOT_POLICY_UPDATE = "SNAPSHOTPOLICY.UPDATE"; public static final String EVENT_SNAPSHOT_POLICY_DELETE = "SNAPSHOTPOLICY.DELETE"; @@ -390,6 +398,11 @@ public class EventTypes { public static final String EVENT_VLAN_IP_RANGE_RELEASE = "VLAN.IP.RANGE.RELEASE"; public static final String EVENT_VLAN_IP_RANGE_UPDATE = "VLAN.IP.RANGE.UPDATE"; + // AS Number + public static final String EVENT_AS_RANGE_CREATE = "AS.RANGE.CREATE"; + public static final String EVENT_AS_RANGE_DELETE = "AS.RANGE.DELETE"; + public static final String EVENT_AS_NUMBER_RELEASE = "AS.NUMBER.RELEASE"; + public static final String EVENT_MANAGEMENT_IP_RANGE_CREATE = "MANAGEMENT.IP.RANGE.CREATE"; public static final String EVENT_MANAGEMENT_IP_RANGE_DELETE = "MANAGEMENT.IP.RANGE.DELETE"; public static final String EVENT_MANAGEMENT_IP_RANGE_UPDATE = "MANAGEMENT.IP.RANGE.UPDATE"; @@ -448,6 +461,7 @@ public class EventTypes { public static final String EVENT_MAINTENANCE_PREPARE_PRIMARY_STORAGE = "MAINT.PREPARE.PS"; // Primary storage pool + public static final String EVENT_UPDATE_PRIMARY_STORAGE = "UPDATE.PS"; public static final String EVENT_ENABLE_PRIMARY_STORAGE = "ENABLE.PS"; public static final String EVENT_DISABLE_PRIMARY_STORAGE = "DISABLE.PS"; public static final String EVENT_SYNC_STORAGE_POOL = "SYNC.STORAGE.POOL"; @@ -722,6 +736,8 @@ public class EventTypes { // SystemVM public static final String EVENT_LIVE_PATCH_SYSTEMVM = "LIVE.PATCH.SYSTEM.VM"; + //Purge resources + public static final String EVENT_PURGE_EXPUNGED_RESOURCES = "PURGE.EXPUNGED.RESOURCES"; // OBJECT STORE public static final String EVENT_OBJECT_STORE_CREATE = "OBJECT.STORE.CREATE"; @@ -738,6 +754,37 @@ public class EventTypes { public static final String EVENT_QUOTA_TARIFF_DELETE = "QUOTA.TARIFF.DELETE"; public static final String EVENT_QUOTA_TARIFF_UPDATE = "QUOTA.TARIFF.UPDATE"; + // Routing + public static final String EVENT_ZONE_IP4_SUBNET_CREATE = "ZONE.IP4.SUBNET.CREATE"; + public static final String EVENT_ZONE_IP4_SUBNET_UPDATE = "ZONE.IP4.SUBNET.UPDATE"; + public static final String EVENT_ZONE_IP4_SUBNET_DELETE = "ZONE.IP4.SUBNET.DELETE"; + public static final String EVENT_ZONE_IP4_SUBNET_DEDICATE = "ZONE.IP4.SUBNET.DEDICATE"; + public static final String EVENT_ZONE_IP4_SUBNET_RELEASE = "ZONE.IP4.SUBNET.RELEASE"; + public static final String EVENT_IP4_GUEST_SUBNET_CREATE = "IP4.GUEST.SUBNET.CREATE"; + public static final String EVENT_IP4_GUEST_SUBNET_DELETE = "IP4.GUEST.SUBNET.DELETE"; + public static final String EVENT_ROUTING_IPV4_FIREWALL_RULE_CREATE = "ROUTING.IPV4.FIREWALL.RULE.CREATE"; + public static final String EVENT_ROUTING_IPV4_FIREWALL_RULE_UPDATE = "ROUTING.IPV4.FIREWALL.RULE.UPDATE"; + public static final String EVENT_ROUTING_IPV4_FIREWALL_RULE_DELETE = "ROUTING.IPV4.FIREWALL.RULE.DELETE"; + public static final String EVENT_BGP_PEER_CREATE = "BGP.PEER.CREATE"; + public static final String EVENT_BGP_PEER_UPDATE = "BGP.PEER.UPDATE"; + public static final String EVENT_BGP_PEER_DELETE = "BGP.PEER.DELETE"; + public static final String EVENT_BGP_PEER_DEDICATE = "BGP.PEER.DEDICATE"; + public static final String EVENT_BGP_PEER_RELEASE = "BGP.PEER.RELEASE"; + public static final String EVENT_NETWORK_BGP_PEER_UPDATE = "NETWORK.BGP.PEER.UPDATE"; + public static final String EVENT_VPC_BGP_PEER_UPDATE = "VPC.BGP.PEER.UPDATE"; + + // SharedFS + public static final String EVENT_SHAREDFS_CREATE = "SHAREDFS.CREATE"; + public static final String EVENT_SHAREDFS_START = "SHAREDFS.START"; + public static final String EVENT_SHAREDFS_UPDATE = "SHAREDFS.UPDATE"; + public static final String EVENT_SHAREDFS_CHANGE_SERVICE_OFFERING = "SHAREDFS.CHANGE.SERVICE.OFFERING"; + public static final String EVENT_SHAREDFS_CHANGE_DISK_OFFERING = "SHAREDFS.CHANGE.DISK.OFFERING"; + public static final String EVENT_SHAREDFS_STOP = "SHAREDFS.STOP"; + public static final String EVENT_SHAREDFS_RESTART = "SHAREDFS.RESTART"; + public static final String EVENT_SHAREDFS_DESTROY = "SHAREDFS.DESTROY"; + public static final String EVENT_SHAREDFS_EXPUNGE = "SHAREDFS.EXPUNGE"; + public static final String EVENT_SHAREDFS_RECOVER = "SHAREDFS.RECOVER"; + static { // TODO: need a way to force author adding event types to declare the entity details as well, with out braking @@ -839,6 +886,8 @@ public class EventTypes { entityEventDetails.put(EVENT_ROLE_UPDATE, Role.class); entityEventDetails.put(EVENT_ROLE_DELETE, Role.class); entityEventDetails.put(EVENT_ROLE_IMPORT, Role.class); + entityEventDetails.put(EVENT_ROLE_ENABLE, Role.class); + entityEventDetails.put(EVENT_ROLE_DISABLE, Role.class); entityEventDetails.put(EVENT_ROLE_PERMISSION_CREATE, RolePermission.class); entityEventDetails.put(EVENT_ROLE_PERMISSION_UPDATE, RolePermission.class); entityEventDetails.put(EVENT_ROLE_PERMISSION_DELETE, RolePermission.class); @@ -895,6 +944,7 @@ public class EventTypes { // Snapshots entityEventDetails.put(EVENT_SNAPSHOT_CREATE, Snapshot.class); entityEventDetails.put(EVENT_SNAPSHOT_DELETE, Snapshot.class); + entityEventDetails.put(EVENT_SNAPSHOT_EXTRACT, Snapshot.class); entityEventDetails.put(EVENT_SNAPSHOT_ON_PRIMARY, Snapshot.class); entityEventDetails.put(EVENT_SNAPSHOT_OFF_PRIMARY, Snapshot.class); entityEventDetails.put(EVENT_SNAPSHOT_POLICY_CREATE, SnapshotPolicy.class); @@ -999,6 +1049,7 @@ public class EventTypes { entityEventDetails.put(EVENT_MAINTENANCE_PREPARE_PRIMARY_STORAGE, Host.class); // Primary storage pool + entityEventDetails.put(EVENT_UPDATE_PRIMARY_STORAGE, StoragePool.class); entityEventDetails.put(EVENT_ENABLE_PRIMARY_STORAGE, StoragePool.class); entityEventDetails.put(EVENT_DISABLE_PRIMARY_STORAGE, StoragePool.class); entityEventDetails.put(EVENT_CHANGE_STORAGE_POOL_SCOPE, StoragePool.class); @@ -1193,6 +1244,35 @@ public class EventTypes { entityEventDetails.put(EVENT_QUOTA_TARIFF_CREATE, QuotaTariff.class); entityEventDetails.put(EVENT_QUOTA_TARIFF_DELETE, QuotaTariff.class); entityEventDetails.put(EVENT_QUOTA_TARIFF_UPDATE, QuotaTariff.class); + + // Routing + entityEventDetails.put(EVENT_ZONE_IP4_SUBNET_CREATE, DataCenterIpv4GuestSubnet.class); + entityEventDetails.put(EVENT_ZONE_IP4_SUBNET_UPDATE, DataCenterIpv4GuestSubnet.class); + entityEventDetails.put(EVENT_ZONE_IP4_SUBNET_DELETE, DataCenterIpv4GuestSubnet.class); + entityEventDetails.put(EVENT_ZONE_IP4_SUBNET_DEDICATE, DataCenterIpv4GuestSubnet.class); + entityEventDetails.put(EVENT_ZONE_IP4_SUBNET_RELEASE, DataCenterIpv4GuestSubnet.class); + entityEventDetails.put(EVENT_IP4_GUEST_SUBNET_CREATE, Ipv4GuestSubnetNetworkMap.class); + entityEventDetails.put(EVENT_IP4_GUEST_SUBNET_DELETE, Ipv4GuestSubnetNetworkMap.class); + entityEventDetails.put(EVENT_ROUTING_IPV4_FIREWALL_RULE_CREATE, FirewallRule.class); + entityEventDetails.put(EVENT_ROUTING_IPV4_FIREWALL_RULE_UPDATE, FirewallRule.class); + entityEventDetails.put(EVENT_ROUTING_IPV4_FIREWALL_RULE_DELETE, FirewallRule.class); + entityEventDetails.put(EVENT_BGP_PEER_CREATE, BgpPeer.class); + entityEventDetails.put(EVENT_BGP_PEER_UPDATE, BgpPeer.class); + entityEventDetails.put(EVENT_BGP_PEER_DELETE, BgpPeer.class); + entityEventDetails.put(EVENT_BGP_PEER_DEDICATE, BgpPeer.class); + entityEventDetails.put(EVENT_BGP_PEER_RELEASE, BgpPeer.class); + + // SharedFS + entityEventDetails.put(EVENT_SHAREDFS_CREATE, SharedFS.class); + entityEventDetails.put(EVENT_SHAREDFS_START, SharedFS.class); + entityEventDetails.put(EVENT_SHAREDFS_STOP, SharedFS.class); + entityEventDetails.put(EVENT_SHAREDFS_UPDATE, SharedFS.class); + entityEventDetails.put(EVENT_SHAREDFS_CHANGE_SERVICE_OFFERING, SharedFS.class); + entityEventDetails.put(EVENT_SHAREDFS_CHANGE_DISK_OFFERING, SharedFS.class); + entityEventDetails.put(EVENT_SHAREDFS_RESTART, SharedFS.class); + entityEventDetails.put(EVENT_SHAREDFS_DESTROY, SharedFS.class); + entityEventDetails.put(EVENT_SHAREDFS_EXPUNGE, SharedFS.class); + entityEventDetails.put(EVENT_SHAREDFS_RECOVER, SharedFS.class); } public static boolean isNetworkEvent(String eventType) { diff --git a/api/src/main/java/com/cloud/host/Host.java b/api/src/main/java/com/cloud/host/Host.java index 4a3b914364f..a3b6ccadc01 100644 --- a/api/src/main/java/com/cloud/host/Host.java +++ b/api/src/main/java/com/cloud/host/Host.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.host; +import com.cloud.cpu.CPU; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.resource.ResourceState; import com.cloud.utils.fsm.StateObject; @@ -52,9 +53,12 @@ public interface Host extends StateObject, Identity, Partition, HAResour return strs; } } - public static final String HOST_UEFI_ENABLE = "host.uefi.enable"; - public static final String HOST_VOLUME_ENCRYPTION = "host.volume.encryption"; - public static final String HOST_INSTANCE_CONVERSION = "host.instance.conversion"; + + String HOST_UEFI_ENABLE = "host.uefi.enable"; + String HOST_VOLUME_ENCRYPTION = "host.volume.encryption"; + String HOST_INSTANCE_CONVERSION = "host.instance.conversion"; + String HOST_OVFTOOL_VERSION = "host.ovftool.version"; + String HOST_VIRTV2V_VERSION = "host.virtv2v.version"; /** * @return name of the machine. @@ -208,4 +212,6 @@ public interface Host extends StateObject, Identity, Partition, HAResour boolean isDisabled(); ResourceState getResourceState(); + + CPU.CPUArch getArch(); } diff --git a/api/src/main/java/com/cloud/hypervisor/Hypervisor.java b/api/src/main/java/com/cloud/hypervisor/Hypervisor.java index 2f0cc736af3..5739daf98f7 100644 --- a/api/src/main/java/com/cloud/hypervisor/Hypervisor.java +++ b/api/src/main/java/com/cloud/hypervisor/Hypervisor.java @@ -17,55 +17,67 @@ package com.cloud.hypervisor; import com.cloud.storage.Storage.ImageFormat; +import org.apache.commons.lang3.StringUtils; -import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.EnumSet; +import java.util.stream.Collectors; + +import static com.cloud.hypervisor.Hypervisor.HypervisorType.Functionality.DirectDownloadTemplate; +import static com.cloud.hypervisor.Hypervisor.HypervisorType.Functionality.RootDiskSizeOverride; +import static com.cloud.hypervisor.Hypervisor.HypervisorType.Functionality.VmStorageMigration; +import static com.cloud.hypervisor.Hypervisor.HypervisorType.Functionality.VmStorageMigrationWithSnapshots; public class Hypervisor { + public static class HypervisorType { + public enum Functionality { + DirectDownloadTemplate, + RootDiskSizeOverride, + VmStorageMigration, + VmStorageMigrationWithSnapshots + } - static Map hypervisorTypeMap; - static Map supportedImageFormatMap; + private static final Map hypervisorTypeMap = new LinkedHashMap<>(); + public static final HypervisorType None = new HypervisorType("None"); //for storage hosts + public static final HypervisorType XenServer = new HypervisorType("XenServer", ImageFormat.VHD, EnumSet.of(RootDiskSizeOverride, VmStorageMigration)); + public static final HypervisorType KVM = new HypervisorType("KVM", ImageFormat.QCOW2, EnumSet.of(DirectDownloadTemplate, RootDiskSizeOverride, VmStorageMigration)); + public static final HypervisorType VMware = new HypervisorType("VMware", ImageFormat.OVA, EnumSet.of(RootDiskSizeOverride, VmStorageMigration, VmStorageMigrationWithSnapshots)); + public static final HypervisorType Hyperv = new HypervisorType("Hyperv"); + public static final HypervisorType VirtualBox = new HypervisorType("VirtualBox"); + public static final HypervisorType Parralels = new HypervisorType("Parralels"); + public static final HypervisorType BareMetal = new HypervisorType("BareMetal"); + public static final HypervisorType Simulator = new HypervisorType("Simulator", null, EnumSet.of(RootDiskSizeOverride, VmStorageMigration)); + public static final HypervisorType Ovm = new HypervisorType("Ovm", ImageFormat.RAW); + public static final HypervisorType Ovm3 = new HypervisorType("Ovm3", ImageFormat.RAW); + public static final HypervisorType LXC = new HypervisorType("LXC"); + public static final HypervisorType Custom = new HypervisorType("Custom", null, EnumSet.of(RootDiskSizeOverride)); + public static final HypervisorType Any = new HypervisorType("Any"); /*If you don't care about the hypervisor type*/ + private final String name; + private final ImageFormat imageFormat; + private final Set supportedFunctionalities; - public enum HypervisorType { - None, //for storage hosts - XenServer, - KVM, - VMware, - Hyperv, - VirtualBox, - Parralels, - BareMetal, - Simulator, - Ovm, - Ovm3, - LXC, - Custom, + public HypervisorType(String name) { + this(name, null, EnumSet.noneOf(Functionality.class)); + } - Any; /*If you don't care about the hypervisor type*/ + public HypervisorType(String name, ImageFormat imageFormat) { + this(name, imageFormat, EnumSet.noneOf(Functionality.class)); + } - static { - hypervisorTypeMap = new HashMap<>(); - hypervisorTypeMap.put("xenserver", HypervisorType.XenServer); - hypervisorTypeMap.put("kvm", HypervisorType.KVM); - hypervisorTypeMap.put("vmware", HypervisorType.VMware); - hypervisorTypeMap.put("hyperv", HypervisorType.Hyperv); - hypervisorTypeMap.put("virtualbox", HypervisorType.VirtualBox); - hypervisorTypeMap.put("parallels", HypervisorType.Parralels); - hypervisorTypeMap.put("baremetal", HypervisorType.BareMetal); - hypervisorTypeMap.put("simulator", HypervisorType.Simulator); - hypervisorTypeMap.put("ovm", HypervisorType.Ovm); - hypervisorTypeMap.put("lxc", HypervisorType.LXC); - hypervisorTypeMap.put("any", HypervisorType.Any); - hypervisorTypeMap.put("ovm3", HypervisorType.Ovm3); - hypervisorTypeMap.put("custom", HypervisorType.Custom); - - supportedImageFormatMap = new HashMap<>(); - supportedImageFormatMap.put(HypervisorType.XenServer, ImageFormat.VHD); - supportedImageFormatMap.put(HypervisorType.KVM, ImageFormat.QCOW2); - supportedImageFormatMap.put(HypervisorType.VMware, ImageFormat.OVA); - supportedImageFormatMap.put(HypervisorType.Ovm, ImageFormat.RAW); - supportedImageFormatMap.put(HypervisorType.Ovm3, ImageFormat.RAW); + public HypervisorType(String name, ImageFormat imageFormat, Set supportedFunctionalities) { + this.name = name; + this.imageFormat = imageFormat; + this.supportedFunctionalities = supportedFunctionalities; + if (name.equals("Parralels")){ // typo in the original code + hypervisorTypeMap.put("parallels", this); + } else { + hypervisorTypeMap.putIfAbsent(name.toLowerCase(Locale.ROOT), this); + } } public static HypervisorType getType(String hypervisor) { @@ -75,24 +87,77 @@ public class Hypervisor { hypervisorTypeMap.getOrDefault(hypervisor.toLowerCase(Locale.ROOT), HypervisorType.None)); } + public static HypervisorType[] values() { + return hypervisorTypeMap.values().toArray(HypervisorType[]::new).clone(); + } + + public static HypervisorType valueOf(String name) { + if (StringUtils.isBlank(name)) { + return null; + } + + HypervisorType hypervisorType = hypervisorTypeMap.get(name.toLowerCase(Locale.ROOT)); + if (hypervisorType == null) { + throw new IllegalArgumentException("HypervisorType '" + name + "' not found"); + } + return hypervisorType; + } + + public static List getListOfHypervisorsSupportingFunctionality(Functionality functionality) { + return hypervisorTypeMap.values().stream() + .filter(hypervisor -> hypervisor.supportedFunctionalities.contains(functionality)) + .collect(Collectors.toList()); + } + /** * Returns the display name of a hypervisor type in case the custom hypervisor is used, * using the 'hypervisor.custom.display.name' setting. Otherwise, returns hypervisor name */ public String getHypervisorDisplayName() { - return !Hypervisor.HypervisorType.Custom.equals(this) ? - this.toString() : - HypervisorGuru.HypervisorCustomDisplayName.value(); + return HypervisorType.Custom.equals(this) ? HypervisorGuru.HypervisorCustomDisplayName.value() : name; } /** * This method really needs to be part of the properties of the hypervisor type itself. * - * @param hyperType * @return */ - public static ImageFormat getSupportedImageFormat(HypervisorType hyperType) { - return supportedImageFormatMap.getOrDefault(hyperType, null); + public ImageFormat getSupportedImageFormat() { + return imageFormat; + } + + public String name() { + return name; + } + + /** + * Make this method to be part of the properties of the hypervisor type itself. + * + * @return true if the hypervisor plugin support the specified functionality + */ + public boolean isFunctionalitySupported(Functionality functionality) { + return supportedFunctionalities.contains(functionality); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o == null || getClass() != o.getClass()) { + return false; + } + HypervisorType that = (HypervisorType) o; + return Objects.equals(name, that.name); + } + + @Override + public String toString() { + return name; } } diff --git a/api/src/main/java/com/cloud/kubernetes/cluster/KubernetesServiceHelper.java b/api/src/main/java/com/cloud/kubernetes/cluster/KubernetesServiceHelper.java index 924dbf37f67..84e898528b5 100644 --- a/api/src/main/java/com/cloud/kubernetes/cluster/KubernetesServiceHelper.java +++ b/api/src/main/java/com/cloud/kubernetes/cluster/KubernetesServiceHelper.java @@ -25,6 +25,7 @@ import com.cloud.utils.component.Adapter; public interface KubernetesServiceHelper extends Adapter { ControlledEntity findByUuid(String uuid); + ControlledEntity findByVmId(long vmId); void checkVmCanBeDestroyed(UserVm userVm); void cleanupForAccount(Account account); } diff --git a/api/src/main/java/com/cloud/network/IpAddress.java b/api/src/main/java/com/cloud/network/IpAddress.java index cf2e2f82db9..ae1af450577 100644 --- a/api/src/main/java/com/cloud/network/IpAddress.java +++ b/api/src/main/java/com/cloud/network/IpAddress.java @@ -97,4 +97,6 @@ public interface IpAddress extends ControlledEntity, Identity, InternalIdentity, void setRuleState(State ruleState); + boolean isForSystemVms(); + } diff --git a/api/src/main/java/com/cloud/network/Ipv6Service.java b/api/src/main/java/com/cloud/network/Ipv6Service.java index 2b4dff01086..4ef5f98c38d 100644 --- a/api/src/main/java/com/cloud/network/Ipv6Service.java +++ b/api/src/main/java/com/cloud/network/Ipv6Service.java @@ -58,7 +58,7 @@ public interface Ipv6Service extends PluggableService, Configurable { Pair getUsedTotalIpv6SubnetForZone(long zoneId); - Pair preAllocateIpv6SubnetForNetwork(long zoneId) throws ResourceAllocationException; + Pair preAllocateIpv6SubnetForNetwork(DataCenter zone) throws ResourceAllocationException; void assignIpv6SubnetToNetwork(String subnet, long networkId); diff --git a/api/src/main/java/com/cloud/network/Network.java b/api/src/main/java/com/cloud/network/Network.java index 458169c80aa..d3bc5005cb7 100644 --- a/api/src/main/java/com/cloud/network/Network.java +++ b/api/src/main/java/com/cloud/network/Network.java @@ -103,7 +103,7 @@ public interface Network extends ControlledEntity, StateObject, I public static final Service Vpn = new Service("Vpn", Capability.SupportedVpnProtocols, Capability.VpnTypes); public static final Service Dhcp = new Service("Dhcp", Capability.ExtraDhcpOptions); public static final Service Dns = new Service("Dns", Capability.AllowDnsSuffixModification); - public static final Service Gateway = new Service("Gateway"); + public static final Service Gateway = new Service("Gateway", Capability.RedundantRouter); public static final Service Firewall = new Service("Firewall", Capability.SupportedProtocols, Capability.MultipleIps, Capability.TrafficStatistics, Capability.SupportedTrafficDirection, Capability.SupportedEgressProtocols); public static final Service Lb = new Service("Lb", Capability.SupportedLBAlgorithms, Capability.SupportedLBIsolation, Capability.SupportedProtocols, @@ -205,6 +205,8 @@ public interface Network extends ControlledEntity, StateObject, I //Add Tungsten Fabric provider public static final Provider Tungsten = new Provider("Tungsten", false); + public static final Provider Nsx = new Provider("Nsx", false); + private final String name; private final boolean isExternal; @@ -410,12 +412,16 @@ public interface Network extends ControlledEntity, StateObject, I String getGateway(); + void setGateway(String gateway); + // "cidr" is the Cloudstack managed address space, all CloudStack managed vms get IP address from "cidr", // In general "cidr" also serves as the network CIDR // But in case IP reservation is configured for a Guest network, "networkcidr" is the Effective network CIDR for that network, // "cidr" will still continue to be the effective address space for CloudStack managed vms in that Guest network String getCidr(); + void setCidr(String cidr); + // "networkcidr" is the network CIDR of the guest network which uses IP reservation. // It is the summation of "cidr" and the reservedIPrange(the address space used for non CloudStack purposes). // For networks not configured with IP reservation, "networkcidr" is always null @@ -427,6 +433,8 @@ public interface Network extends ControlledEntity, StateObject, I long getDataCenterId(); + long getAccountId(); + long getNetworkOfferingId(); @Override @@ -499,4 +507,6 @@ public interface Network extends ControlledEntity, StateObject, I Integer getPublicMtu(); Integer getPrivateMtu(); + + Integer getNetworkCidrSize(); } diff --git a/api/src/main/java/com/cloud/network/NetworkModel.java b/api/src/main/java/com/cloud/network/NetworkModel.java index ed3506c0da1..a4cd87af008 100644 --- a/api/src/main/java/com/cloud/network/NetworkModel.java +++ b/api/src/main/java/com/cloud/network/NetworkModel.java @@ -173,6 +173,8 @@ public interface NetworkModel { boolean isProviderSupportServiceInNetwork(long networkId, Service service, Provider provider); + boolean isAnyServiceSupportedInNetwork(long networkId, Provider provider, Service... services); + boolean isProviderEnabledInPhysicalNetwork(long physicalNetowrkId, String providerName); String getNetworkTag(HypervisorType hType, Network network); @@ -356,4 +358,8 @@ public interface NetworkModel { void verifyIp6DnsPair(final String ip6Dns1, final String ip6Dns2); + boolean isSecurityGroupSupportedForZone(Long zoneId); + + boolean checkSecurityGroupSupportForNetwork(Account account, DataCenter zone, List networkIds, + List securityGroupsIds); } diff --git a/api/src/main/java/com/cloud/network/NetworkProfile.java b/api/src/main/java/com/cloud/network/NetworkProfile.java index 44853069575..2e8efb48930 100644 --- a/api/src/main/java/com/cloud/network/NetworkProfile.java +++ b/api/src/main/java/com/cloud/network/NetworkProfile.java @@ -22,10 +22,9 @@ import java.util.Date; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; -import org.apache.log4j.Logger; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public class NetworkProfile implements Network { - static final Logger s_logger = Logger.getLogger(NetworkProfile.class); private final long id; private final String uuid; private final long dataCenterId; @@ -43,8 +42,8 @@ public class NetworkProfile implements Network { private final Mode mode; private final BroadcastDomainType broadcastDomainType; private TrafficType trafficType; - private final String gateway; - private final String cidr; + private String gateway; + private String cidr; private final String networkCidr; private final String ip6Gateway; private final String ip6Cidr; @@ -64,6 +63,7 @@ public class NetworkProfile implements Network { private final String guruName; private boolean strechedL2Subnet; private String externalId; + private Integer networkCidrSize; public NetworkProfile(Network network) { id = network.getId(); @@ -100,6 +100,7 @@ public class NetworkProfile implements Network { isRedundant = network.isRedundant(); isRollingRestart = network.isRollingRestart(); externalId = network.getExternalId(); + networkCidrSize = network.getNetworkCidrSize(); } @Override @@ -212,11 +213,21 @@ public class NetworkProfile implements Network { return gateway; } + @Override + public void setGateway(String gateway) { + this.gateway = gateway; + } + @Override public String getCidr() { return cidr; } + @Override + public void setCidr(String cidr) { + this.cidr = cidr; + } + @Override public String getNetworkCidr() { return networkCidr; @@ -369,4 +380,16 @@ public class NetworkProfile implements Network { return null; } + @Override + public Integer getNetworkCidrSize() { + return networkCidrSize; + } + + @Override + public String toString() { + return String.format("NetworkProfile %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "networkOfferingId")); + } + } diff --git a/api/src/main/java/com/cloud/network/NetworkService.java b/api/src/main/java/com/cloud/network/NetworkService.java index c562a54a048..b8dd464b365 100644 --- a/api/src/main/java/com/cloud/network/NetworkService.java +++ b/api/src/main/java/com/cloud/network/NetworkService.java @@ -19,6 +19,7 @@ package com.cloud.network; import java.util.List; import java.util.Map; +import com.cloud.dc.DataCenter; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.command.admin.address.ReleasePodIpCmdByAdmin; import org.apache.cloudstack.api.command.admin.network.DedicateGuestVlanRangeCmd; @@ -56,6 +57,7 @@ import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.Nic; import com.cloud.vm.NicSecondaryIp; +import org.apache.cloudstack.network.element.InternalLoadBalancerElementService; /** * The NetworkService interface is the "public" api to entities that make requests to the orchestration engine @@ -88,6 +90,8 @@ public interface NetworkService { IpAddress reserveIpAddress(Account account, Boolean displayIp, Long ipAddressId) throws ResourceAllocationException; + IpAddress reserveIpAddressWithVlanDetail(Account account, DataCenter zone, Boolean displayIp, String vlanDetailKey) throws ResourceAllocationException; + boolean releaseReservedIpAddress(long ipAddressId) throws InsufficientAddressCapacityException; boolean releaseIpAddress(long ipAddressId) throws InsufficientAddressCapacityException; @@ -259,4 +263,9 @@ public interface NetworkService { PublicIpQuarantine updatePublicIpAddressInQuarantine(UpdateQuarantinedIpCmd cmd); void removePublicIpAddressFromQuarantine(RemoveQuarantinedIpCmd cmd); + + InternalLoadBalancerElementService getInternalLoadBalancerElementByType(VirtualRouterProvider.Type type); + InternalLoadBalancerElementService getInternalLoadBalancerElementByNetworkServiceProviderId(long networkProviderId); + InternalLoadBalancerElementService getInternalLoadBalancerElementById(long providerId); + List getInternalLoadBalancerElements(); } diff --git a/api/src/main/java/com/cloud/network/Networks.java b/api/src/main/java/com/cloud/network/Networks.java index aeed5d4aec6..8e7399bb21d 100644 --- a/api/src/main/java/com/cloud/network/Networks.java +++ b/api/src/main/java/com/cloud/network/Networks.java @@ -78,7 +78,7 @@ public class Networks { } @Override public String getValueFrom(URI uri) { - return uri.getAuthority(); + return uri == null ? null : uri.getAuthority(); } }, Vswitch("vs", String.class), LinkLocal(null, null), Vnet("vnet", Long.class), Storage("storage", Integer.class), Lswitch("lswitch", String.class) { @@ -96,7 +96,7 @@ public class Networks { */ @Override public String getValueFrom(URI uri) { - return uri.getSchemeSpecificPart(); + return uri == null ? null : uri.getSchemeSpecificPart(); } }, Mido("mido", String.class), Pvlan("pvlan", String.class), @@ -128,7 +128,8 @@ public class Networks { }, UnDecided(null, null), OpenDaylight("opendaylight", String.class), - TUNGSTEN("tf", String.class); + TUNGSTEN("tf", String.class), + NSX("nsx", String.class); private final String scheme; private final Class type; @@ -175,7 +176,7 @@ public class Networks { * @return the scheme as BroadcastDomainType */ public static BroadcastDomainType getSchemeValue(URI uri) { - return toEnumValue(uri.getScheme()); + return toEnumValue(uri == null ? null : uri.getScheme()); } /** @@ -189,7 +190,7 @@ public class Networks { if (com.cloud.dc.Vlan.UNTAGGED.equalsIgnoreCase(str)) { return Native; } - return getSchemeValue(new URI(str)); + return getSchemeValue(str == null ? null : new URI(str)); } /** @@ -218,7 +219,7 @@ public class Networks { * @return the host part as String */ public String getValueFrom(URI uri) { - return uri.getHost(); + return uri == null ? null : uri.getHost(); } /** @@ -241,7 +242,7 @@ public class Networks { * @throws URISyntaxException the string is not even an uri */ public static String getValue(String uriString) throws URISyntaxException { - return getValue(new URI(uriString)); + return getValue(uriString == null ? null : new URI(uriString)); } /** diff --git a/api/src/main/java/com/cloud/network/VirtualRouterProvider.java b/api/src/main/java/com/cloud/network/VirtualRouterProvider.java index aca526b1832..98410ca09f8 100644 --- a/api/src/main/java/com/cloud/network/VirtualRouterProvider.java +++ b/api/src/main/java/com/cloud/network/VirtualRouterProvider.java @@ -21,7 +21,7 @@ import org.apache.cloudstack.api.InternalIdentity; public interface VirtualRouterProvider extends InternalIdentity, Identity { public enum Type { - VirtualRouter, ElasticLoadBalancerVm, VPCVirtualRouter, InternalLbVm, NetScalerVm + VirtualRouter, ElasticLoadBalancerVm, VPCVirtualRouter, InternalLbVm, NetScalerVm, Nsx } public Type getType(); diff --git a/api/src/main/java/com/cloud/network/element/BgpServiceProvider.java b/api/src/main/java/com/cloud/network/element/BgpServiceProvider.java new file mode 100644 index 00000000000..ee919cb1af7 --- /dev/null +++ b/api/src/main/java/com/cloud/network/element/BgpServiceProvider.java @@ -0,0 +1,31 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.network.element; + +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.vpc.Vpc; + +import org.apache.cloudstack.network.BgpPeer; + +import java.util.List; + +public interface BgpServiceProvider extends NetworkElement { + + boolean applyBgpPeers(Vpc vpc, Network network, List bgpPeers) throws ResourceUnavailableException; + +} diff --git a/api/src/main/java/com/cloud/network/element/LoadBalancingServiceProvider.java b/api/src/main/java/com/cloud/network/element/LoadBalancingServiceProvider.java index 1bb37be970d..dc0f60f4519 100644 --- a/api/src/main/java/com/cloud/network/element/LoadBalancingServiceProvider.java +++ b/api/src/main/java/com/cloud/network/element/LoadBalancingServiceProvider.java @@ -48,4 +48,7 @@ public interface LoadBalancingServiceProvider extends NetworkElement, IpDeployin List updateHealthChecks(Network network, List lbrules); boolean handlesOnlyRulesInTransitionState(); + + default void expungeLbVmRefs(List vmIds, Long batchSize) { + } } diff --git a/api/src/main/java/com/cloud/network/element/NetworkACLServiceProvider.java b/api/src/main/java/com/cloud/network/element/NetworkACLServiceProvider.java index 8c3243c99f4..852a650cfcd 100644 --- a/api/src/main/java/com/cloud/network/element/NetworkACLServiceProvider.java +++ b/api/src/main/java/com/cloud/network/element/NetworkACLServiceProvider.java @@ -21,6 +21,7 @@ import java.util.List; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.vpc.NetworkACLItem; +import com.cloud.network.vpc.Vpc; public interface NetworkACLServiceProvider extends NetworkElement { @@ -32,4 +33,6 @@ public interface NetworkACLServiceProvider extends NetworkElement { */ boolean applyNetworkACLs(Network config, List rules) throws ResourceUnavailableException; + boolean reorderAclRules(Vpc vpc, List networks, List networkACLItems); + } diff --git a/api/src/main/java/com/cloud/network/element/VpcProvider.java b/api/src/main/java/com/cloud/network/element/VpcProvider.java index 14e86195a70..6debd1fbc2d 100644 --- a/api/src/main/java/com/cloud/network/element/VpcProvider.java +++ b/api/src/main/java/com/cloud/network/element/VpcProvider.java @@ -22,6 +22,7 @@ import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.IpAddress; import com.cloud.network.vpc.NetworkACLItem; import com.cloud.network.vpc.PrivateGateway; import com.cloud.network.vpc.StaticRouteProfile; @@ -52,4 +53,6 @@ public interface VpcProvider extends NetworkElement { boolean applyStaticRoutes(Vpc vpc, List routes) throws ResourceUnavailableException; boolean applyACLItemsToPrivateGw(PrivateGateway gateway, List rules) throws ResourceUnavailableException; + + boolean updateVpcSourceNatIp(Vpc vpc, IpAddress address); } diff --git a/api/src/main/java/com/cloud/network/guru/NetworkGuru.java b/api/src/main/java/com/cloud/network/guru/NetworkGuru.java index c4f2beba63e..7b81c75ed84 100644 --- a/api/src/main/java/com/cloud/network/guru/NetworkGuru.java +++ b/api/src/main/java/com/cloud/network/guru/NetworkGuru.java @@ -79,20 +79,24 @@ public interface NetworkGuru extends Adapter { * be used to make determination can be isolation methods, services * provided on the guest network and the service provider that's on the * guest network. - * + *

* If a network is already fully substantiated with the necessary resources * during this design phase, then the state should be set to Setup. If * the resources are not allocated at this point, the state should be set * to Allocated. * - * @param offering network offering that contains the package of services - * the end user intends to use on that network. - * @param plan where is this network being deployed. + * @param offering network offering that contains the package of services + * the end user intends to use on that network. + * @param plan where is this network being deployed. * @param userSpecified user specified parameters for this network. - * @param owner owner of this network. + * @param name + * @param vpcId + * @param owner owner of this network. * @return Network */ - Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner); + Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, String name, Long vpcId, Account owner); + + void setup(Network network, long networkId); /** * For guest networks that are in Allocated state after the design stage, diff --git a/api/src/main/java/com/cloud/network/lb/LoadBalancingRule.java b/api/src/main/java/com/cloud/network/lb/LoadBalancingRule.java index 64b2aeedf12..e4cf4ec526f 100644 --- a/api/src/main/java/com/cloud/network/lb/LoadBalancingRule.java +++ b/api/src/main/java/com/cloud/network/lb/LoadBalancingRule.java @@ -63,6 +63,10 @@ public class LoadBalancingRule { return lb.getId(); } + public LoadBalancer getLb() { + return lb; + } + public String getName() { return lb.getName(); } diff --git a/api/src/main/java/com/cloud/network/nsx/NsxProvider.java b/api/src/main/java/com/cloud/network/nsx/NsxProvider.java new file mode 100644 index 00000000000..19cb3b4b939 --- /dev/null +++ b/api/src/main/java/com/cloud/network/nsx/NsxProvider.java @@ -0,0 +1,34 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.network.nsx; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface NsxProvider extends InternalIdentity, Identity { + String getHostname(); + + String getPort(); + String getProviderName(); + String getUsername(); + long getZoneId(); + + String getTier0Gateway(); + String getEdgeCluster(); + + String getTransportZone(); +} diff --git a/api/src/main/java/com/cloud/network/nsx/NsxService.java b/api/src/main/java/com/cloud/network/nsx/NsxService.java new file mode 100644 index 00000000000..bc4e6aafbfe --- /dev/null +++ b/api/src/main/java/com/cloud/network/nsx/NsxService.java @@ -0,0 +1,36 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.network.nsx; + +import com.cloud.network.IpAddress; +import com.cloud.network.vpc.Vpc; +import org.apache.cloudstack.framework.config.ConfigKey; + +public interface NsxService { + + ConfigKey NSX_API_FAILURE_RETRIES = new ConfigKey<>("Advanced", Integer.class, + "nsx.api.failure.retries", "30", + "Number of retries for NSX API operations in case of failures", + true, ConfigKey.Scope.Zone); + ConfigKey NSX_API_FAILURE_INTERVAL = new ConfigKey<>("Advanced", Integer.class, + "nsx.api.failure.interval", "60", + "Waiting time (in seconds) before retrying an NSX API operation in case of failure", + true, ConfigKey.Scope.Zone); + + boolean createVpcNetwork(Long zoneId, long accountId, long domainId, Long vpcId, String vpcName, boolean sourceNatEnabled); + boolean updateVpcSourceNatIp(Vpc vpc, IpAddress address); +} diff --git a/api/src/main/java/com/cloud/network/vpc/VpcOffering.java b/api/src/main/java/com/cloud/network/vpc/VpcOffering.java index b4df8e38dba..38263f59667 100644 --- a/api/src/main/java/com/cloud/network/vpc/VpcOffering.java +++ b/api/src/main/java/com/cloud/network/vpc/VpcOffering.java @@ -18,6 +18,7 @@ package com.cloud.network.vpc; import java.util.Date; +import com.cloud.offering.NetworkOffering; import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; @@ -29,6 +30,8 @@ public interface VpcOffering extends InternalIdentity, Identity { public static final String defaultVPCOfferingName = "Default VPC offering"; public static final String defaultVPCNSOfferingName = "Default VPC offering with Netscaler"; public static final String redundantVPCOfferingName = "Redundant VPC offering"; + public static final String DEFAULT_VPC_NAT_NSX_OFFERING_NAME = "VPC offering with NSX - NAT Mode"; + public static final String DEFAULT_VPC_ROUTE_NSX_OFFERING_NAME = "VPC offering with NSX - Route Mode"; /** * @@ -53,6 +56,10 @@ public interface VpcOffering extends InternalIdentity, Identity { */ boolean isDefault(); + boolean isForNsx(); + + NetworkOffering.NetworkMode getNetworkMode(); + /** * @return service offering id used by VPC virtual router */ @@ -73,4 +80,8 @@ public interface VpcOffering extends InternalIdentity, Identity { Date getRemoved(); Date getCreated(); + + NetworkOffering.RoutingMode getRoutingMode(); + + Boolean isSpecifyAsNumber(); } diff --git a/api/src/main/java/com/cloud/network/vpc/VpcProvisioningService.java b/api/src/main/java/com/cloud/network/vpc/VpcProvisioningService.java index 5cccd6c5a82..10f1ddcc12d 100644 --- a/api/src/main/java/com/cloud/network/vpc/VpcProvisioningService.java +++ b/api/src/main/java/com/cloud/network/vpc/VpcProvisioningService.java @@ -24,6 +24,7 @@ import org.apache.cloudstack.api.command.admin.vpc.CreateVPCOfferingCmd; import org.apache.cloudstack.api.command.admin.vpc.UpdateVPCOfferingCmd; import org.apache.cloudstack.api.command.user.vpc.ListVPCOfferingsCmd; +import com.cloud.offering.NetworkOffering; import com.cloud.utils.Pair; import com.cloud.utils.net.NetUtils; @@ -36,7 +37,10 @@ public interface VpcProvisioningService { VpcOffering createVpcOffering(String name, String displayText, List supportedServices, Map> serviceProviders, Map serviceCapabilitystList, NetUtils.InternetProtocol internetProtocol, - Long serviceOfferingId, List domainIds, List zoneIds, VpcOffering.State state); + Long serviceOfferingId, Boolean forNsx, NetworkOffering.NetworkMode networkMode, + List domainIds, List zoneIds, VpcOffering.State state, + NetworkOffering.RoutingMode routingMode, boolean specifyAsNumber); + Pair,Integer> listVpcOfferings(ListVPCOfferingsCmd cmd); diff --git a/api/src/main/java/com/cloud/network/vpc/VpcService.java b/api/src/main/java/com/cloud/network/vpc/VpcService.java index 0f0d29f4082..af2a9847a62 100644 --- a/api/src/main/java/com/cloud/network/vpc/VpcService.java +++ b/api/src/main/java/com/cloud/network/vpc/VpcService.java @@ -56,7 +56,8 @@ public interface VpcService { * @throws ResourceAllocationException TODO */ Vpc createVpc(long zoneId, long vpcOffId, long vpcOwnerId, String vpcName, String displayText, String cidr, String networkDomain, - String ip4Dns1, String ip4Dns2, String ip6Dns1, String ip6Dns2, Boolean displayVpc, Integer publicMtu) + String ip4Dns1, String ip4Dns2, String ip6Dns1, String ip6Dns2, Boolean displayVpc, Integer publicMtu, Integer cidrSize, + Long asNumber, List bgpPeerIds) throws ResourceAllocationException; /** diff --git a/api/src/main/java/com/cloud/network/vpn/RemoteAccessVpnService.java b/api/src/main/java/com/cloud/network/vpn/RemoteAccessVpnService.java index bbb9771d27a..ffa8af4576d 100644 --- a/api/src/main/java/com/cloud/network/vpn/RemoteAccessVpnService.java +++ b/api/src/main/java/com/cloud/network/vpn/RemoteAccessVpnService.java @@ -39,7 +39,7 @@ public interface RemoteAccessVpnService { VpnUser addVpnUser(long vpnOwnerId, String userName, String password); - boolean removeVpnUser(long vpnOwnerId, String userName, Account caller); + boolean removeVpnUser(Account vpnOwner, String userName, Account caller); List listVpnUsers(long vpnOwnerId, String userName); diff --git a/api/src/main/java/com/cloud/offering/NetworkOffering.java b/api/src/main/java/com/cloud/offering/NetworkOffering.java index 207880ea28c..7011aea679e 100644 --- a/api/src/main/java/com/cloud/offering/NetworkOffering.java +++ b/api/src/main/java/com/cloud/offering/NetworkOffering.java @@ -43,6 +43,15 @@ public interface NetworkOffering extends InfrastructureEntity, InternalIdentity, InternalLbProvider, PublicLbProvider, servicepackageuuid, servicepackagedescription, PromiscuousMode, MacAddressChanges, ForgedTransmits, MacLearning, RelatedNetworkOffering, domainid, zoneid, pvlanType, internetProtocol } + public enum NetworkMode { + NATTED, + ROUTED + } + + enum RoutingMode { + Static, Dynamic + } + public final static String SystemPublicNetwork = "System-Public-Network"; public final static String SystemControlNetwork = "System-Control-Network"; public final static String SystemManagementNetwork = "System-Management-Network"; @@ -52,6 +61,11 @@ public interface NetworkOffering extends InfrastructureEntity, InternalIdentity, public final static String DefaultSharedNetworkOfferingWithSGService = "DefaultSharedNetworkOfferingWithSGService"; public static final String DEFAULT_TUNGSTEN_SHARED_NETWORK_OFFERING_WITH_SGSERVICE = "DefaultTungstenSharedNetworkOfferingWithSGService"; + public static final String DEFAULT_NAT_NSX_OFFERING_FOR_VPC = "DefaultNATNSXNetworkOfferingForVpc"; + public static final String DEFAULT_NAT_NSX_OFFERING_FOR_VPC_WITH_ILB = "DefaultNATNSXNetworkOfferingForVpcWithInternalLB"; + public static final String DEFAULT_ROUTED_NSX_OFFERING_FOR_VPC = "DefaultRoutedNSXNetworkOfferingForVpc"; + public static final String DEFAULT_NAT_NSX_OFFERING = "DefaultNATNSXNetworkOffering"; + public static final String DEFAULT_ROUTED_NSX_OFFERING = "DefaultRoutedNSXNetworkOffering"; public final static String QuickCloudNoServices = "QuickCloudNoServices"; public final static String DefaultIsolatedNetworkOfferingWithSourceNatService = "DefaultIsolatedNetworkOfferingWithSourceNatService"; public final static String OvsIsolatedNetworkOfferingWithSourceNatService = "OvsIsolatedNetworkOfferingWithSourceNatService"; @@ -90,6 +104,10 @@ public interface NetworkOffering extends InfrastructureEntity, InternalIdentity, boolean isForTungsten(); + boolean isForNsx(); + + NetworkMode getNetworkMode(); + TrafficType getTrafficType(); boolean isSpecifyVlan(); @@ -151,4 +169,8 @@ public interface NetworkOffering extends InfrastructureEntity, InternalIdentity, String getServicePackage(); Date getCreated(); + + RoutingMode getRoutingMode(); + + Boolean isSpecifyAsNumber(); } diff --git a/api/src/main/java/com/cloud/offering/ServiceOffering.java b/api/src/main/java/com/cloud/offering/ServiceOffering.java index 58c7b0dbaf9..acb7a9f1cf9 100644 --- a/api/src/main/java/com/cloud/offering/ServiceOffering.java +++ b/api/src/main/java/com/cloud/offering/ServiceOffering.java @@ -33,6 +33,9 @@ public interface ServiceOffering extends InfrastructureEntity, InternalIdentity, static final String internalLbVmDefaultOffUniqueName = "Cloud.Com-InternalLBVm"; // leaving cloud.com references as these are identifyers and no real world addresses (check against DB) + + static final String PURGE_DB_ENTITIES_KEY = "purge.db.entities"; + enum State { Inactive, Active, } diff --git a/api/src/main/java/com/cloud/org/Cluster.java b/api/src/main/java/com/cloud/org/Cluster.java index 4079c88dfde..5124168084c 100644 --- a/api/src/main/java/com/cloud/org/Cluster.java +++ b/api/src/main/java/com/cloud/org/Cluster.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.org; +import com.cloud.cpu.CPU; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Managed.ManagedState; import org.apache.cloudstack.kernel.Partition; @@ -38,4 +39,6 @@ public interface Cluster extends Grouping, Partition { AllocationState getAllocationState(); ManagedState getManagedState(); + + CPU.CPUArch getArch(); } diff --git a/api/src/main/java/com/cloud/region/ha/GlobalLoadBalancingRulesService.java b/api/src/main/java/com/cloud/region/ha/GlobalLoadBalancingRulesService.java index ab6e6fb6c5a..3b61367e3b4 100644 --- a/api/src/main/java/com/cloud/region/ha/GlobalLoadBalancingRulesService.java +++ b/api/src/main/java/com/cloud/region/ha/GlobalLoadBalancingRulesService.java @@ -19,6 +19,7 @@ package com.cloud.region.ha; import java.util.List; +import com.cloud.user.Account; import org.apache.cloudstack.api.command.user.region.ha.gslb.AssignToGlobalLoadBalancerRuleCmd; import org.apache.cloudstack.api.command.user.region.ha.gslb.CreateGlobalLoadBalancerRuleCmd; import org.apache.cloudstack.api.command.user.region.ha.gslb.DeleteGlobalLoadBalancerRuleCmd; @@ -39,7 +40,7 @@ public interface GlobalLoadBalancingRulesService { GlobalLoadBalancerRule updateGlobalLoadBalancerRule(UpdateGlobalLoadBalancerRuleCmd updateGslbCmd); - boolean revokeAllGslbRulesForAccount(com.cloud.user.Account caller, long accountId) throws com.cloud.exception.ResourceUnavailableException; + boolean revokeAllGslbRulesForAccount(com.cloud.user.Account caller, Account account) throws com.cloud.exception.ResourceUnavailableException; /* * methods for managing sites participating in global load balancing diff --git a/api/src/main/java/com/cloud/server/ManagementServerHostStats.java b/api/src/main/java/com/cloud/server/ManagementServerHostStats.java index 1f201d7689f..1eea7addba3 100644 --- a/api/src/main/java/com/cloud/server/ManagementServerHostStats.java +++ b/api/src/main/java/com/cloud/server/ManagementServerHostStats.java @@ -32,6 +32,8 @@ public interface ManagementServerHostStats { String getManagementServerHostUuid(); + long getManagementServerRunId(); + long getSessions(); double getCpuUtilization(); diff --git a/api/src/main/java/com/cloud/server/ManagementService.java b/api/src/main/java/com/cloud/server/ManagementService.java index 18f3e901cd9..d6d7f7a59c6 100644 --- a/api/src/main/java/com/cloud/server/ManagementService.java +++ b/api/src/main/java/com/cloud/server/ManagementService.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import com.cloud.user.UserData; import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd; import org.apache.cloudstack.api.command.admin.config.ListCfgGroupsByCmd; import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd; @@ -66,6 +65,7 @@ import org.apache.cloudstack.api.command.user.vm.GetVMPasswordCmd; import org.apache.cloudstack.api.command.user.vmgroup.UpdateVMGroupCmd; import org.apache.cloudstack.config.Configuration; import org.apache.cloudstack.config.ConfigurationGroup; +import org.apache.cloudstack.framework.config.ConfigKey; import com.cloud.alert.Alert; import com.cloud.capacity.Capacity; @@ -85,6 +85,7 @@ import com.cloud.storage.GuestOSHypervisor; import com.cloud.storage.GuestOsCategory; import com.cloud.storage.StoragePool; import com.cloud.user.SSHKeyPair; +import com.cloud.user.UserData; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.vm.InstanceGroup; @@ -98,6 +99,14 @@ import com.cloud.vm.VirtualMachine.Type; public interface ManagementService { static final String Name = "management-server"; + ConfigKey JsInterpretationEnabled = new ConfigKey<>("Hidden" + , Boolean.class + , "js.interpretation.enabled" + , "false" + , "Enable/Disable all JavaScript interpretation related functionalities to create or update Javascript rules." + , false + , ConfigKey.Scope.Global); + /** * returns the a map of the names/values in the configuration table * @@ -481,4 +490,6 @@ public interface ManagementService { Pair patchSystemVM(PatchSystemVMCmd cmd); + void checkJsInterpretationAllowedIfNeededForParameterValue(String paramName, boolean paramValue); + } diff --git a/api/src/main/java/com/cloud/server/ResourceManagerUtil.java b/api/src/main/java/com/cloud/server/ResourceManagerUtil.java index 9a3b51a70d5..f5081cbe307 100644 --- a/api/src/main/java/com/cloud/server/ResourceManagerUtil.java +++ b/api/src/main/java/com/cloud/server/ResourceManagerUtil.java @@ -18,6 +18,7 @@ package com.cloud.server; public interface ResourceManagerUtil { long getResourceId(String resourceId, ResourceTag.ResourceObjectType resourceType); + long getResourceId(String resourceId, ResourceTag.ResourceObjectType resourceType, boolean checkAccess); String getUuid(String resourceId, ResourceTag.ResourceObjectType resourceType); ResourceTag.ResourceObjectType getResourceType(String resourceTypeStr); void checkResourceAccessible(Long accountId, Long domainId, String exceptionMessage); diff --git a/api/src/main/java/com/cloud/storage/DataStoreRole.java b/api/src/main/java/com/cloud/storage/DataStoreRole.java index 185e370159c..d9af495ab00 100644 --- a/api/src/main/java/com/cloud/storage/DataStoreRole.java +++ b/api/src/main/java/com/cloud/storage/DataStoreRole.java @@ -20,6 +20,7 @@ package com.cloud.storage; import com.cloud.utils.exception.CloudRuntimeException; + public enum DataStoreRole { Primary("primary"), Image("image"), ImageCache("imagecache"), Backup("backup"), Object("object"); diff --git a/api/src/main/java/com/cloud/storage/Storage.java b/api/src/main/java/com/cloud/storage/Storage.java index 0d7a3ed90c0..05b8b3ab7a8 100644 --- a/api/src/main/java/com/cloud/storage/Storage.java +++ b/api/src/main/java/com/cloud/storage/Storage.java @@ -150,6 +150,17 @@ public class Storage { Storage } + /** + * StoragePoolTypes carry some details about the format and capabilities of a storage pool. While not necessarily a + * 1:1 with PrimaryDataStoreDriver (and for KVM agent, KVMStoragePool and StorageAdaptor) implementations, it is + * often used to decide which storage plugin or storage command to call, so it may be necessary for new storage + * plugins to add a StoragePoolType. This can be done by adding it below, or by creating a new public static final + * instance of StoragePoolType in the plugin itself, which registers it with the map. + * + * Note that if the StoragePoolType is for KVM and defined in plugin code rather than below, care must be taken to + * ensure this is available on the agent side as well. This is best done by defining the StoragePoolType in a common + * package available on both management server and agent plugin jars. + */ public static enum StoragePoolType { Filesystem(false, true, EncryptionSupport.Hypervisor), // local directory NetworkFilesystem(true, true, EncryptionSupport.Hypervisor), // NFS diff --git a/api/src/main/java/com/cloud/storage/StorageService.java b/api/src/main/java/com/cloud/storage/StorageService.java index 1ce335b0115..b8df75cd3e4 100644 --- a/api/src/main/java/com/cloud/storage/StorageService.java +++ b/api/src/main/java/com/cloud/storage/StorageService.java @@ -95,6 +95,10 @@ public interface StorageService { StoragePool updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException; + StoragePool enablePrimaryStoragePool(Long id); + + StoragePool disablePrimaryStoragePool(Long id); + StoragePool getStoragePool(long id); boolean deleteImageStore(DeleteImageStoreCmd cmd); diff --git a/api/src/main/java/com/cloud/storage/StorageStats.java b/api/src/main/java/com/cloud/storage/StorageStats.java index a474b23489c..502e2aaae40 100644 --- a/api/src/main/java/com/cloud/storage/StorageStats.java +++ b/api/src/main/java/com/cloud/storage/StorageStats.java @@ -26,4 +26,7 @@ public interface StorageStats { * @return bytes capacity of the storage server */ public long getCapacityBytes(); + + Long getCapacityIops(); + Long getUsedIops(); } diff --git a/api/src/main/java/com/cloud/storage/Upload.java b/api/src/main/java/com/cloud/storage/Upload.java index 59d203ac73a..4e696e877cc 100644 --- a/api/src/main/java/com/cloud/storage/Upload.java +++ b/api/src/main/java/com/cloud/storage/Upload.java @@ -40,7 +40,7 @@ public interface Upload extends InternalIdentity, Identity { } public static enum Type { - VOLUME, TEMPLATE, ISO + VOLUME, SNAPSHOT, TEMPLATE, ISO } public static enum Mode { diff --git a/api/src/main/java/com/cloud/storage/VMTemplateStorageResourceAssoc.java b/api/src/main/java/com/cloud/storage/VMTemplateStorageResourceAssoc.java index f43d5331222..db702a61f2b 100644 --- a/api/src/main/java/com/cloud/storage/VMTemplateStorageResourceAssoc.java +++ b/api/src/main/java/com/cloud/storage/VMTemplateStorageResourceAssoc.java @@ -17,6 +17,7 @@ package com.cloud.storage; import java.util.Date; +import java.util.List; import org.apache.cloudstack.api.InternalIdentity; @@ -25,6 +26,8 @@ public interface VMTemplateStorageResourceAssoc extends InternalIdentity { UNKNOWN, DOWNLOAD_ERROR, NOT_DOWNLOADED, DOWNLOAD_IN_PROGRESS, DOWNLOADED, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS, CREATING, CREATED, BYPASSED } + List PENDING_DOWNLOAD_STATES = List.of(Status.NOT_DOWNLOADED, Status.DOWNLOAD_IN_PROGRESS); + String getInstallPath(); long getTemplateId(); diff --git a/api/src/main/java/com/cloud/storage/Volume.java b/api/src/main/java/com/cloud/storage/Volume.java index 308ed2544ed..c7fbdb0a544 100644 --- a/api/src/main/java/com/cloud/storage/Volume.java +++ b/api/src/main/java/com/cloud/storage/Volume.java @@ -30,6 +30,8 @@ import com.cloud.utils.fsm.StateObject; public interface Volume extends ControlledEntity, Identity, InternalIdentity, BasedOn, StateObject, Displayable { + static final long DISK_OFFERING_SUITABILITY_CHECK_VOLUME_ID = -1; + // Managed storage volume parameters (specified in the compute/disk offering for PowerFlex) String BANDWIDTH_LIMIT_IN_MBPS = "bandwidthLimitInMbps"; String IOPS_LIMIT = "iopsLimit"; @@ -269,11 +271,13 @@ public interface Volume extends ControlledEntity, Identity, InternalIdentity, Ba void setExternalUuid(String externalUuid); - public Long getPassphraseId(); + Long getPassphraseId(); - public void setPassphraseId(Long id); + void setPassphraseId(Long id); - public String getEncryptFormat(); + String getEncryptFormat(); - public void setEncryptFormat(String encryptFormat); + void setEncryptFormat(String encryptFormat); + + boolean isDeleteProtection(); } diff --git a/api/src/main/java/com/cloud/storage/VolumeApiService.java b/api/src/main/java/com/cloud/storage/VolumeApiService.java index 833ba442888..4182728c204 100644 --- a/api/src/main/java/com/cloud/storage/VolumeApiService.java +++ b/api/src/main/java/com/cloud/storage/VolumeApiService.java @@ -22,7 +22,12 @@ import java.net.MalformedURLException; import java.util.List; import java.util.Map; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.offering.DiskOffering; +import com.cloud.user.Account; import com.cloud.utils.Pair; +import com.cloud.utils.fsm.NoTransitionException; + import org.apache.cloudstack.api.command.user.volume.AssignVolumeCmd; import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; import org.apache.cloudstack.api.command.user.volume.ChangeOfferingForVolumeCmd; @@ -37,13 +42,9 @@ import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd; import org.apache.cloudstack.api.response.GetUploadParamsResponse; import org.apache.cloudstack.framework.config.ConfigKey; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.user.Account; -import com.cloud.utils.fsm.NoTransitionException; - public interface VolumeApiService { - ConfigKey ConcurrentMigrationsThresholdPerDatastore = new ConfigKey("Advanced" + ConfigKey ConcurrentMigrationsThresholdPerDatastore = new ConfigKey<>("Advanced" , Long.class , "concurrent.migrations.per.target.datastore" , "0" @@ -51,7 +52,7 @@ public interface VolumeApiService { , true // not sure if this is to be dynamic , ConfigKey.Scope.Global); - ConfigKey UseHttpsToUpload = new ConfigKey("Advanced", + ConfigKey UseHttpsToUpload = new ConfigKey<>("Advanced", Boolean.class, "use.https.to.upload", "true", @@ -85,7 +86,7 @@ public interface VolumeApiService { * @param cmd * the API command wrapping the criteria * @return the volume object - * @throws ResourceAllocationException + * @throws ResourceAllocationException no capacity to allocate the new volume size */ Volume resizeVolume(ResizeVolumeCmd cmd) throws ResourceAllocationException; @@ -102,8 +103,12 @@ public interface VolumeApiService { boolean deleteVolume(long volumeId, Account caller); + Volume changeDiskOfferingForVolumeInternal(Long volumeId, Long newDiskOfferingId, Long newSize, Long newMinIops, Long newMaxIops, boolean autoMigrateVolume, boolean shrinkOk) throws ResourceAllocationException; + Volume attachVolumeToVM(AttachVolumeCmd command); + Volume attachVolumeToVM(Long vmId, Long volumeId, Long deviceId, Boolean allowAttachForSharedFS); + Volume detachVolumeViaDestroyVM(long vmId, long volumeId); Volume detachVolumeFromVM(DetachVolumeCmd cmd); @@ -113,7 +118,9 @@ public interface VolumeApiService { Snapshot allocSnapshot(Long volumeId, Long policyId, String snapshotName, Snapshot.LocationType locationType, List zoneIds) throws ResourceAllocationException; - Volume updateVolume(long volumeId, String path, String state, Long storageId, Boolean displayVolume, String customId, long owner, String chainInfo, String name); + Volume updateVolume(long volumeId, String path, String state, Long storageId, + Boolean displayVolume, Boolean deleteProtection, + String customId, long owner, String chainInfo, String name); /** * Extracts the volume to a particular location. @@ -163,6 +170,14 @@ public interface VolumeApiService { * * */ + boolean doesStoragePoolSupportDiskOffering(StoragePool destPool, DiskOffering diskOffering); + + /** + * Checks if the storage pool supports the required disk offering tags + * destPool the storage pool to check the disk offering tags + * diskOfferingTags the tags that should be supported + * return whether the tags are supported in the storage pool + */ boolean doesStoragePoolSupportDiskOfferingTags(StoragePool destPool, String diskOfferingTags); Volume destroyVolume(long volumeId, Account caller, boolean expunge, boolean forceExpunge); diff --git a/api/src/main/java/com/cloud/storage/snapshot/SnapshotApiService.java b/api/src/main/java/com/cloud/storage/snapshot/SnapshotApiService.java index 0893f337ce2..67afd6aa4e2 100644 --- a/api/src/main/java/com/cloud/storage/snapshot/SnapshotApiService.java +++ b/api/src/main/java/com/cloud/storage/snapshot/SnapshotApiService.java @@ -21,6 +21,7 @@ import java.util.List; import org.apache.cloudstack.api.command.user.snapshot.CopySnapshotCmd; import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotPolicyCmd; import org.apache.cloudstack.api.command.user.snapshot.DeleteSnapshotPoliciesCmd; +import org.apache.cloudstack.api.command.user.snapshot.ExtractSnapshotCmd; import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd; import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotsCmd; import org.apache.cloudstack.api.command.user.snapshot.UpdateSnapshotPolicyCmd; @@ -106,6 +107,16 @@ public interface SnapshotApiService { */ Snapshot createSnapshot(Long volumeId, Long policyId, Long snapshotId, Account snapshotOwner); + /** + * Extracts the snapshot to a particular location. + * + * @param cmd + * the command specifying url (where the snapshot needs to be extracted to), zoneId (zone where the snapshot exists) and + * id (the id of the snapshot) + * + */ + String extractSnapshot(ExtractSnapshotCmd cmd); + /** * Archives a snapshot from primary storage to secondary storage. * @param id Snapshot ID diff --git a/api/src/main/java/com/cloud/template/VirtualMachineTemplate.java b/api/src/main/java/com/cloud/template/VirtualMachineTemplate.java index 1f8cef0365b..d8872d5fe72 100644 --- a/api/src/main/java/com/cloud/template/VirtualMachineTemplate.java +++ b/api/src/main/java/com/cloud/template/VirtualMachineTemplate.java @@ -19,6 +19,7 @@ package com.cloud.template; import java.util.Date; import java.util.Map; +import com.cloud.cpu.CPU; import com.cloud.user.UserData; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.Identity; @@ -148,4 +149,6 @@ public interface VirtualMachineTemplate extends ControlledEntity, Identity, Inte UserData.UserDataOverridePolicy getUserDataOverridePolicy(); + CPU.CPUArch getArch(); + } diff --git a/api/src/main/java/com/cloud/user/Account.java b/api/src/main/java/com/cloud/user/Account.java index 2b815531116..1cc5eae64a6 100644 --- a/api/src/main/java/com/cloud/user/Account.java +++ b/api/src/main/java/com/cloud/user/Account.java @@ -94,4 +94,8 @@ public interface Account extends ControlledEntity, InternalIdentity, Identity { boolean isDefault(); + public void setApiKeyAccess(Boolean apiKeyAccess); + + public Boolean getApiKeyAccess(); + } diff --git a/api/src/main/java/com/cloud/user/AccountService.java b/api/src/main/java/com/cloud/user/AccountService.java index 60db7abb734..c0ebcf09f59 100644 --- a/api/src/main/java/com/cloud/user/AccountService.java +++ b/api/src/main/java/com/cloud/user/AccountService.java @@ -19,6 +19,7 @@ package com.cloud.user; import java.util.List; import java.util.Map; +import com.cloud.utils.Pair; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -86,6 +87,8 @@ public interface AccountService { boolean isDomainAdmin(Long accountId); + boolean isResourceDomainAdmin(Long accountId); + boolean isNormalUser(long accountId); User getActiveUserByRegistrationToken(String registrationToken); @@ -127,9 +130,9 @@ public interface AccountService { */ UserAccount getUserAccountById(Long userId); - public Map getKeys(GetUserKeysCmd cmd); + public Pair> getKeys(GetUserKeysCmd cmd); - public Map getKeys(Long userId); + public Pair> getKeys(Long userId); /** * Lists user two-factor authentication provider plugins diff --git a/api/src/main/java/com/cloud/user/ResourceLimitService.java b/api/src/main/java/com/cloud/user/ResourceLimitService.java index f2d87a4390d..2f4ad1347be 100644 --- a/api/src/main/java/com/cloud/user/ResourceLimitService.java +++ b/api/src/main/java/com/cloud/user/ResourceLimitService.java @@ -18,13 +18,18 @@ package com.cloud.user; import java.util.List; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.framework.config.ConfigKey; + import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.ResourceCount; import com.cloud.configuration.ResourceLimit; import com.cloud.domain.Domain; import com.cloud.exception.ResourceAllocationException; -import org.apache.cloudstack.framework.config.ConfigKey; -import org.apache.cloudstack.user.ResourceReservation; +import com.cloud.offering.DiskOffering; +import com.cloud.offering.ServiceOffering; +import com.cloud.template.VirtualMachineTemplate; public interface ResourceLimitService { @@ -33,7 +38,21 @@ public interface ResourceLimitService { static final ConfigKey MaxProjectSecondaryStorage = new ConfigKey<>("Project Defaults", Long.class, "max.project.secondary.storage", "400", "The default maximum secondary storage space (in GiB) that can be used for a project", false); static final ConfigKey ResourceCountCheckInterval = new ConfigKey<>("Advanced", Long.class, "resourcecount.check.interval", "300", - "Time (in seconds) to wait before running resource recalculation and fixing task. Default is 300 seconds, Setting this to 0 disables execution of the task", false); + "Time (in seconds) to wait before running resource recalculation and fixing tasks like stale resource reservation cleanup" + + ". Default is 300 seconds, Setting this to 0 disables execution of the task", true); + static final ConfigKey ResourceReservationCleanupDelay = new ConfigKey<>("Advanced", Long.class, "resource.reservation.cleanup.delay", "3600", + "Time (in seconds) after which a resource reservation gets deleted. Default is 3600 seconds, Setting this to 0 disables execution of the task", true); + static final ConfigKey ResourceLimitHostTags = new ConfigKey<>("Advanced", String.class, "resource.limit.host.tags", "", + "A comma-separated list of tags for host resource limits", true); + static final ConfigKey ResourceLimitStorageTags = new ConfigKey<>("Advanced", String.class, "resource.limit.storage.tags", "", + "A comma-separated list of tags for storage resource limits", true); + static final ConfigKey DefaultMaxAccountProjects = new ConfigKey<>("Account Defaults",Long.class,"max.account.projects","10", + "The default maximum number of projects that can be created for an account",false); + static final ConfigKey DefaultMaxDomainProjects = new ConfigKey<>("Domain Defaults",Long.class,"max.domain.projects","50", + "The default maximum number of projects that can be created for a domain",false); + + static final List HostTagsSupportingTypes = List.of(ResourceType.user_vm, ResourceType.cpu, ResourceType.memory); + static final List StorageTagsSupportingTypes = List.of(ResourceType.volume, ResourceType.primary_storage); /** * Updates an existing resource limit with the specified details. If a limit doesn't exist, will create one. @@ -46,22 +65,27 @@ public interface ResourceLimitService { * TODO * @param max * TODO + * @param tag + * tag for the resource type * * @return the updated/created resource limit */ - ResourceLimit updateResourceLimit(Long accountId, Long domainId, Integer resourceType, Long max); + ResourceLimit updateResourceLimit(Long accountId, Long domainId, Integer resourceType, Long max, String tag); /** * Updates an existing resource count details for the account/domain * * @param accountId - * TODO + * Id of the account for which resource recalculation to be done * @param domainId - * TODO + * Id of the domain for which resource recalculation to be doneDO * @param typeId - * TODO + * type of the resource for which recalculation to be done + * @param tag + * tag for the resource type for which recalculation to be done * @return the updated/created resource counts */ + List recalculateResourceCount(Long accountId, Long domainId, Integer typeId, String tag); List recalculateResourceCount(Long accountId, Long domainId, Integer typeId); /** @@ -77,7 +101,7 @@ public interface ResourceLimitService { * TODO * @return a list of limits that match the criteria */ - public List searchForLimits(Long id, Long accountId, Long domainId, ResourceType resourceType, Long startIndex, Long pageSizeVal); + public List searchForLimits(Long id, Long accountId, Long domainId, ResourceType resourceType, String tag, Long startIndex, Long pageSizeVal); /** * Finds the resource limit for a specified account and type. If the account has an infinite limit, will check @@ -85,9 +109,10 @@ public interface ResourceLimitService { * * @param account * @param type + * @param tag * @return resource limit */ - public long findCorrectResourceLimitForAccount(Account account, ResourceType type); + public long findCorrectResourceLimitForAccount(Account account, ResourceType type, String tag); /** * This call should be used when we have already queried resource limit for an account. This is to handle @@ -105,9 +130,10 @@ public interface ResourceLimitService { * * @param domain * @param type + * @param tag * @return resource limit */ - public long findCorrectResourceLimitForDomain(Domain domain, ResourceType type); + public long findCorrectResourceLimitForDomain(Domain domain, ResourceType type, String tag); /** * Finds the default resource limit for a specified type. @@ -122,9 +148,10 @@ public interface ResourceLimitService { * * @param domain * @param type + * @param tag * @return resource limit */ - public long findCorrectResourceLimitForAccountAndDomain(Account account, Domain domain, ResourceType type); + public long findCorrectResourceLimitForAccountAndDomain(Account account, Domain domain, ResourceType type, String tag); /** * Increments the resource count @@ -134,6 +161,7 @@ public interface ResourceLimitService { * @param delta */ public void incrementResourceCount(long accountId, ResourceType type, Long... delta); + public void incrementResourceCountWithTag(long accountId, ResourceType type, String tag, Long... delta); /** * Decrements the resource count @@ -143,6 +171,7 @@ public interface ResourceLimitService { * @param delta */ public void decrementResourceCount(long accountId, ResourceType type, Long... delta); + public void decrementResourceCountWithTag(long accountId, ResourceType type, String tag, Long... delta); /** * Checks if a limit has been exceeded for an account @@ -155,15 +184,17 @@ public interface ResourceLimitService { * @throws ResourceAllocationException */ public void checkResourceLimit(Account account, ResourceCount.ResourceType type, long... count) throws ResourceAllocationException; + public void checkResourceLimitWithTag(Account account, ResourceCount.ResourceType type, String tag, long... count) throws ResourceAllocationException; /** * Gets the count of resources for a resource type and account * * @param account * @param type + * @param tag * @return count of resources */ - public long getResourceCount(Account account, ResourceType type); + public long getResourceCount(Account account, ResourceType type, String tag); /** * Checks if a limit has been exceeded for an account if displayResource flag is on @@ -208,15 +239,49 @@ public interface ResourceLimitService { */ void decrementResourceCount(long accountId, ResourceType type, Boolean displayResource, Long... delta); - /** - * Adds a reservation that will be counted in subsequent calls to {count}getResourceCount{code} until {code}this[code} - * is closed. It will create a reservation record that will be counted when resource limits are checked. - * @param account The account for which the reservation is. - * @param displayResource whether this resource is shown to users at all (if not it is not counted to limits) - * @param type resource type - * @param delta amount to reserve (will not be <+ 0) - * @return a {code}AutoClosable{Code} object representing the resource the user needs - */ - ResourceReservation getReservation(Account account, Boolean displayResource, ResourceType type, Long delta) throws ResourceAllocationException; + List getResourceLimitHostTags(); + List getResourceLimitHostTags(ServiceOffering serviceOffering, VirtualMachineTemplate template); + List getResourceLimitStorageTags(); + List getResourceLimitStorageTags(DiskOffering diskOffering); + void updateTaggedResourceLimitsAndCountsForAccounts(List responses, String tag); + void updateTaggedResourceLimitsAndCountsForDomains(List responses, String tag); + void checkVolumeResourceLimit(Account owner, Boolean display, Long size, DiskOffering diskOffering) throws ResourceAllocationException; + + void checkVolumeResourceLimitForDiskOfferingChange(Account owner, Boolean display, Long currentSize, Long newSize, + DiskOffering currentOffering, DiskOffering newOffering) throws ResourceAllocationException; + + void checkPrimaryStorageResourceLimit(Account owner, Boolean display, Long size, DiskOffering diskOffering) throws ResourceAllocationException; + + void incrementVolumeResourceCount(long accountId, Boolean display, Long size, DiskOffering diskOffering); + void decrementVolumeResourceCount(long accountId, Boolean display, Long size, DiskOffering diskOffering); + + void updateVmResourceCountForTemplateChange(long accountId, Boolean display, ServiceOffering offering, VirtualMachineTemplate currentTemplate, VirtualMachineTemplate newTemplate); + + void updateVmResourceCountForServiceOfferingChange(long accountId, Boolean display, Long currentCpu, Long newCpu, Long currentMemory, + Long newMemory, + ServiceOffering currentOffering, ServiceOffering newOffering, + VirtualMachineTemplate template); + + void updateVolumeResourceCountForDiskOfferingChange(long accountId, Boolean display, Long currentSize, Long newSize, + DiskOffering currentDiskOffering, DiskOffering newDiskOffering); + + void incrementVolumePrimaryStorageResourceCount(long accountId, Boolean display, Long size, DiskOffering diskOffering); + void decrementVolumePrimaryStorageResourceCount(long accountId, Boolean display, Long size, DiskOffering diskOffering); + void checkVmResourceLimit(Account owner, Boolean display, ServiceOffering serviceOffering, VirtualMachineTemplate template) throws ResourceAllocationException; + void incrementVmResourceCount(long accountId, Boolean display, ServiceOffering serviceOffering, VirtualMachineTemplate template); + void decrementVmResourceCount(long accountId, Boolean display, ServiceOffering serviceOffering, VirtualMachineTemplate template); + + void checkVmResourceLimitsForServiceOfferingChange(Account owner, Boolean display, Long currentCpu, Long newCpu, + Long currentMemory, Long newMemory, ServiceOffering currentOffering, ServiceOffering newOffering, VirtualMachineTemplate template) throws ResourceAllocationException; + + void checkVmResourceLimitsForTemplateChange(Account owner, Boolean display, ServiceOffering offering, + VirtualMachineTemplate currentTemplate, VirtualMachineTemplate newTemplate) throws ResourceAllocationException; + + void checkVmCpuResourceLimit(Account owner, Boolean display, ServiceOffering serviceOffering, VirtualMachineTemplate template, Long cpu) throws ResourceAllocationException; + void incrementVmCpuResourceCount(long accountId, Boolean display, ServiceOffering serviceOffering, VirtualMachineTemplate template, Long cpu); + void decrementVmCpuResourceCount(long accountId, Boolean display, ServiceOffering serviceOffering, VirtualMachineTemplate template, Long cpu); + void checkVmMemoryResourceLimit(Account owner, Boolean display, ServiceOffering serviceOffering, VirtualMachineTemplate template, Long memory) throws ResourceAllocationException; + void incrementVmMemoryResourceCount(long accountId, Boolean display, ServiceOffering serviceOffering, VirtualMachineTemplate template, Long memory); + void decrementVmMemoryResourceCount(long accountId, Boolean display, ServiceOffering serviceOffering, VirtualMachineTemplate template, Long memory); } diff --git a/api/src/main/java/com/cloud/user/User.java b/api/src/main/java/com/cloud/user/User.java index 422e264f10b..041b39ad272 100644 --- a/api/src/main/java/com/cloud/user/User.java +++ b/api/src/main/java/com/cloud/user/User.java @@ -94,4 +94,9 @@ public interface User extends OwnedBy, InternalIdentity { public boolean isUser2faEnabled(); public String getKeyFor2fa(); + + public void setApiKeyAccess(Boolean apiKeyAccess); + + public Boolean getApiKeyAccess(); + } diff --git a/api/src/main/java/com/cloud/vm/NicProfile.java b/api/src/main/java/com/cloud/vm/NicProfile.java index 183c8dcb2d5..a0c80ceb1bf 100644 --- a/api/src/main/java/com/cloud/vm/NicProfile.java +++ b/api/src/main/java/com/cloud/vm/NicProfile.java @@ -450,6 +450,9 @@ public class NicProfile implements InternalIdentity, Serializable { @Override public String toString() { - return String.format("NicProfile %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "vmId", "deviceId", "broadcastUri", "reservationId", "iPv4Address")); + return String.format("NicProfile %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "vmId", "deviceId", + "broadcastUri", "reservationId", "iPv4Address")); } } diff --git a/api/src/main/java/com/cloud/vm/UserVmService.java b/api/src/main/java/com/cloud/vm/UserVmService.java index 2fdd2592483..dc9e8c1f0d8 100644 --- a/api/src/main/java/com/cloud/vm/UserVmService.java +++ b/api/src/main/java/com/cloud/vm/UserVmService.java @@ -68,10 +68,7 @@ public interface UserVmService { /** * Destroys one virtual machine * - * @param userId - * the id of the user performing the action - * @param vmId - * the id of the virtual machine. + * @param cmd the API Command Object containg the parameters to use for this service action * @throws ConcurrentOperationException * @throws ResourceUnavailableException */ @@ -112,14 +109,14 @@ public interface UserVmService { UserVm startVirtualMachine(StartVMCmd cmd) throws StorageUnavailableException, ExecutionException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException; + UserVm rebootVirtualMachine(RebootVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ResourceAllocationException; + void startVirtualMachine(UserVm vm) throws OperationTimedoutException, ResourceUnavailableException, InsufficientCapacityException; void startVirtualMachineForHA(VirtualMachine vm, Map params, DeploymentPlanner planner) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, OperationTimedoutException; - UserVm rebootVirtualMachine(RebootVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException; - UserVm updateVirtualMachine(UpdateVMCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException; /** @@ -156,14 +153,6 @@ public interface UserVmService { * Creates a Basic Zone User VM in the database and returns the VM to the * caller. * - * - * - * @param sshKeyPair - * - name of the ssh key pair used to login to the virtual - * machine - * @param cpuSpeed - * @param memory - * @param cpuNumber * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -239,9 +228,6 @@ public interface UserVmService { * Creates a User VM in Advanced Zone (Security Group feature is enabled) in * the database and returns the VM to the caller. * - * - * - * @param type * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -317,14 +303,6 @@ public interface UserVmService { * Creates a User VM in Advanced Zone (Security Group feature is disabled) * in the database and returns the VM to the caller. * - * - * - * @param sshKeyPair - * - name of the ssh key pair used to login to the virtual - * machine - * @param cpuSpeed - * @param memory - * @param cpuNumber * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -491,14 +469,14 @@ public interface UserVmService { VirtualMachine migrateVirtualMachineWithVolume(Long vmId, Host destinationHost, Map volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException; - UserVm moveVMToUser(AssignVMCmd moveUserVMCmd) throws ResourceAllocationException, ConcurrentOperationException, ResourceUnavailableException, + UserVm moveVmToUser(AssignVMCmd moveUserVMCmd) throws ResourceAllocationException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; VirtualMachine vmStorageMigration(Long vmId, StoragePool destPool); VirtualMachine vmStorageMigration(Long vmId, Map volumeToPool); - UserVm restoreVM(RestoreVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException; + UserVm restoreVM(RestoreVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ResourceAllocationException; UserVm restoreVirtualMachine(Account caller, long vmId, Long newTemplateId, Long rootDiskOfferingId, boolean expunge, Map details) throws InsufficientCapacityException, ResourceUnavailableException; @@ -525,7 +503,31 @@ public interface UserVmService { void collectVmNetworkStatistics (UserVm userVm); - UserVm importVM(final DataCenter zone, final Host host, final VirtualMachineTemplate template, final String instanceName, final String displayName, final Account owner, final String userData, final Account caller, final Boolean isDisplayVm, final String keyboard, + /** + * Import VM into CloudStack + * @param zone importing zone + * @param host importing host + * @param template template for the imported VM + * @param instanceNameInternal set to null to CloudStack to autogenerate from the next available VM ID on database + * @param displayName display name for the imported VM + * @param owner owner of the imported VM + * @param userData user data for the imported VM + * @param caller caller account + * @param isDisplayVm true to display the imported VM + * @param keyboard keyboard distribution for the imported VM + * @param accountId account ID + * @param userId user ID + * @param serviceOffering service offering for the imported VM + * @param sshPublicKey ssh key for the imported VM + * @param hostName the name for the imported VM + * @param hypervisorType hypervisor type for the imported VM + * @param customParameters details for the imported VM + * @param powerState power state of the imported VM + * @param networkNicMap network to nic mapping + * @return the imported VM + * @throws InsufficientCapacityException in case of errors + */ + UserVm importVM(final DataCenter zone, final Host host, final VirtualMachineTemplate template, final String instanceNameInternal, final String displayName, final Account owner, final String userData, final Account caller, final Boolean isDisplayVm, final String keyboard, final long accountId, final long userId, final ServiceOffering serviceOffering, final String sshPublicKey, final String hostName, final HypervisorType hypervisorType, final Map customParameters, final VirtualMachine.PowerState powerState, final LinkedHashMap> networkNicMap) throws InsufficientCapacityException; diff --git a/api/src/main/java/com/cloud/vm/VirtualMachine.java b/api/src/main/java/com/cloud/vm/VirtualMachine.java index e7c5efb773b..e2ea408e7b8 100644 --- a/api/src/main/java/com/cloud/vm/VirtualMachine.java +++ b/api/src/main/java/com/cloud/vm/VirtualMachine.java @@ -333,6 +333,8 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Partition, */ Date getCreated(); + Date getRemoved(); + long getServiceOfferingId(); Long getBackupOfferingId(); diff --git a/api/src/main/java/com/cloud/vm/VmDetailConstants.java b/api/src/main/java/com/cloud/vm/VmDetailConstants.java index f7d87ab18f1..a6c9b6eba16 100644 --- a/api/src/main/java/com/cloud/vm/VmDetailConstants.java +++ b/api/src/main/java/com/cloud/vm/VmDetailConstants.java @@ -19,6 +19,7 @@ package com.cloud.vm; public interface VmDetailConstants { String KEYBOARD = "keyboard"; String CPU_CORE_PER_SOCKET = "cpu.corespersocket"; + String CPU_THREAD_PER_CORE = "cpu.threadspercore"; String ROOT_DISK_SIZE = "rootdisksize"; String BOOT_MODE = "boot.mode"; String NAME_ON_HYPERVISOR= "nameonhypervisor"; @@ -100,4 +101,13 @@ public interface VmDetailConstants { String VMWARE_HOST_NAME = String.format("%s-host", VMWARE_TO_KVM_PREFIX); String VMWARE_DISK = String.format("%s-disk", VMWARE_TO_KVM_PREFIX); String VMWARE_MAC_ADDRESSES = String.format("%s-mac-addresses", VMWARE_TO_KVM_PREFIX); + + // TPM + String VIRTUAL_TPM_ENABLED = "virtual.tpm.enabled"; + String VIRTUAL_TPM_MODEL = "virtual.tpm.model"; + String VIRTUAL_TPM_VERSION = "virtual.tpm.version"; + + // CPU mode and model, ADMIN only + String GUEST_CPU_MODE = "guest.cpu.mode"; + String GUEST_CPU_MODEL = "guest.cpu.model"; } diff --git a/api/src/main/java/com/cloud/vm/snapshot/VMSnapshotService.java b/api/src/main/java/com/cloud/vm/snapshot/VMSnapshotService.java index 84a56aaedd3..754e463e710 100644 --- a/api/src/main/java/com/cloud/vm/snapshot/VMSnapshotService.java +++ b/api/src/main/java/com/cloud/vm/snapshot/VMSnapshotService.java @@ -19,6 +19,7 @@ package com.cloud.vm.snapshot; import java.util.List; +import com.cloud.utils.fsm.NoTransitionException; import org.apache.cloudstack.api.command.user.vmsnapshot.ListVMSnapshotCmd; import com.cloud.exception.ConcurrentOperationException; @@ -53,4 +54,6 @@ public interface VMSnapshotService { * @param id vm id */ boolean deleteVMSnapshotsFromDB(Long vmId, boolean unmanage); + + void updateOperationFailed(VMSnapshot vmSnapshot) throws NoTransitionException; } diff --git a/api/src/main/java/org/apache/cloudstack/acl/Role.java b/api/src/main/java/org/apache/cloudstack/acl/Role.java index 5e5ffd583d8..ce4166ef4c8 100644 --- a/api/src/main/java/org/apache/cloudstack/acl/Role.java +++ b/api/src/main/java/org/apache/cloudstack/acl/Role.java @@ -21,7 +21,18 @@ import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; public interface Role extends RoleEntity, InternalIdentity, Identity { + + enum State { + ENABLED, DISABLED; + + @Override + public String toString(){ + return super.toString().toLowerCase(); + } + } + RoleType getRoleType(); boolean isDefault(); boolean isPublicRole(); + State getState(); } diff --git a/api/src/main/java/org/apache/cloudstack/acl/RoleService.java b/api/src/main/java/org/apache/cloudstack/acl/RoleService.java index 07f62a7e7f8..f041c8342ae 100644 --- a/api/src/main/java/org/apache/cloudstack/acl/RoleService.java +++ b/api/src/main/java/org/apache/cloudstack/acl/RoleService.java @@ -30,6 +30,11 @@ public interface RoleService { ConfigKey EnableDynamicApiChecker = new ConfigKey<>("Advanced", Boolean.class, "dynamic.apichecker.enabled", "false", "If set to true, this enables the dynamic role-based api access checker and disables the default static role-based api access checker.", true); + ConfigKey DynamicApiCheckerCachePeriod = new ConfigKey<>("Advanced", Integer.class, + "dynamic.apichecker.cache.period", "0", + "Defines the expiration time in seconds for the Dynamic API Checker cache, determining how long cached data is retained before being refreshed. If set to zero then caching will be disabled", + false); + boolean isEnabled(); /** @@ -54,6 +59,10 @@ public interface RoleService { boolean deleteRole(Role role); + boolean enableRole(Role role); + + boolean disableRole(Role role); + RolePermission findRolePermission(Long id); RolePermission findRolePermissionByRoleIdAndRule(Long roleId, String rule); @@ -76,7 +85,7 @@ public interface RoleService { */ List listRoles(); - Pair, Integer> listRoles(Long startIndex, Long limit); + Pair, Integer> listRoles(String state, Long startIndex, Long limit); /** * Find all roles that have the giving {@link String} as part of their name. @@ -84,14 +93,14 @@ public interface RoleService { */ List findRolesByName(String name); - Pair, Integer> findRolesByName(String name, String keyword, Long startIndex, Long limit); + Pair, Integer> findRolesByName(String name, String keyword, String state, Long startIndex, Long limit); /** * Find all roles by {@link RoleType}. If the role type is {@link RoleType#Admin}, the calling account must be a root admin, otherwise we return an empty list. */ List findRolesByType(RoleType roleType); - Pair, Integer> findRolesByType(RoleType roleType, Long startIndex, Long limit); + Pair, Integer> findRolesByType(RoleType roleType, String state, Long startIndex, Long limit); List findAllPermissionsBy(Long roleId); diff --git a/api/src/main/java/org/apache/cloudstack/acl/RoleType.java b/api/src/main/java/org/apache/cloudstack/acl/RoleType.java index ec82cd6605b..005d47c85bc 100644 --- a/api/src/main/java/org/apache/cloudstack/acl/RoleType.java +++ b/api/src/main/java/org/apache/cloudstack/acl/RoleType.java @@ -20,7 +20,8 @@ import org.apache.commons.lang3.StringUtils; import com.cloud.user.Account; import com.google.common.base.Enums; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import java.util.HashMap; import java.util.Map; @@ -37,7 +38,7 @@ public enum RoleType { private Account.Type accountType; private int mask; - private static Logger logger = Logger.getLogger(RoleType.class.getName()); + private static Logger LOGGER = LogManager.getLogger(RoleType.class.getName()); private static Map ACCOUNT_TYPE_MAP = new HashMap<>(); static { @@ -104,10 +105,10 @@ public enum RoleType { * */ public static Account.Type getAccountTypeByRole(final Role role, final Account.Type defautAccountType) { if (role != null) { - logger.debug(String.format("Role [%s] is not null; therefore, we use its account type [%s].", role, defautAccountType)); + LOGGER.debug(String.format("Role [%s] is not null; therefore, we use its account type [%s].", role, defautAccountType)); return role.getRoleType().getAccountType(); } - logger.debug(String.format("Role is null; therefore, we use the default account type [%s] value.", defautAccountType)); + LOGGER.debug(String.format("Role is null; therefore, we use the default account type [%s] value.", defautAccountType)); return defautAccountType; } } diff --git a/api/src/main/java/org/apache/cloudstack/affinity/AffinityGroupResponse.java b/api/src/main/java/org/apache/cloudstack/affinity/AffinityGroupResponse.java index 6cda8d07bd8..69f391a5656 100644 --- a/api/src/main/java/org/apache/cloudstack/affinity/AffinityGroupResponse.java +++ b/api/src/main/java/org/apache/cloudstack/affinity/AffinityGroupResponse.java @@ -25,6 +25,7 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.EntityReference; import org.apache.cloudstack.api.response.ControlledViewEntityResponse; +import org.apache.cloudstack.dedicated.DedicatedResourceResponse; import com.cloud.serializer.Param; @@ -76,6 +77,10 @@ public class AffinityGroupResponse extends BaseResponse implements ControlledVie @Param(description = "virtual machine IDs associated with this affinity group") private List vmIdList; + @SerializedName("dedicatedresources") + @Param(description = "dedicated resources associated with this affinity group") + private List dedicatedResources; + public AffinityGroupResponse() { } @@ -171,4 +176,12 @@ public class AffinityGroupResponse extends BaseResponse implements ControlledVie this.vmIdList.add(vmId); } + public void addDedicatedResource(DedicatedResourceResponse dedicatedResourceResponse) { + if (this.dedicatedResources == null) { + this.dedicatedResources = new ArrayList<>(); + } + + this.dedicatedResources.add(dedicatedResourceResponse); + } + } diff --git a/api/src/main/java/org/apache/cloudstack/api/AbstractGetUploadParamsCmd.java b/api/src/main/java/org/apache/cloudstack/api/AbstractGetUploadParamsCmd.java index ed3381ae97c..083a1be00f5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/AbstractGetUploadParamsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/AbstractGetUploadParamsCmd.java @@ -25,11 +25,9 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.GetUploadParamsResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; public abstract class AbstractGetUploadParamsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AbstractGetUploadParamsCmd.class.getName()); @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the volume/template/iso") private String name; diff --git a/api/src/main/java/org/apache/cloudstack/api/ApiArgValidator.java b/api/src/main/java/org/apache/cloudstack/api/ApiArgValidator.java index 3e06fc0e44e..38047235273 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ApiArgValidator.java +++ b/api/src/main/java/org/apache/cloudstack/api/ApiArgValidator.java @@ -32,4 +32,9 @@ public enum ApiArgValidator { * Validates if the parameter is an UUID with the method {@link UuidUtils#isUuid(String)}. */ UuidString, + + /** + * Validates if the parameter is a valid RFC Compliance domain name. + */ + RFCComplianceDomainName, } diff --git a/api/src/main/java/org/apache/cloudstack/api/ApiCommandResourceType.java b/api/src/main/java/org/apache/cloudstack/api/ApiCommandResourceType.java index 93893676516..f2f52cec969 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ApiCommandResourceType.java +++ b/api/src/main/java/org/apache/cloudstack/api/ApiCommandResourceType.java @@ -85,7 +85,8 @@ public enum ApiCommandResourceType { Bucket(org.apache.cloudstack.storage.object.Bucket.class), QuotaTariff(org.apache.cloudstack.quota.QuotaTariff.class), KubernetesCluster(null), - KubernetesSupportedVersion(null); + KubernetesSupportedVersion(null), + SharedFS(org.apache.cloudstack.storage.sharedfs.SharedFS.class); private final Class clazz; diff --git a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java index b2042c116a7..4abc0d13d74 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java +++ b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java @@ -26,13 +26,23 @@ public class ApiConstants { public static final String ACTIVATION_RULE = "activationrule"; public static final String ACTIVITY = "activity"; public static final String ADAPTER_TYPE = "adaptertype"; + public static final String ADDITONAL_CONFIG_ENABLED = "additionalconfigenabled"; public static final String ADDRESS = "address"; public static final String ALGORITHM = "algorithm"; public static final String ALIAS = "alias"; + public static final String ALLOCATED_DATE = "allocateddate"; public static final String ALLOCATED_ONLY = "allocatedonly"; + public static final String ALLOCATED_TIME = "allocated"; + public static final String ALLOW_USER_FORCE_STOP_VM = "allowuserforcestopvm"; public static final String ANNOTATION = "annotation"; public static final String API_KEY = "apikey"; + public static final String API_KEY_ACCESS = "apikeyaccess"; public static final String ARCHIVED = "archived"; + public static final String ARCH = "arch"; + public static final String AS_NUMBER = "asnumber"; + public static final String AS_NUMBER_ID = "asnumberid"; + public static final String ASN_RANGE = "asnrange"; + public static final String ASN_RANGE_ID = "asnrangeid"; public static final String ASYNC_BACKUP = "asyncbackup"; public static final String AUTO_SELECT = "autoselect"; public static final String USER_API_KEY = "userapikey"; @@ -46,6 +56,9 @@ public class ApiConstants { public static final String BACKUP_OFFERING_NAME = "backupofferingname"; public static final String BACKUP_OFFERING_ID = "backupofferingid"; public static final String BASE64_IMAGE = "base64image"; + public static final String BGP_PEERS = "bgppeers"; + public static final String BGP_PEER_IDS = "bgppeerids"; + public static final String BATCH_SIZE = "batchsize"; public static final String BITS = "bits"; public static final String BOOTABLE = "bootable"; public static final String BIND_DN = "binddn"; @@ -87,6 +100,8 @@ public class ApiConstants { public static final String DNS_SEARCH_ORDER = "dnssearchorder"; public static final String CHAIN_INFO = "chaininfo"; public static final String CIDR = "cidr"; + public static final String CIDR_SIZE = "cidrsize"; + public static final String IP6_CIDR = "ip6cidr"; public static final String CIDR_LIST = "cidrlist"; public static final String DEST_CIDR_LIST = "destcidrlist"; @@ -126,6 +141,7 @@ public class ApiConstants { public static final String DATACENTER_NAME = "datacentername"; public static final String DATADISK_OFFERING_LIST = "datadiskofferinglist"; public static final String DEFAULT_VALUE = "defaultvalue"; + public static final String DELETE_PROTECTION = "deleteprotection"; public static final String DESCRIPTION = "description"; public static final String DESTINATION = "destination"; public static final String DESTINATION_ZONE_ID = "destzoneid"; @@ -170,11 +186,14 @@ public class ApiConstants { public static final String DURATION = "duration"; public static final String ELIGIBLE = "eligible"; public static final String EMAIL = "email"; + public static final String END_ASN = "endasn"; public static final String END_DATE = "enddate"; public static final String END_IP = "endip"; public static final String END_IPV6 = "endipv6"; public static final String END_PORT = "endport"; public static final String ENTRY_TIME = "entrytime"; + public static final String EVENT_ID = "eventid"; + public static final String EVENT_TYPE = "eventtype"; public static final String EXPIRES = "expires"; public static final String EXTRA_CONFIG = "extraconfig"; public static final String EXTRA_DHCP_OPTION = "extradhcpoption"; @@ -185,6 +204,7 @@ public class ApiConstants { public static final String EXTERNAL_UUID = "externaluuid"; public static final String FENCE = "fence"; public static final String FETCH_LATEST = "fetchlatest"; + public static final String FILESYSTEM = "filesystem"; public static final String FIRSTNAME = "firstname"; public static final String FORCED = "forced"; public static final String FORCED_DESTROY_LOCAL_STORAGE = "forcedestroylocalstorage"; @@ -210,6 +230,7 @@ public class ApiConstants { public static final String HA_PROVIDER = "haprovider"; public static final String HA_STATE = "hastate"; public static final String HEALTH = "health"; + public static final String HEADERS = "headers"; public static final String HIDE_IP_ADDRESS_USAGE = "hideipaddressusage"; public static final String HOST_ID = "hostid"; public static final String HOST_IDS = "hostids"; @@ -269,6 +290,7 @@ public class ApiConstants { public static final String IS_ENCRYPTED = "isencrypted"; public static final String IS_EXTRACTABLE = "isextractable"; public static final String IS_FEATURED = "isfeatured"; + public static final String IS_IMPLICIT = "isimplicit"; public static final String IS_PORTABLE = "isportable"; public static final String IS_PUBLIC = "ispublic"; public static final String IS_PERSISTENT = "ispersistent"; @@ -284,6 +306,7 @@ public class ApiConstants { public static final String JOB_STATUS = "jobstatus"; public static final String KEEPALIVE_ENABLED = "keepaliveenabled"; public static final String KERNEL_VERSION = "kernelversion"; + public static final String KEY = "key"; public static final String LABEL = "label"; public static final String LASTNAME = "lastname"; public static final String LAST_BOOT = "lastboottime"; @@ -291,6 +314,7 @@ public class ApiConstants { public static final String LAST_SERVER_STOP = "lastserverstop"; public static final String LEVEL = "level"; public static final String LENGTH = "length"; + public static final String LIMIT = "limit"; public static final String LIMIT_CPU_USE = "limitcpuuse"; public static final String LIST_HOSTS = "listhosts"; public static final String LOCK = "lock"; @@ -308,6 +332,10 @@ public class ApiConstants { public static final String MIGRATIONS = "migrations"; public static final String MEMORY = "memory"; public static final String MODE = "mode"; + public static final String MULTI_ARCH = "ismultiarch"; + public static final String NSX_MODE = "nsxmode"; + public static final String NETWORK_MODE = "networkmode"; + public static final String NSX_ENABLED = "isnsxenabled"; public static final String NAME = "name"; public static final String METHOD_NAME = "methodname"; public static final String NETWORK_DOMAIN = "networkdomain"; @@ -327,6 +355,7 @@ public class ApiConstants { public static final String IS_DEFAULT_USE = "defaultuse"; public static final String OLD_FORMAT = "oldformat"; public static final String OP = "op"; + public static final String OPTION = "option"; public static final String OPTIONS = "options"; public static final String OS_CATEGORY_ID = "oscategoryid"; public static final String OS_CATEGORY_NAME = "oscategoryname"; @@ -346,6 +375,7 @@ public class ApiConstants { public static final String PARENT = "parent"; public static final String PARENT_ID = "parentid"; public static final String PARENT_DOMAIN_ID = "parentdomainid"; + public static final String PARENT_SUBNET = "parentsubnet"; public static final String PARENT_TEMPLATE_ID = "parenttemplateid"; public static final String PASSWORD = "password"; public static final String CURRENT_PASSWORD = "currentpassword"; @@ -354,6 +384,15 @@ public class ApiConstants { public static final String SSHKEY_ENABLED = "sshkeyenabled"; public static final String PATH = "path"; public static final String PAYLOAD = "payload"; + public static final String PAYLOAD_URL = "payloadurl"; + public static final String PEERS = "peers"; + public static final String PEER_ID = "peerid"; + public static final String PEER_NAME = "peername"; + public static final String PEER_MSID = "peermsid"; + public static final String PEER_RUNID = "peerrunid"; + public static final String PEER_SERVICE_IP = "peerserviceip"; + public static final String PEER_SERVICE_PORT = "peerserviceport"; + public static final String PEER_STATE = "peerstate"; public static final String POD_ID = "podid"; public static final String POD_NAME = "podname"; public static final String POD_IDS = "podids"; @@ -381,11 +420,13 @@ public class ApiConstants { public static final String PUBLIC_START_PORT = "publicport"; public static final String PUBLIC_END_PORT = "publicendport"; public static final String PUBLIC_ZONE = "publiczone"; + public static final String PURGE_RESOURCES = "purgeresources"; public static final String RECEIVED_BYTES = "receivedbytes"; public static final String RECONNECT = "reconnect"; public static final String RECOVER = "recover"; public static final String REPAIR = "repair"; public static final String REQUIRES_HVM = "requireshvm"; + public static final String RESOURCE_COUNT = "resourcecount"; public static final String RESOURCE_NAME = "resourcename"; public static final String RESOURCE_TYPE = "resourcetype"; public static final String RESOURCE_TYPE_NAME = "resourcetypename"; @@ -398,11 +439,9 @@ public class ApiConstants { public static final String QUERY_FILTER = "queryfilter"; public static final String SCHEDULE = "schedule"; public static final String SCOPE = "scope"; - public static final String SECRET_KEY = "usersecretkey"; - public static final String SECONDARY_IP = "secondaryip"; - public static final String SINCE = "since"; - public static final String KEY = "key"; public static final String SEARCH_BASE = "searchbase"; + public static final String SECONDARY_IP = "secondaryip"; + public static final String SECRET_KEY = "secretkey"; public static final String SECURITY_GROUP_IDS = "securitygroupids"; public static final String SECURITY_GROUP_NAMES = "securitygroupnames"; public static final String SECURITY_GROUP_NAME = "securitygroupname"; @@ -420,15 +459,18 @@ public class ApiConstants { public static final String SHOW_UNIQUE = "showunique"; public static final String SIGNATURE = "signature"; public static final String SIGNATURE_VERSION = "signatureversion"; + public static final String SINCE = "since"; public static final String SIZE = "size"; + public static final String SIZEGB = "sizegb"; public static final String SNAPSHOT = "snapshot"; public static final String SNAPSHOT_ID = "snapshotid"; public static final String SNAPSHOT_POLICY_ID = "snapshotpolicyid"; public static final String SNAPSHOT_TYPE = "snapshottype"; public static final String SNAPSHOT_QUIESCEVM = "quiescevm"; - public static final String SUPPORTS_STORAGE_SNAPSHOT = "supportsstoragesnapshot"; public static final String SOURCE_CIDR_LIST = "sourcecidrlist"; public static final String SOURCE_ZONE_ID = "sourcezoneid"; + public static final String SSL_VERIFICATION = "sslverification"; + public static final String START_ASN = "startasn"; public static final String START_DATE = "startdate"; public static final String START_ID = "startid"; public static final String START_IP = "startip"; @@ -448,6 +490,9 @@ public class ApiConstants { public static final String SYSTEM_VM_TYPE = "systemvmtype"; public static final String TAGS = "tags"; public static final String STORAGE_TAGS = "storagetags"; + public static final String SUCCESS = "success"; + public static final String SUITABLE_FOR_VM = "suitableforvirtualmachine"; + public static final String SUPPORTS_STORAGE_SNAPSHOT = "supportsstoragesnapshot"; public static final String TARGET_IQN = "targetiqn"; public static final String TEMPLATE_FILTER = "templatefilter"; public static final String TEMPLATE_ID = "templateid"; @@ -458,6 +503,7 @@ public class ApiConstants { public static final String TIMEOUT = "timeout"; public static final String TIMEZONE = "timezone"; public static final String TIMEZONEOFFSET = "timezoneoffset"; + public static final String TOTAL = "total"; public static final String TOTAL_SUBNETS = "totalsubnets"; public static final String TYPE = "type"; public static final String TRUST_STORE = "truststore"; @@ -465,6 +511,7 @@ public class ApiConstants { public static final String URL = "url"; public static final String USAGE_INTERFACE = "usageinterface"; public static final String USED_SUBNETS = "usedsubnets"; + public static final String USED_IOPS = "usediops"; public static final String USER_DATA = "userdata"; public static final String USER_DATA_NAME = "userdataname"; @@ -480,6 +527,7 @@ public class ApiConstants { public static final String USERNAME = "username"; public static final String USER_CONFIGURABLE = "userconfigurable"; public static final String USER_SECURITY_GROUP_LIST = "usersecuritygrouplist"; + public static final String USER_SECRET_KEY = "usersecretkey"; public static final String USE_VIRTUAL_NETWORK = "usevirtualnetwork"; public static final String UPDATE_IN_SEQUENCE = "updateinsequence"; public static final String VALUE = "value"; @@ -489,6 +537,7 @@ public class ApiConstants { public static final String VIRTUAL_MACHINE_ID_IP = "vmidipmap"; public static final String VIRTUAL_MACHINE_COUNT = "virtualmachinecount"; public static final String VIRTUAL_MACHINE_TYPE = "virtualmachinetype"; + public static final String VIRTUAL_MACHINE_STATE = "vmstate"; public static final String VIRTUAL_MACHINES = "virtualmachines"; public static final String USAGE_ID = "usageid"; public static final String USAGE_TYPE = "usagetype"; @@ -501,6 +550,7 @@ public class ApiConstants { public static final String ISOLATED_PVLAN = "isolatedpvlan"; public static final String ISOLATED_PVLAN_TYPE = "isolatedpvlantype"; public static final String ISOLATION_URI = "isolationuri"; + public static final String IS_ALLOCATED = "isallocated"; public static final String IS_DEDICATED = "isdedicated"; public static final String TAKEN = "taken"; public static final String VM_AVAILABLE = "vmavailable"; @@ -529,6 +579,7 @@ public class ApiConstants { public static final String NETWORK_ID = "networkid"; public static final String NETWORK_FILTER = "networkfilter"; public static final String NIC_ID = "nicid"; + public static final String SPECIFY_AS_NUMBER = "specifyasnumber"; public static final String SPECIFY_VLAN = "specifyvlan"; public static final String IS_DEFAULT = "isdefault"; public static final String IS_SYSTEM = "issystem"; @@ -559,6 +610,7 @@ public class ApiConstants { public static final String ALLOCATION_STATE = "allocationstate"; public static final String MANAGED_STATE = "managedstate"; public static final String MANAGEMENT_SERVER_ID = "managementserverid"; + public static final String MANAGEMENT_SERVER_NAME = "managementservername"; public static final String STORAGE = "storage"; public static final String STORAGE_ID = "storageid"; public static final String PING_STORAGE_SERVER_IP = "pingstorageserverip"; @@ -669,6 +721,8 @@ public class ApiConstants { public static final String ASSOCIATED_NETWORK = "associatednetwork"; public static final String ASSOCIATED_NETWORK_ID = "associatednetworkid"; public static final String ASSOCIATED_NETWORK_NAME = "associatednetworkname"; + public static final String ASSOCIATED_VPC_ID = "associatedvpcid"; + public static final String ASSOCIATED_VPC_NAME = "associatedvpcname"; public static final String SOURCE_NAT_SUPPORTED = "sourcenatsupported"; public static final String RESOURCE_STATE = "resourcestate"; public static final String PROJECT_INVITE_REQUIRED = "projectinviterequired"; @@ -681,8 +735,11 @@ public class ApiConstants { public static final String TRAFFIC_TYPE_IMPLEMENTOR = "traffictypeimplementor"; public static final String KEYWORD = "keyword"; public static final String LIST_ALL = "listall"; + public static final String LIST_ONLY_REMOVED = "listonlyremoved"; public static final String LIST_SYSTEM_VMS = "listsystemvms"; public static final String IP_RANGES = "ipranges"; + public static final String IPV4_ROUTING = "ip4routing"; + public static final String IPV4_ROUTES = "ip4routes"; public static final String IPV6_ROUTING = "ip6routing"; public static final String IPV6_ROUTES = "ip6routes"; public static final String SPECIFY_IP_RANGES = "specifyipranges"; @@ -710,6 +767,12 @@ public class ApiConstants { public static final String VSWITCH_TYPE_PUBLIC_TRAFFIC = "publicvswitchtype"; public static final String VSWITCH_NAME_GUEST_TRAFFIC = "guestvswitchname"; public static final String VSWITCH_NAME_PUBLIC_TRAFFIC = "publicvswitchname"; + + // NSX + public static final String EDGE_CLUSTER = "edgecluster"; + public static final String TIER0_GATEWAY = "tier0gateway"; + + public static final String TRANSPORT_ZONE = "transportzone"; // Tungsten-Fabric public static final String TUNGSTEN_VIRTUAL_ROUTER_UUID = "tungstenvirtualrouteruuid"; public static final String TUNGSTEN_PROVIDER_HOSTNAME = "tungstenproviderhostname"; @@ -733,6 +796,7 @@ public class ApiConstants { public static final String POLICY_UUID = "policyuuid"; public static final String RULE_UUID = "ruleuuid"; public static final String DIRECTION = "direction"; + public static final String TAGGED_RESOURCES = "taggedresources"; public static final String TAG_UUID = "taguuid"; public static final String TAG_TYPE = "tagtype"; public static final String TAG_VALUE = "tagvalue"; @@ -830,6 +894,9 @@ public class ApiConstants { public static final String FORCE_ENCAP = "forceencap"; public static final String SPLIT_CONNECTIONS = "splitconnections"; public static final String FOR_VPC = "forvpc"; + public static final String FOR_NSX = "fornsx"; + public static final String NSX_SUPPORT_LB = "nsxsupportlb"; + public static final String NSX_SUPPORTS_INTERNAL_LB = "nsxsupportsinternallb"; public static final String FOR_TUNGSTEN = "fortungsten"; public static final String SHRINK_OK = "shrinkok"; public static final String NICIRA_NVP_DEVICE_ID = "nvpdeviceid"; @@ -839,6 +906,11 @@ public class ApiConstants { public static final String NICIRA_NVP_L2_GATEWAYSERVICE_UUID = "l2gatewayserviceuuid"; public static final String NSX_LOGICAL_SWITCH = "nsxlogicalswitch"; public static final String NSX_LOGICAL_SWITCH_PORT = "nsxlogicalswitchport"; + public static final String NSX_PROVIDER_UUID = "nsxprovideruuid"; + public static final String NSX_PROVIDER_HOSTNAME = "nsxproviderhostname"; + + public static final String NSX_PROVIDER_PORT = "nsxproviderport"; + public static final String NSX_CONTROLLER_ID = "nsxcontrollerid"; public static final String S3_ACCESS_KEY = "accesskey"; public static final String S3_SECRET_KEY = "secretkey"; public static final String S3_END_POINT = "endpoint"; @@ -927,7 +999,9 @@ public class ApiConstants { public static final String ACL_NAME = "aclname"; public static final String NUMBER = "number"; public static final String IS_DYNAMICALLY_SCALABLE = "isdynamicallyscalable"; + public static final String ROUTED_MODE_ENABLED = "routedmodeenabled"; public static final String ROUTING = "isrouting"; + public static final String ROUTING_MODE = "routingmode"; public static final String MAX_CONNECTIONS = "maxconnections"; public static final String SERVICE_STATE = "servicestate"; @@ -963,6 +1037,7 @@ public class ApiConstants { public static final String SUPPORTS_REGION_LEVEL_VPC = "supportsregionLevelvpc"; public static final String SUPPORTS_STRECHED_L2_SUBNET = "supportsstrechedl2subnet"; public static final String SUPPORTS_PUBLIC_ACCESS = "supportspublicaccess"; + public static final String SUPPORTS_INTERNAL_LB = "supportsinternallb"; public static final String SUPPORTS_VM_AUTOSCALING = "supportsvmautoscaling"; public static final String REGION_LEVEL_VPC = "regionlevelvpc"; public static final String STRECHED_L2_SUBNET = "strechedl2subnet"; @@ -1081,14 +1156,13 @@ public class ApiConstants { public static final String SOURCE_NAT_IP = "sourcenatipaddress"; public static final String SOURCE_NAT_IP_ID = "sourcenatipaddressid"; public static final String HAS_RULES = "hasrules"; + public static final String NSX_DETAIL_KEY = "forNsx"; public static final String DISK_PATH = "diskpath"; public static final String IMPORT_SOURCE = "importsource"; public static final String TEMP_PATH = "temppath"; public static final String OBJECT_STORAGE = "objectstore"; - public static final String HEURISTIC_RULE = "heuristicrule"; public static final String HEURISTIC_TYPE_VALID_OPTIONS = "Valid options are: ISO, SNAPSHOT, TEMPLATE and VOLUME."; - public static final String MANAGEMENT = "management"; public static final String IS_VNF = "isvnf"; public static final String VNF_NICS = "vnfnics"; @@ -1105,7 +1179,20 @@ public class ApiConstants { public static final String PARAMETER_DESCRIPTION_IS_TAG_A_RULE = "Whether the informed tag is a JS interpretable rule or not."; + public static final String WEBHOOK_ID = "webhookid"; + public static final String WEBHOOK_NAME = "webhookname"; + public static final String NFS_MOUNT_OPTIONS = "nfsmountopts"; + public static final String MOUNT_OPTIONS = "mountopts"; + + public static final String SHAREDFSVM_MIN_CPU_COUNT = "sharedfsvmmincpucount"; + public static final String SHAREDFSVM_MIN_RAM_SIZE = "sharedfsvmminramsize"; + + public static final String PARAMETER_DESCRIPTION_ACTIVATION_RULE = "Quota tariff's activation rule. It can receive a JS script that results in either " + + "a boolean or a numeric value: if it results in a boolean value, the tariff value will be applied according to the result; if it results in a numeric value, the " + + "numeric value will be applied; if the result is neither a boolean nor a numeric value, the tariff will not be applied. If the rule is not informed, the tariff " + + "value will be applied."; + public static final String VMWARE_DC = "vmwaredc"; /** * This enum specifies IO Drivers, each option controls specific policies on I/O. @@ -1129,6 +1216,14 @@ public class ApiConstants { } } + public static final String PARAMETER_DESCRIPTION_START_DATE_POSSIBLE_FORMATS = "The recommended format is \"yyyy-MM-dd'T'HH:mm:ssZ\" (e.g.: \"2023-01-01T12:00:00+0100\"); " + + "however, the following formats are also accepted: \"yyyy-MM-dd HH:mm:ss\" (e.g.: \"2023-01-01 12:00:00\") and \"yyyy-MM-dd\" (e.g.: \"2023-01-01\" - if the time is not " + + "added, it will be interpreted as \"00:00:00\"). If the recommended format is not used, the date will be considered in the server timezone."; + + public static final String PARAMETER_DESCRIPTION_END_DATE_POSSIBLE_FORMATS = "The recommended format is \"yyyy-MM-dd'T'HH:mm:ssZ\" (e.g.: \"2023-01-01T12:00:00+0100\"); " + + "however, the following formats are also accepted: \"yyyy-MM-dd HH:mm:ss\" (e.g.: \"2023-01-01 12:00:00\") and \"yyyy-MM-dd\" (e.g.: \"2023-01-01\" - if the time is not " + + "added, it will be interpreted as \"23:59:59\"). If the recommended format is not used, the date will be considered in the server timezone."; + public enum BootType { UEFI, BIOS; @@ -1158,4 +1253,30 @@ public class ApiConstants { public enum DomainDetails { all, resource, min; } + + public enum ApiKeyAccess { + DISABLED(false), + ENABLED(true), + INHERIT(null); + + Boolean apiKeyAccess; + + ApiKeyAccess(Boolean keyAccess) { + apiKeyAccess = keyAccess; + } + + public Boolean toBoolean() { + return apiKeyAccess; + } + + public static ApiKeyAccess fromBoolean(Boolean value) { + if (value == null) { + return INHERIT; + } else if (value) { + return ENABLED; + } else { + return DISABLED; + } + } + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/ApiServerService.java b/api/src/main/java/org/apache/cloudstack/api/ApiServerService.java index 54fda7e36b8..cbbcdc3bda4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ApiServerService.java +++ b/api/src/main/java/org/apache/cloudstack/api/ApiServerService.java @@ -21,7 +21,9 @@ import java.util.Map; import javax.servlet.http.HttpSession; +import com.cloud.domain.Domain; import com.cloud.exception.CloudAuthenticationException; +import com.cloud.user.UserAccount; public interface ApiServerService { public boolean verifyRequest(Map requestParameters, Long userId, InetAddress remoteAddress) throws ServerApiException; @@ -42,4 +44,8 @@ public interface ApiServerService { public String handleRequest(Map params, String responseType, StringBuilder auditTrailSb) throws ServerApiException; public Class getCmdClass(String cmdName); + + boolean forgotPassword(UserAccount userAccount, Domain domain); + + boolean resetPassword(UserAccount userAccount, String token, String password); } diff --git a/api/src/main/java/org/apache/cloudstack/api/BaseAsyncCmd.java b/api/src/main/java/org/apache/cloudstack/api/BaseAsyncCmd.java index 865ec745640..6859b0a7f40 100644 --- a/api/src/main/java/org/apache/cloudstack/api/BaseAsyncCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/BaseAsyncCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api; -import org.apache.log4j.Logger; /** * queryAsyncJobResult API command. @@ -30,7 +29,6 @@ public abstract class BaseAsyncCmd extends BaseCmd { public static final String migrationSyncObject = "migration"; public static final String snapshotHostSyncObject = "snapshothost"; public static final String gslbSyncObject = "globalserverloadbalancer"; - private static final Logger s_logger = Logger.getLogger(BaseAsyncCmd.class.getName()); private Object job; diff --git a/api/src/main/java/org/apache/cloudstack/api/BaseCmd.java b/api/src/main/java/org/apache/cloudstack/api/BaseCmd.java index f32922819b0..457afdc8847 100644 --- a/api/src/main/java/org/apache/cloudstack/api/BaseCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/BaseCmd.java @@ -31,6 +31,7 @@ import java.util.regex.Pattern; import javax.inject.Inject; +import com.cloud.bgp.BGPService; import org.apache.cloudstack.acl.ProjectRoleService; import org.apache.cloudstack.acl.RoleService; import org.apache.cloudstack.acl.RoleType; @@ -38,7 +39,7 @@ import org.apache.cloudstack.affinity.AffinityGroupService; import org.apache.cloudstack.alert.AlertService; import org.apache.cloudstack.annotation.AnnotationService; import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.network.element.InternalLoadBalancerElementService; +import org.apache.cloudstack.network.RoutedIpv4Manager; import org.apache.cloudstack.network.lb.ApplicationLoadBalancerService; import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService; import org.apache.cloudstack.query.QueryService; @@ -47,7 +48,8 @@ import org.apache.cloudstack.storage.ImageStoreService; import org.apache.cloudstack.storage.template.VnfTemplateManager; import org.apache.cloudstack.usage.UsageService; import org.apache.commons.collections.MapUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.configuration.ConfigurationService; import com.cloud.exception.ConcurrentOperationException; @@ -95,7 +97,7 @@ import com.cloud.vm.UserVmService; import com.cloud.vm.snapshot.VMSnapshotService; public abstract class BaseCmd { - private static final Logger s_logger = Logger.getLogger(BaseCmd.class.getName()); + protected transient Logger logger = LogManager.getLogger(getClass()); public static final String RESPONSE_SUFFIX = "response"; public static final String RESPONSE_TYPE_XML = HttpUtils.RESPONSE_TYPE_XML; public static final String RESPONSE_TYPE_JSON = HttpUtils.RESPONSE_TYPE_JSON; @@ -200,8 +202,6 @@ public abstract class BaseCmd { @Inject public AffinityGroupService _affinityGroupService; @Inject - public InternalLoadBalancerElementService _internalLbElementSvc; - @Inject public InternalLoadBalancerVMService _internalLbSvc; @Inject public NetworkModel _ntwkModel; @@ -219,7 +219,11 @@ public abstract class BaseCmd { public VnfTemplateManager vnfTemplateManager; @Inject public BucketApiService _bucketService; + @Inject + public BGPService bgpService; + @Inject + public RoutedIpv4Manager routedIpv4Manager; public abstract void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException; @@ -374,7 +378,7 @@ public abstract class BaseCmd { if (roleIsAllowed) { validFields.add(field); } else { - s_logger.debug("Ignoring parameter " + parameterAnnotation.name() + " as the caller is not authorized to pass it in"); + logger.debug("Ignoring parameter " + parameterAnnotation.name() + " as the caller is not authorized to pass it in"); } } @@ -419,7 +423,7 @@ public abstract class BaseCmd { if(!isDisplay) break; } catch (Exception e){ - s_logger.trace("Caught exception while checking first class entities for display property, continuing on", e); + logger.trace("Caught exception while checking first class entities for display property, continuing on", e); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java index 052d7d1e8b7..be95547a8a7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.ResponseObject.ResponseView; import org.apache.cloudstack.api.command.ResponseViewProvider; @@ -28,7 +27,6 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; public abstract class BaseListTemplateOrIsoPermissionsCmd extends BaseCmd implements ResponseViewProvider { - public Logger logger = getLogger(); protected static final String s_name = "listtemplatepermissionsresponse"; ///////////////////////////////////////////////////// @@ -59,9 +57,6 @@ public abstract class BaseListTemplateOrIsoPermissionsCmd extends BaseCmd implem return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - protected Logger getLogger() { - return Logger.getLogger(BaseListTemplateOrIsoPermissionsCmd.class); - } @Override public String getCommandName() { diff --git a/api/src/main/java/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java b/api/src/main/java/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java index 08f390f1972..9a8282df112 100644 --- a/api/src/main/java/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java @@ -16,15 +16,15 @@ // under the License. package org.apache.cloudstack.api; -import org.apache.log4j.Logger; +import com.cloud.cpu.CPU; import org.apache.cloudstack.api.response.GuestOSResponse; import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.commons.lang3.StringUtils; import java.util.Collection; import java.util.Map; public abstract class BaseUpdateTemplateOrIsoCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(BaseUpdateTemplateOrIsoCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -79,6 +79,11 @@ public abstract class BaseUpdateTemplateOrIsoCmd extends BaseCmd { description = "optional boolean field, which indicates if details should be cleaned up or not (if set to true, details removed for this resource, details field ignored; if false or not set, no action)") private Boolean cleanupDetails; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "the CPU arch of the template/ISO. Valid options are: x86_64, aarch64", + since = "4.20") + private String arch; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -143,4 +148,11 @@ public abstract class BaseUpdateTemplateOrIsoCmd extends BaseCmd { public boolean isCleanupDetails(){ return cleanupDetails == null ? false : cleanupDetails.booleanValue(); } + + public CPU.CPUArch getCPUArch() { + if (StringUtils.isBlank(arch)) { + return null; + } + return CPU.CPUArch.fromType(arch); + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java index 410ffefb00d..e6ee0897db0 100644 --- a/api/src/main/java/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.SuccessResponse; @@ -27,16 +26,12 @@ import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.exception.InvalidParameterValueException; public abstract class BaseUpdateTemplateOrIsoPermissionsCmd extends BaseCmd { - public Logger _logger = getLogger(); protected String _name = getResponseName(); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - protected Logger getLogger() { - return Logger.getLogger(BaseUpdateTemplateOrIsoPermissionsCmd.class); - } protected String getResponseName() { return "updatetemplateorisopermissionsresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/ResponseGenerator.java b/api/src/main/java/org/apache/cloudstack/api/ResponseGenerator.java index ef759aaf9c3..ea0d946ee41 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ResponseGenerator.java +++ b/api/src/main/java/org/apache/cloudstack/api/ResponseGenerator.java @@ -22,6 +22,9 @@ import java.util.List; import java.util.Map; import java.util.Set; +import com.cloud.bgp.ASNumber; +import com.cloud.bgp.ASNumberRange; + import org.apache.cloudstack.storage.object.Bucket; import org.apache.cloudstack.affinity.AffinityGroup; import org.apache.cloudstack.affinity.AffinityGroupResponse; @@ -31,11 +34,14 @@ import org.apache.cloudstack.api.ResponseObject.ResponseView; import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.ApplicationLoadBalancerResponse; +import org.apache.cloudstack.api.response.ASNRangeResponse; +import org.apache.cloudstack.api.response.ASNumberResponse; import org.apache.cloudstack.api.response.AsyncJobResponse; import org.apache.cloudstack.api.response.AutoScalePolicyResponse; import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; import org.apache.cloudstack.api.response.BackupOfferingResponse; +import org.apache.cloudstack.api.response.BackupRepositoryResponse; import org.apache.cloudstack.api.response.BackupResponse; import org.apache.cloudstack.api.response.BackupScheduleResponse; import org.apache.cloudstack.api.response.BucketResponse; @@ -54,6 +60,7 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.ExtractResponse; +import org.apache.cloudstack.api.response.SharedFSResponse; import org.apache.cloudstack.api.response.FirewallResponse; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.GlobalLoadBalancerResponse; @@ -139,6 +146,7 @@ import org.apache.cloudstack.api.response.VpnUsersResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.backup.Backup; import org.apache.cloudstack.backup.BackupOffering; +import org.apache.cloudstack.backup.BackupRepository; import org.apache.cloudstack.backup.BackupSchedule; import org.apache.cloudstack.config.Configuration; import org.apache.cloudstack.config.ConfigurationGroup; @@ -151,6 +159,7 @@ import org.apache.cloudstack.region.PortableIp; import org.apache.cloudstack.region.PortableIpRange; import org.apache.cloudstack.region.Region; import org.apache.cloudstack.secstorage.heuristics.Heuristic; +import org.apache.cloudstack.storage.sharedfs.SharedFS; import org.apache.cloudstack.storage.object.ObjectStore; import org.apache.cloudstack.usage.Usage; @@ -345,9 +354,11 @@ public interface ResponseGenerator { SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group); - ExtractResponse createExtractResponse(Long uploadId, Long id, Long zoneId, Long accountId, String mode, String url); + ExtractResponse createImageExtractResponse(Long id, Long zoneId, Long accountId, String mode, String url); - ExtractResponse createExtractResponse(Long id, Long zoneId, Long accountId, String mode, String url); + ExtractResponse createVolumeExtractResponse(Long id, Long zoneId, Long accountId, String mode, String url); + + ExtractResponse createSnapshotExtractResponse(Long id, Long zoneId, Long accountId, String url); String toSerializedString(CreateCmdResponse response, String responseType); @@ -549,4 +560,12 @@ public interface ResponseGenerator { ObjectStoreResponse createObjectStoreResponse(ObjectStore os); BucketResponse createBucketResponse(Bucket bucket); + + ASNRangeResponse createASNumberRangeResponse(ASNumberRange asnRange); + + ASNumberResponse createASNumberResponse(ASNumber asn); + + BackupRepositoryResponse createBackupRepositoryResponse(BackupRepository repository); + + SharedFSResponse createSharedFSResponse(ResponseView view, SharedFS sharedFS); } diff --git a/api/src/main/java/org/apache/cloudstack/api/auth/APIAuthenticationType.java b/api/src/main/java/org/apache/cloudstack/api/auth/APIAuthenticationType.java index 5ba9d182daa..1f78708f7e5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/auth/APIAuthenticationType.java +++ b/api/src/main/java/org/apache/cloudstack/api/auth/APIAuthenticationType.java @@ -17,5 +17,5 @@ package org.apache.cloudstack.api.auth; public enum APIAuthenticationType { - LOGIN_API, LOGOUT_API, READONLY_API, LOGIN_2FA_API + LOGIN_API, LOGOUT_API, READONLY_API, LOGIN_2FA_API, PASSWORD_RESET } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java index 945bb956c3e..6dbc6acc59a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java @@ -21,7 +21,6 @@ import java.util.Map; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -43,7 +42,6 @@ import com.cloud.user.UserAccount; @APICommand(name = "createAccount", description = "Creates an account", responseObject = AccountResponse.class, entityType = {Account.class}, requestHasSensitiveInfo = true, responseHasSensitiveInfo = true) public class CreateAccountCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateAccountCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java index 9a0ea4e9ec0..a90fc4aebe9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java @@ -31,7 +31,6 @@ import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.region.RegionService; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.user.Account; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteAccount", description = "Deletes a account, and all users associated with this account", responseObject = SuccessResponse.class, entityType = {Account.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteAccountCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteAccountCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -91,12 +89,11 @@ public class DeleteAccountCmd extends BaseAsyncCmd { CallContext.current().setEventDetails("Account ID: " + (account != null ? account.getUuid() : getId())); // Account not found is already handled by service boolean result = _regionService.deleteUserAccount(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - setResponseObject(response); - } else { + if (!result) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete user account and all corresponding users"); } + SuccessResponse response = new SuccessResponse(getCommandName()); + setResponseObject(response); } @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java index 91b0673e186..55293eca619 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.account; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -43,7 +42,6 @@ import com.cloud.user.Account; @APICommand(name = "disableAccount", description = "Disables an account", responseObject = AccountResponse.class, entityType = {Account.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class DisableAccountCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DisableAccountCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java index cc37dc23713..da96383f134 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.account; import javax.inject.Inject; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "enableAccount", description = "Enables an account", responseObject = AccountResponse.class, entityType = {Account.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class EnableAccountCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(EnableAccountCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java index a430914a25a..d7847373e92 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.account; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.utils.exception.CloudRuntimeException; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class LockAccountCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(LockAccountCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java index 36d299bcfc8..3347a0d09f3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java @@ -21,9 +21,10 @@ import java.util.Map; import javax.inject.Inject; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.ApiCommandResourceType; +import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.RoleResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -41,9 +42,8 @@ import org.apache.cloudstack.region.RegionService; import com.cloud.user.Account; @APICommand(name = "updateAccount", description = "Updates account information for the authenticated user", responseObject = AccountResponse.class, entityType = {Account.class}, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) -public class UpdateAccountCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateAccountCmd.class.getName()); + responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) +public class UpdateAccountCmd extends BaseCmd implements UserCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -72,6 +72,9 @@ public class UpdateAccountCmd extends BaseCmd { @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "Details for the account used to store specific parameters") private Map details; + @Parameter(name = ApiConstants.API_KEY_ACCESS, type = CommandType.STRING, description = "Determines if Api key access for this user is enabled, disabled or inherits the value from its parent, the domain level setting api.key.access", since = "4.20.1.0", authorized = {RoleType.Admin}) + private String apiKeyAccess; + @Inject RegionService _regionService; @@ -111,6 +114,10 @@ public class UpdateAccountCmd extends BaseCmd { return params; } + public String getApiKeyAccess() { + return apiKeyAccess; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -133,7 +140,7 @@ public class UpdateAccountCmd extends BaseCmd { public void execute() { Account result = _regionService.updateAccount(this); if (result != null){ - AccountResponse response = _responseGenerator.createAccountResponse(ResponseView.Full, result); + AccountResponse response = _responseGenerator.createAccountResponse(getResponseView(), result); response.setResponseName(getCommandName()); setResponseObject(response); } else { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/DisableRoleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/DisableRoleCmd.java new file mode 100644 index 00000000000..80cb92c8362 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/DisableRoleCmd.java @@ -0,0 +1,69 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.acl; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import org.apache.cloudstack.acl.Role; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiArgValidator; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.RoleResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.context.CallContext; + +@APICommand(name = "disableRole", description = "Disables a role", responseObject = SuccessResponse.class, + requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin}) +public class DisableRoleCmd extends BaseCmd { + + @Parameter(name = ApiConstants.ID, type = BaseCmd.CommandType.UUID, required = true, entityType = RoleResponse.class, + description = "ID of the role", validations = {ApiArgValidator.PositiveNumber}) + private Long roleId; + + public Long getRoleId() { + return roleId; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { + Role role = roleService.findRole(getRoleId()); + if (role == null) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Cannot find the role with provided id"); + } + CallContext.current().setEventDetails("Role id: " + role.getId()); + boolean result = roleService.disableRole(role); + SuccessResponse response = new SuccessResponse(getCommandName()); + response.setSuccess(result); + setResponseObject(response); + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/EnableRoleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/EnableRoleCmd.java new file mode 100644 index 00000000000..c4a6505d52f --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/EnableRoleCmd.java @@ -0,0 +1,69 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.acl; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import org.apache.cloudstack.acl.Role; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiArgValidator; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.RoleResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.context.CallContext; + +@APICommand(name = "enableRole", description = "Enables a role", responseObject = SuccessResponse.class, + requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin}) +public class EnableRoleCmd extends BaseCmd { + + @Parameter(name = ApiConstants.ID, type = BaseCmd.CommandType.UUID, required = true, entityType = RoleResponse.class, + description = "ID of the role", validations = {ApiArgValidator.PositiveNumber}) + private Long roleId; + + public Long getRoleId() { + return roleId; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { + Role role = roleService.findRole(getRoleId()); + if (role == null) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Cannot find the role with provided id"); + } + CallContext.current().setEventDetails("Role id: " + role.getId()); + boolean result = roleService.enableRole(role); + SuccessResponse response = new SuccessResponse(getCommandName()); + response.setSuccess(result); + setResponseObject(response); + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/ListRolesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/ListRolesCmd.java index fef2b27eaa5..d82cc852e4f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/ListRolesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/ListRolesCmd.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import com.cloud.exception.InvalidParameterValueException; import org.apache.cloudstack.acl.Role; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -51,6 +52,9 @@ public class ListRolesCmd extends BaseListCmd { @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, description = "List role by role type, valid options are: Admin, ResourceAdmin, DomainAdmin, User.") private String roleType; + @Parameter(name = ApiConstants.STATE, type = CommandType.STRING, description = "List role by role type status, valid options are: enabled, disabled") + private String roleState; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -70,6 +74,17 @@ public class ListRolesCmd extends BaseListCmd { return null; } + public Role.State getRoleState() { + if (roleState == null) { + return null; + } + try { + return Role.State.valueOf(roleState.toUpperCase()); + } catch (IllegalArgumentException e) { + throw new InvalidParameterValueException("Unrecognized role state value"); + } + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -93,6 +108,7 @@ public class ListRolesCmd extends BaseListCmd { roleResponse.setDescription(role.getDescription()); roleResponse.setIsDefault(role.isDefault()); roleResponse.setPublicRole(role.isPublicRole()); + roleResponse.setState(role.getState().toString()); roleResponse.setObjectName("role"); roleResponses.add(roleResponse); } @@ -104,14 +120,16 @@ public class ListRolesCmd extends BaseListCmd { @Override public void execute() { Pair, Integer> roles; + Role.State state = getRoleState(); + String roleStateStr = state != null ? state.toString() : null; if (getId() != null && getId() > 0L) { roles = new Pair<>(Collections.singletonList(roleService.findRole(getId(), true)), 1); } else if (StringUtils.isNotBlank(getName()) || StringUtils.isNotBlank(getKeyword())) { - roles = roleService.findRolesByName(getName(), getKeyword(), getStartIndex(), getPageSizeVal()); + roles = roleService.findRolesByName(getName(), getKeyword(), roleStateStr, getStartIndex(), getPageSizeVal()); } else if (getRoleType() != null) { - roles = roleService.findRolesByType(getRoleType(), getStartIndex(), getPageSizeVal()); + roles = roleService.findRolesByType(getRoleType(), roleStateStr, getStartIndex(), getPageSizeVal()); } else { - roles = roleService.listRoles(getStartIndex(), getPageSizeVal()); + roles = roleService.listRoles(roleStateStr, getStartIndex(), getPageSizeVal()); } setupResponse(roles); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/RoleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/RoleCmd.java index 4c317d06b13..b3d816adc3f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/RoleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/RoleCmd.java @@ -59,6 +59,7 @@ public abstract class RoleCmd extends BaseCmd { response.setRoleType(role.getRoleType()); response.setDescription(role.getDescription()); response.setPublicRole(role.isPublicRole()); + response.setState(role.getState().toString()); response.setResponseName(getCommandName()); response.setObjectName("role"); setResponseObject(response); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/project/ListProjectRolesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/project/ListProjectRolesCmd.java index e876dbc9b58..dedbb410ea5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/project/ListProjectRolesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/acl/project/ListProjectRolesCmd.java @@ -72,7 +72,7 @@ public class ListProjectRolesCmd extends BaseListCmd { @Override public void execute() { - List projectRoles; + List projectRoles = new ArrayList<>(); if (getProjectId() != null && getProjectRoleId() != null) { projectRoles = Collections.singletonList(projRoleService.findProjectRole(getProjectRoleId(), getProjectId())); } else if (StringUtils.isNotBlank(getRoleName())) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/address/AcquirePodIpCmdByAdmin.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/address/AcquirePodIpCmdByAdmin.java index a965624a2a9..7397697bd2c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/address/AcquirePodIpCmdByAdmin.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/address/AcquirePodIpCmdByAdmin.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.address; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.exception.ResourceUnavailableException; @APICommand(name = "acquirePodIpAddress", description = "Allocates IP addresses in respective Pod of a Zone", responseObject = AcquirePodIpCmdResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AcquirePodIpCmdByAdmin extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AcquirePodIpCmdByAdmin.class.getName()); private static final String s_name = "acquirepodipaddress"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/address/AssociateIPAddrCmdByAdmin.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/address/AssociateIPAddrCmdByAdmin.java index 56f41b5f58e..672691ffbd8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/address/AssociateIPAddrCmdByAdmin.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/address/AssociateIPAddrCmdByAdmin.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.address; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ResponseObject.ResponseView; @@ -27,5 +26,4 @@ import org.apache.cloudstack.api.response.IPAddressResponse; @APICommand(name = "associateIpAddress", description = "Acquires and associates a public IP to an account.", responseObject = IPAddressResponse.class, responseView = ResponseView.Full, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AssociateIPAddrCmdByAdmin extends AssociateIPAddrCmd implements AdminCmd { - public static final Logger s_logger = Logger.getLogger(AssociateIPAddrCmdByAdmin.class.getName()); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/address/ReleasePodIpCmdByAdmin.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/address/ReleasePodIpCmdByAdmin.java index b6bfbcaa1e2..7d4cab6a0ac 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/address/ReleasePodIpCmdByAdmin.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/address/ReleasePodIpCmdByAdmin.java @@ -16,7 +16,6 @@ //under the License. package org.apache.cloudstack.api.command.admin.address; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -31,7 +30,6 @@ import com.cloud.user.Account; @APICommand(name = "releasePodIpAddress", description = "Releases a Pod IP back to the Pod", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ReleasePodIpCmdByAdmin extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ReleasePodIpCmdByAdmin.class.getName()); private static final String s_name = "releasepodipresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/affinitygroup/UpdateVMAffinityGroupCmdByAdmin.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/affinitygroup/UpdateVMAffinityGroupCmdByAdmin.java index 7bf9b64481b..43e70838e18 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/affinitygroup/UpdateVMAffinityGroupCmdByAdmin.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/affinitygroup/UpdateVMAffinityGroupCmdByAdmin.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.affinitygroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ResponseObject.ResponseView; @@ -33,5 +32,4 @@ import com.cloud.vm.VirtualMachine; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class UpdateVMAffinityGroupCmdByAdmin extends UpdateVMAffinityGroupCmd implements AdminCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVMAffinityGroupCmdByAdmin.class.getName()); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java index 9446272df6e..30f3bbbec1b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/alert/GenerateAlertCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; @@ -35,7 +34,6 @@ import com.cloud.event.EventTypes; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class GenerateAlertCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(GenerateAlertCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java index 617d1104eda..7fa66ffff1f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.autoscale; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "createCounter", description = "Adds metric counter for VM auto scaling", responseObject = CounterResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateCounterCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateCounterCmd.class.getName()); private static final String s_name = "counterresponse"; // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java index e1f7859a56b..b7b2ce5cb70 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.autoscale; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteCounter", description = "Deletes a counter for VM auto scaling", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteCounterCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteCounterCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// @@ -55,7 +53,7 @@ public class DeleteCounterCmd extends BaseAsyncCmd { try { result = _autoScaleService.deleteCounter(getId()); } catch (ResourceInUseException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, ex.getMessage()); } @@ -63,7 +61,7 @@ public class DeleteCounterCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { - s_logger.warn("Failed to delete counter with Id: " + getId()); + logger.warn("Failed to delete counter with Id: " + getId()); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete counter."); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/backup/UpdateBackupOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/backup/UpdateBackupOfferingCmd.java index 1cd6f4a8328..9de06715ee7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/backup/UpdateBackupOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/backup/UpdateBackupOfferingCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.backup.BackupManager; import org.apache.cloudstack.backup.BackupOffering; import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.user.Account; @@ -39,7 +38,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "updateBackupOffering", description = "Updates a backup offering.", responseObject = BackupOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.16.0") public class UpdateBackupOfferingCmd extends BaseCmd { - private static final Logger LOGGER = Logger.getLogger(UpdateBackupOfferingCmd.class.getName()); @Inject private BackupManager backupManager; @@ -100,7 +98,7 @@ public class UpdateBackupOfferingCmd extends BaseCmd { this.setResponseObject(response); } catch (CloudRuntimeException e) { ApiErrorCode paramError = e instanceof InvalidParameterValueException ? ApiErrorCode.PARAM_ERROR : ApiErrorCode.INTERNAL_ERROR; - LOGGER.error(String.format("Failed to update Backup Offering [id: %s] due to: [%s].", id, e.getMessage()), e); + logger.error(String.format("Failed to update Backup Offering [id: %s] due to: [%s].", id, e.getMessage()), e); throw new ServerApiException(paramError, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/CreateASNRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/CreateASNRangeCmd.java new file mode 100644 index 00000000000..beacba850c3 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/CreateASNRangeCmd.java @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.bgp; + +import com.cloud.bgp.ASNumberRange; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ASNRangeResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + +@APICommand(name = "createASNRange", + description = "Creates a range of Autonomous Systems for BGP Dynamic Routing", + responseObject = ASNRangeResponse.class, + entityType = {ASNumberRange.class}, + since = "4.20.0", + authorized = {RoleType.Admin}) +public class CreateASNRangeCmd extends BaseCmd { + + @Parameter(name = ApiConstants.ZONE_ID, type = BaseCmd.CommandType.UUID, entityType = ZoneResponse.class, + description = "the zone ID", required = true) + private Long zoneId; + + @Parameter(name = ApiConstants.START_ASN, type = CommandType.LONG, required=true, description = "the start AS Number") + private Long startASNumber; + + @Parameter(name = ApiConstants.END_ASN, type = CommandType.LONG, required=true, description = "the end AS Number") + private Long endASNumber; + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { + try { + ASNumberRange asnRange = bgpService.createASNumberRange(zoneId, startASNumber, endASNumber); + ASNRangeResponse response = _responseGenerator.createASNumberRangeResponse(asnRange); + response.setResponseName(getCommandName()); + setResponseObject(response); + } catch (Exception e) { + String msg = String.format("Cannot create AS Number Range %s-%s for zone %s: %s", startASNumber, endASNumber, zoneId, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, msg); + } + } + + public Long getZoneId() { + return zoneId; + } + + public Long getStartASNumber() { + return startASNumber; + } + + public Long getEndASNumber() { + return endASNumber; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/DeleteASNRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/DeleteASNRangeCmd.java new file mode 100644 index 00000000000..33e139315bf --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/DeleteASNRangeCmd.java @@ -0,0 +1,79 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.bgp; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ASNRangeResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.context.CallContext; + +@APICommand(name = "deleteASNRange", + description = "deletes a range of Autonomous Systems for BGP Dynamic Routing", + responseObject = SuccessResponse.class, + since = "4.20.0", + authorized = {RoleType.Admin}) +public class DeleteASNRangeCmd extends BaseCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + //////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + entityType = ASNRangeResponse.class, + required = true, + description = "ID of the AS range") + private Long id; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { + if (bgpService.deleteASRange(getId())) { + SuccessResponse response = new SuccessResponse(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to remove AS range: " + getId()); + } + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/ListASNRangesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/ListASNRangesCmd.java new file mode 100644 index 00000000000..82e54581102 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/ListASNRangesCmd.java @@ -0,0 +1,79 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.bgp; + +import com.cloud.bgp.ASNumberRange; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ASNRangeResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + +import java.util.ArrayList; +import java.util.List; + +@APICommand(name = "listASNRanges", + description = "List Autonomous Systems Number Ranges", + responseObject = ASNRangeResponse.class, + entityType = {ASNumberRange.class}, + since = "4.20.0", + authorized = {RoleType.Admin}) +public class ListASNRangesCmd extends BaseListCmd { + + @Parameter(name = ApiConstants.ZONE_ID, type = BaseCmd.CommandType.UUID, entityType = ZoneResponse.class, + description = "the zone ID") + private Long zoneId; + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { + try { + List ranges = bgpService.listASNumberRanges(zoneId); + ListResponse response = new ListResponse<>(); + List responses = new ArrayList<>(); + for (ASNumberRange asnRange : ranges) { + responses.add(_responseGenerator.createASNumberRangeResponse(asnRange)); + } + response.setResponses(responses); + response.setResponseName(getCommandName()); + setResponseObject(response); + } catch (Exception e) { + String msg = String.format("Error listing AS Number Ranges: %s", e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, msg); + } + } + + public Long getZoneId() { + return zoneId; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/ReleaseASNumberCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/ReleaseASNumberCmd.java new file mode 100644 index 00000000000..687f60dc6da --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/bgp/ReleaseASNumberCmd.java @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.bgp; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.utils.Pair; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + +@APICommand(name = "releaseASNumber", + description = "Releases an AS Number back to the pool", + since = "4.20.0", + authorized = {RoleType.Admin}, + responseObject = SuccessResponse.class, + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false) +public class ReleaseASNumberCmd extends BaseCmd { + + @Parameter(name = ApiConstants.ZONE_ID, type = BaseCmd.CommandType.UUID, entityType = ZoneResponse.class, + description = "the zone ID", required = true) + private Long zoneId; + + @Parameter(name= ApiConstants.AS_NUMBER, type=CommandType.LONG, description="the AS Number to be released", + required = true) + private Long asNumber; + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { + try { + Pair resultPair = bgpService.releaseASNumber(zoneId, asNumber, false); + Boolean result = resultPair.first(); + if (!result) { + String details = resultPair.second(); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Cannot release AS Number %s: %s", asNumber, details)); + } + SuccessResponse response = new SuccessResponse(getCommandName()); + response.setDisplayText(String.format("AS Number %s is released successfully", asNumber)); + setResponseObject(response); + } catch (Exception e) { + String msg = String.format("Error releasing AS Number %s: %s", asNumber, e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, msg); + } + } + + public Long getZoneId() { + return zoneId; + } + + public Long getAsNumber() { + return asNumber; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/IssueCertificateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/IssueCertificateCmd.java index 4c543fdb6a8..463af000f58 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/IssueCertificateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/ca/IssueCertificateCmd.java @@ -37,7 +37,6 @@ import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.ca.Certificate; import org.apache.cloudstack.utils.security.CertUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; @@ -49,7 +48,6 @@ import com.cloud.event.EventTypes; since = "4.11.0", authorized = {RoleType.Admin}) public class IssueCertificateCmd extends BaseAsyncCmd { - private static final Logger LOG = Logger.getLogger(IssueCertificateCmd.class); @Inject @@ -132,7 +130,7 @@ public class IssueCertificateCmd extends BaseAsyncCmd { certificateResponse.setCaCertificate(CertUtils.x509CertificatesToPem(certificate.getCaCertificates())); } } catch (final IOException e) { - LOG.error("Failed to generate and convert client certificate(s) to PEM due to error: ", e); + logger.error("Failed to generate and convert client certificate(s) to PEM due to error: ", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to process and return client certificate"); } certificateResponse.setResponseName(getCommandName()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java index df48b2511b6..69cb43ce40e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java @@ -20,8 +20,8 @@ package org.apache.cloudstack.api.command.admin.cluster; import java.util.ArrayList; import java.util.List; +import com.cloud.cpu.CPU; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -42,7 +42,6 @@ import com.cloud.user.Account; @APICommand(name = "addCluster", description = "Adds a new cluster", responseObject = ClusterResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false) public class AddClusterCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddClusterCmd.class.getName()); @Parameter(name = ApiConstants.CLUSTER_NAME, type = CommandType.STRING, required = true, description = "the cluster name") @@ -69,6 +68,11 @@ public class AddClusterCmd extends BaseCmd { description = "hypervisor type of the cluster: XenServer,KVM,VMware,Hyperv,BareMetal,Simulator,Ovm3") private String hypervisor; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "the CPU arch of the cluster. Valid options are: x86_64, aarch64", + since = "4.20") + private String arch; + @Parameter(name = ApiConstants.CLUSTER_TYPE, type = CommandType.STRING, required = true, description = "type of the cluster: CloudManaged, ExternalManaged") private String clusterType; @@ -206,6 +210,10 @@ public class AddClusterCmd extends BaseCmd { return ApiCommandResourceType.Cluster; } + public CPU.CPUArch getArch() { + return CPU.CPUArch.fromType(arch); + } + @Override public void execute() { try { @@ -226,10 +234,10 @@ public class AddClusterCmd extends BaseCmd { this.setResponseObject(response); } catch (DiscoveryException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (ResourceInUseException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); ServerApiException e = new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); for (String proxyObj : ex.getIdProxyList()) { e.addProxyObject(proxyObj); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java index 497cef4c3ec..2b1cfe8bcb5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.cluster; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -33,7 +32,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteCluster", description = "Deletes a cluster.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteClusterCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteClusterCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/ListClustersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/ListClustersCmd.java index d83330c664a..90ec9d1ff07 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/ListClustersCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/ListClustersCmd.java @@ -19,8 +19,6 @@ package org.apache.cloudstack.api.command.admin.cluster; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListCmd; @@ -29,14 +27,15 @@ import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.commons.lang3.StringUtils; +import com.cloud.cpu.CPU; import com.cloud.org.Cluster; import com.cloud.utils.Pair; @APICommand(name = "listClusters", description = "Lists clusters.", responseObject = ClusterResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListClustersCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListClustersCmd.class.getName()); ///////////////////////////////////////////////////// @@ -70,6 +69,11 @@ public class ListClustersCmd extends BaseListCmd { @Parameter(name = ApiConstants.SHOW_CAPACITIES, type = CommandType.BOOLEAN, description = "flag to display the capacity of the clusters") private Boolean showCapacities; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "CPU arch of the clusters", + since = "4.20.1") + private String arch; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -114,25 +118,29 @@ public class ListClustersCmd extends BaseListCmd { return showCapacities; } + public CPU.CPUArch getArch() { + return StringUtils.isBlank(arch) ? null : CPU.CPUArch.fromType(arch); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// protected Pair, Integer> getClusterResponses() { Pair, Integer> result = _mgr.searchForClusters(this); - List clusterResponses = new ArrayList(); + List clusterResponses = new ArrayList<>(); for (Cluster cluster : result.first()) { ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, showCapacities); clusterResponse.setObjectName("cluster"); clusterResponses.add(clusterResponse); } - return new Pair, Integer>(clusterResponses, result.second()); + return new Pair<>(clusterResponses, result.second()); } @Override public void execute() { Pair, Integer> clusterResponses = getClusterResponses(); - ListResponse response = new ListResponse(); + ListResponse response = new ListResponse<>(); response.setResponses(clusterResponses.first(), clusterResponses.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java index dd527fb409a..c4ee87380ed 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java @@ -16,8 +16,8 @@ // under the License. package org.apache.cloudstack.api.command.admin.cluster; +import com.cloud.cpu.CPU; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -30,11 +30,11 @@ import org.apache.cloudstack.api.response.ClusterResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.org.Cluster; import com.cloud.user.Account; +import org.apache.commons.lang3.StringUtils; @APICommand(name = "updateCluster", description = "Updates an existing cluster", responseObject = ClusterResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateClusterCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddClusterCmd.class.getName()); @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = ClusterResponse.class, required = true, description = "the ID of the Cluster") @@ -55,6 +55,11 @@ public class UpdateClusterCmd extends BaseCmd { @Parameter(name = ApiConstants.MANAGED_STATE, type = CommandType.STRING, description = "whether this cluster is managed by cloudstack") private String managedState; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "the CPU arch of the cluster. Valid options are: x86_64, aarch64", + since = "4.20") + private String arch; + public String getClusterName() { return clusterName; } @@ -110,6 +115,13 @@ public class UpdateClusterCmd extends BaseCmd { return ApiCommandResourceType.Cluster; } + public CPU.CPUArch getArch() { + if (StringUtils.isBlank(arch)) { + return null; + } + return CPU.CPUArch.fromType(arch); + } + @Override public void execute() { Cluster cluster = _resourceService.getCluster(getId()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListCfgGroupsByCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListCfgGroupsByCmd.java index 46ab10cb2bc..d735218169d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListCfgGroupsByCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListCfgGroupsByCmd.java @@ -27,14 +27,12 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ConfigurationGroupResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.config.ConfigurationGroup; -import org.apache.log4j.Logger; import com.cloud.utils.Pair; @APICommand(name = ListCfgGroupsByCmd.APINAME, description = "Lists all configuration groups (primarily used for UI).", responseObject = ConfigurationGroupResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.18.0") public class ListCfgGroupsByCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListCfgGroupsByCmd.class.getName()); public static final String APINAME = "listConfigurationGroups"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java index 80abe5d3e8f..e365d8bc2dc 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java @@ -23,7 +23,6 @@ import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.DomainResponse; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -47,7 +46,6 @@ import com.cloud.utils.exception.CloudRuntimeException; public class ListCfgsByCmd extends BaseListCmd { public static final String APINAME = "listConfigurations"; - public static final Logger s_logger = Logger.getLogger(ListCfgsByCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListDeploymentPlannersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListDeploymentPlannersCmd.java index 4f5186a6df6..78fa31beeb4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListDeploymentPlannersCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListDeploymentPlannersCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.config; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseListCmd; @@ -29,7 +28,6 @@ import org.apache.cloudstack.api.response.ListResponse; @APICommand(name = "listDeploymentPlanners", description = "Lists all DeploymentPlanners available.", responseObject = DeploymentPlannersResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListDeploymentPlannersCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListDeploymentPlannersCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListHypervisorCapabilitiesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListHypervisorCapabilitiesCmd.java index 64f1c19b70c..e7cc9e0234e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListHypervisorCapabilitiesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ListHypervisorCapabilitiesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.config; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -39,7 +38,6 @@ import com.cloud.utils.Pair; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListHypervisorCapabilitiesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListHypervisorCapabilitiesCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ResetCfgCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ResetCfgCmd.java index ada389e0093..f114b263b63 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ResetCfgCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/ResetCfgCmd.java @@ -25,7 +25,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ImageStoreResponse; import org.apache.cloudstack.framework.config.ConfigKey; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.ClusterResponse; @@ -41,7 +40,6 @@ import com.cloud.utils.Pair; @APICommand(name = "resetConfiguration", description = "Resets a configuration. The configuration will be set to default value for global setting, and removed from account_details or domain_details for Account/Domain settings", responseObject = ConfigurationResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.16.0") public class ResetCfgCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ResetCfgCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java index 63dc51452f0..dbf478df701 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.config; import com.cloud.utils.crypt.DBEncryptionUtil; import org.apache.cloudstack.acl.RoleService; import org.apache.cloudstack.api.response.DomainResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiArgValidator; import org.apache.cloudstack.api.ApiConstants; @@ -41,7 +40,6 @@ import com.cloud.user.Account; @APICommand(name = "updateConfiguration", description = "Updates a configuration.", responseObject = ConfigurationResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateCfgCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateCfgCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java index 6c70b24653d..01f7af10841 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.config; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -36,7 +35,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateHypervisorCapabilitiesCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateHypervisorCapabilitiesCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/diagnostics/RunDiagnosticsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/diagnostics/RunDiagnosticsCmd.java index 3d3c7410dc5..4537eb6f215 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/diagnostics/RunDiagnosticsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/diagnostics/RunDiagnosticsCmd.java @@ -38,7 +38,6 @@ import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.diagnostics.DiagnosticsService; import org.apache.cloudstack.diagnostics.DiagnosticsType; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientCapacityException; @@ -53,7 +52,6 @@ import com.cloud.vm.VirtualMachine; authorized = {RoleType.Admin}, since = "4.12.0.0") public class RunDiagnosticsCmd extends BaseAsyncCmd { - private static final Logger LOGGER = Logger.getLogger(RunDiagnosticsCmd.class); @Inject private DiagnosticsService diagnosticsService; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/ListTemplateDirectDownloadCertificatesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/ListTemplateDirectDownloadCertificatesCmd.java index 53b29a37f8f..145ff6ba782 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/ListTemplateDirectDownloadCertificatesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/ListTemplateDirectDownloadCertificatesCmd.java @@ -35,7 +35,6 @@ import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.direct.download.DirectDownloadCertificate; import org.apache.cloudstack.direct.download.DirectDownloadCertificateHostMap; import org.apache.cloudstack.direct.download.DirectDownloadManager; -import org.apache.log4j.Logger; import javax.inject.Inject; import java.util.ArrayList; @@ -63,7 +62,6 @@ public class ListTemplateDirectDownloadCertificatesCmd extends BaseListCmd { description = "if set to true: include the hosts where the certificate is uploaded to") private Boolean listHosts; - private static final Logger LOG = Logger.getLogger(ListTemplateDirectDownloadCertificatesCmd.class); public boolean isListHosts() { return listHosts != null && listHosts; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/RevokeTemplateDirectDownloadCertificateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/RevokeTemplateDirectDownloadCertificateCmd.java index e44ebd31274..eb9031cbc58 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/RevokeTemplateDirectDownloadCertificateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/RevokeTemplateDirectDownloadCertificateCmd.java @@ -41,7 +41,6 @@ import org.apache.cloudstack.direct.download.DirectDownloadManager; import org.apache.cloudstack.direct.download.DirectDownloadManager.HostCertificateStatus; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import javax.inject.Inject; import java.util.ArrayList; @@ -57,7 +56,6 @@ public class RevokeTemplateDirectDownloadCertificateCmd extends BaseCmd { @Inject DirectDownloadManager directDownloadManager; - private static final Logger LOG = Logger.getLogger(RevokeTemplateDirectDownloadCertificateCmd.class); @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DirectDownloadCertificateResponse.class, diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/UploadTemplateDirectDownloadCertificateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/UploadTemplateDirectDownloadCertificateCmd.java index 0fa1797c7fe..c5c102be56d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/UploadTemplateDirectDownloadCertificateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/direct/download/UploadTemplateDirectDownloadCertificateCmd.java @@ -33,7 +33,6 @@ import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.direct.download.DirectDownloadCertificate; import org.apache.cloudstack.direct.download.DirectDownloadManager; import org.apache.cloudstack.direct.download.DirectDownloadManager.HostCertificateStatus; -import org.apache.log4j.Logger; import javax.inject.Inject; import java.util.ArrayList; @@ -49,7 +48,6 @@ public class UploadTemplateDirectDownloadCertificateCmd extends BaseCmd { @Inject DirectDownloadManager directDownloadManager; - private static final Logger LOG = Logger.getLogger(UploadTemplateDirectDownloadCertificateCmd.class); @Parameter(name = ApiConstants.CERTIFICATE, type = BaseCmd.CommandType.STRING, required = true, length = 65535, description = "SSL certificate") @@ -97,7 +95,7 @@ public class UploadTemplateDirectDownloadCertificateCmd extends BaseCmd { } try { - LOG.debug("Uploading certificate " + name + " to agents for Direct Download"); + logger.debug("Uploading certificate " + name + " to agents for Direct Download"); Pair> uploadStatus = directDownloadManager.uploadCertificateToHosts(certificate, name, hypervisor, zoneId, hostId); DirectDownloadCertificate certificate = uploadStatus.first(); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java index f6e09695f88..c7f06920bb8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.domain; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = { RoleType.Admin, RoleType.DomainAdmin }) public class CreateDomainCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateDomainCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java index e0783b63098..db3bae25e39 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.region.RegionService; -import org.apache.log4j.Logger; import com.cloud.domain.Domain; import com.cloud.event.EventTypes; @@ -40,7 +39,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = { RoleType.Admin, RoleType.DomainAdmin }) public class DeleteDomainCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteDomainCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/ListDomainChildrenCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/ListDomainChildrenCmd.java index 72614627f31..8514bb6dda5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/ListDomainChildrenCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/ListDomainChildrenCmd.java @@ -22,7 +22,6 @@ import java.util.List; import com.cloud.server.ResourceIcon; import com.cloud.server.ResourceTag; import org.apache.cloudstack.api.response.ResourceIconResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listDomainChildren", description = "Lists all children domains belonging to a specified domain", responseObject = DomainResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListDomainChildrenCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListDomainChildrenCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmd.java index 8b6661f27ff..895e9328992 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmd.java @@ -20,11 +20,6 @@ import java.util.ArrayList; import java.util.EnumSet; import java.util.List; -import com.cloud.server.ResourceIcon; -import com.cloud.server.ResourceTag; -import org.apache.cloudstack.api.response.ResourceIconResponse; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiConstants.DomainDetails; @@ -34,14 +29,17 @@ import org.apache.cloudstack.api.ResponseObject.ResponseView; import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ResourceIconResponse; +import org.apache.commons.collections.CollectionUtils; import com.cloud.domain.Domain; import com.cloud.exception.InvalidParameterValueException; +import com.cloud.server.ResourceIcon; +import com.cloud.server.ResourceTag; @APICommand(name = "listDomains", description = "Lists domains and provides detailed information for listed domains", responseObject = DomainResponse.class, responseView = ResponseView.Restricted, entityType = {Domain.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListDomainsCmd extends BaseListCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListDomainsCmd.class.getName()); private static final String s_name = "listdomainsresponse"; @@ -73,6 +71,9 @@ public class ListDomainsCmd extends BaseListCmd implements UserCmd { description = "flag to display the resource icon for domains") private Boolean showIcon; + @Parameter(name = ApiConstants.TAG, type = CommandType.STRING, description = "Tag for resource type to return usage", since = "4.20.0") + private String tag; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -99,7 +100,7 @@ public class ListDomainsCmd extends BaseListCmd implements UserCmd { dv = EnumSet.of(DomainDetails.all); } else { try { - ArrayList dc = new ArrayList(); + ArrayList dc = new ArrayList<>(); for (String detail : viewDetails) { dc.add(DomainDetails.valueOf(detail)); } @@ -112,10 +113,14 @@ public class ListDomainsCmd extends BaseListCmd implements UserCmd { return dv; } - public Boolean getShowIcon() { + public boolean getShowIcon() { return showIcon != null ? showIcon : false; } + public String getTag() { + return tag; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -130,12 +135,20 @@ public class ListDomainsCmd extends BaseListCmd implements UserCmd { ListResponse response = _queryService.searchForDomains(this); response.setResponseName(getCommandName()); this.setResponseObject(response); - if (response != null && response.getCount() > 0 && getShowIcon()) { - updateDomainResponse(response.getResponses()); - } + updateDomainResponse(response.getResponses()); } - private void updateDomainResponse(List response) { + protected void updateDomainResponse(List response) { + if (CollectionUtils.isEmpty(response)) { + return; + } + EnumSet details = getDetails(); + if (details.contains(DomainDetails.all) || details.contains(DomainDetails.resource)) { + _resourceLimitService.updateTaggedResourceLimitsAndCountsForDomains(response, getTag()); + } + if (!getShowIcon()) { + return; + } for (DomainResponse domainResponse : response) { ResourceIcon resourceIcon = resourceIconManager.getByResourceTypeAndUuid(ResourceTag.ResourceObjectType.Domain, domainResponse.getId()); if (resourceIcon == null) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java index db4030da772..353cb852bfd 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.domain; import javax.inject.Inject; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "updateDomain", description = "Updates a domain with a new name", responseObject = DomainResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateDomainCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateDomainCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/AddGuestOsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/AddGuestOsCmd.java index 0ad50071287..b854e8389c4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/AddGuestOsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/AddGuestOsCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.guest; import org.apache.commons.collections.MapUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -43,7 +42,6 @@ import java.util.Map; @APICommand(name = "addGuestOs", description = "Add a new guest OS type", responseObject = GuestOSResponse.class, since = "4.4.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddGuestOsCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(AddGuestOsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/AddGuestOsMappingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/AddGuestOsMappingCmd.java index 0ddd21994e3..3fdfebb54bf 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/AddGuestOsMappingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/AddGuestOsMappingCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.guest; import org.apache.commons.lang3.BooleanUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "addGuestOsMapping", description = "Adds a guest OS name to hypervisor OS name mapping", responseObject = GuestOsMappingResponse.class, since = "4.4.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddGuestOsMappingCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(AddGuestOsMappingCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/GetHypervisorGuestOsNamesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/GetHypervisorGuestOsNamesCmd.java index 79517708290..da920a2ec2d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/GetHypervisorGuestOsNamesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/GetHypervisorGuestOsNamesCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.HypervisorGuestOsNamesResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.user.Account; @@ -35,8 +34,6 @@ import com.cloud.utils.Pair; @APICommand(name = GetHypervisorGuestOsNamesCmd.APINAME, description = "Gets the guest OS names in the hypervisor", responseObject = HypervisorGuestOsNamesResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.19.0", authorized = {RoleType.Admin}) public class GetHypervisorGuestOsNamesCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(GetHypervisorGuestOsNamesCmd.class.getName()); - public static final String APINAME = "getHypervisorGuestOsNames"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/ListGuestOsMappingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/ListGuestOsMappingCmd.java index 29ae0b4f188..23e62cdc781 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/ListGuestOsMappingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/ListGuestOsMappingCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.guest; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listGuestOsMapping", description = "Lists all available OS mappings for given hypervisor", responseObject = GuestOsMappingResponse.class, since = "4.4.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListGuestOsMappingCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListGuestOsMappingCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/RemoveGuestOsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/RemoveGuestOsCmd.java index 14beb83e073..d38682ce5bb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/RemoveGuestOsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/RemoveGuestOsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.guest; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -36,7 +35,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RemoveGuestOsCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RemoveGuestOsCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/RemoveGuestOsMappingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/RemoveGuestOsMappingCmd.java index 0a72b7e0451..a472ab672c5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/RemoveGuestOsMappingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/RemoveGuestOsMappingCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.guest; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -36,7 +35,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RemoveGuestOsMappingCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RemoveGuestOsMappingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/UpdateGuestOsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/UpdateGuestOsCmd.java index 25f022b3b51..c98cd149ef3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/UpdateGuestOsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/UpdateGuestOsCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.guest; import org.apache.commons.collections.MapUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -42,7 +41,6 @@ import java.util.Map; since = "4.4.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateGuestOsCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateGuestOsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/UpdateGuestOsMappingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/UpdateGuestOsMappingCmd.java index c83be131b4f..fc67ef0a7e7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/UpdateGuestOsMappingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/guest/UpdateGuestOsMappingCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.guest; import org.apache.commons.lang3.BooleanUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "updateGuestOsMapping", description = "Updates the information about Guest OS to Hypervisor specific name mapping", responseObject = GuestOsMappingResponse.class, since = "4.4.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateGuestOsMappingCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateGuestOsMappingCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java index 15955b9f0a8..ca27837aa88 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.host; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.user.Account; @APICommand(name = "addHost", description = "Adds a new host.", responseObject = HostResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false) public class AddHostCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddHostCmd.class.getName()); ///////////////////////////////////////////////////// @@ -150,7 +148,7 @@ public class AddHostCmd extends BaseCmd { this.setResponseObject(response); } catch (DiscoveryException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java index 225eb1dfecd..c965a39450b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.host; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "addSecondaryStorage", description = "Adds secondary storage.", responseObject = ImageStoreResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddSecondaryStorageCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddSecondaryStorageCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -81,7 +79,7 @@ public class AddSecondaryStorageCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage"); } } catch (DiscoveryException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java index cca449f570b..a514a61b8a4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.host; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "cancelHostMaintenance", description = "Cancels host maintenance.", responseObject = HostResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CancelMaintenanceCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CancelMaintenanceCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java index 934965cd24c..38325c2f072 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.host; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,7 +31,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteHost", description = "Deletes a host.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteHostCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteHostCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/FindHostsForMigrationCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/FindHostsForMigrationCmd.java index 2b6ccb68eea..db30e4f4c02 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/FindHostsForMigrationCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/FindHostsForMigrationCmd.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.utils.Ternary; @APICommand(name = "findHostsForMigration", description = "Find hosts suitable for migrating a virtual machine.", responseObject = HostForMigrationResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class FindHostsForMigrationCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(FindHostsForMigrationCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ListHostTagsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ListHostTagsCmd.java index ed4f9a09bc5..9ea2b2a7fbb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ListHostTagsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ListHostTagsCmd.java @@ -18,7 +18,6 @@ */ package org.apache.cloudstack.api.command.admin.host; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.BaseListCmd; @@ -27,7 +26,6 @@ import org.apache.cloudstack.api.response.HostTagResponse; @APICommand(name = "listHostTags", description = "Lists host tags", responseObject = HostTagResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListHostTagsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListHostTagsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java index b8668f61ca4..099ffc0bde4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java @@ -21,8 +21,6 @@ import java.util.EnumSet; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +33,9 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.commons.lang3.StringUtils; +import com.cloud.cpu.CPU; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor.HypervisorType; @@ -45,7 +45,6 @@ import com.cloud.utils.Ternary; @APICommand(name = "listHosts", description = "Lists hosts.", responseObject = HostResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListHostsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListHostsCmd.class.getName()); ///////////////////////////////////////////////////// @@ -107,6 +106,9 @@ public class ListHostsCmd extends BaseListCmd { @Parameter(name = ApiConstants.HYPERVISOR, type = CommandType.STRING, description = "hypervisor type of host: XenServer,KVM,VMware,Hyperv,BareMetal,Simulator") private String hypervisor; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, description = "CPU Arch of the host", since = "4.20.1") + private String arch; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -191,6 +193,10 @@ public class ListHostsCmd extends BaseListCmd { return outOfBandManagementPowerState; } + public CPU.CPUArch getArch() { + return StringUtils.isBlank(arch) ? null : CPU.CPUArch.fromType(arch); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java index a89965e822e..2641c54364e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java @@ -25,7 +25,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.host.Host; @@ -35,7 +34,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "prepareHostForMaintenance", description = "Prepares a host for maintenance.", responseObject = HostResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class PrepareForMaintenanceCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(PrepareForMaintenanceCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java index 7439d9da514..3550d61fdb9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java @@ -25,7 +25,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.AgentUnavailableException; @@ -36,7 +35,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "reconnectHost", description = "Reconnects a host.", responseObject = HostResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ReconnectHostCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ReconnectHostCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ReleaseHostReservationCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ReleaseHostReservationCmd.java index 90c388bc7dc..7fee0684c78 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ReleaseHostReservationCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/ReleaseHostReservationCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.host; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "releaseHostReservation", description = "Releases host reservation.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ReleaseHostReservationCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ReleaseHostReservationCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java index 9cf47a9c4b9..397f9c80735 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java @@ -27,14 +27,12 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.GuestOSCategoryResponse; import org.apache.cloudstack.api.response.HostResponse; -import org.apache.log4j.Logger; import java.util.List; @APICommand(name = "updateHost", description = "Updates a host.", responseObject = HostResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateHostCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateHostCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -127,8 +125,9 @@ public class UpdateHostCmd extends BaseCmd { hostResponse.setResponseName(getCommandName()); this.setResponseObject(hostResponse); } catch (Exception e) { - s_logger.debug("Failed to update host:" + getId(), e); - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update host:" + getId() + "," + e.getMessage()); + Host host = _entityMgr.findById(Host.class, getId()); + logger.debug("Failed to update host: {} with id {}", host, getId(), e); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to update host: %s with id %d, %s", host, getId(), e.getMessage())); } } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java index 2e05ad14475..c94fe2c5865 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java @@ -24,14 +24,12 @@ import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.commons.lang3.BooleanUtils; -import org.apache.log4j.Logger; import com.cloud.user.Account; @APICommand(name = "updateHostPassword", description = "Update password of a host/pool on management server.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = false) public class UpdateHostPasswordCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateHostPasswordCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ConfigureInternalLoadBalancerElementCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ConfigureInternalLoadBalancerElementCmd.java index 1c7e4a0ce21..c94d326ee62 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ConfigureInternalLoadBalancerElementCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ConfigureInternalLoadBalancerElementCmd.java @@ -17,12 +17,6 @@ package org.apache.cloudstack.api.command.admin.internallb; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; @@ -47,10 +41,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ConfigureInternalLoadBalancerElementCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ConfigureInternalLoadBalancerElementCmd.class.getName()); - - @Inject - private List _service; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -100,7 +90,8 @@ public class ConfigureInternalLoadBalancerElementCmd extends BaseAsyncCmd { @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { CallContext.current().setEventDetails("Internal load balancer element: " + id); - VirtualRouterProvider result = _service.get(0).configureInternalLoadBalancerElement(getId(), getEnabled()); + InternalLoadBalancerElementService service = _networkService.getInternalLoadBalancerElementById(id); + VirtualRouterProvider result = service.configureInternalLoadBalancerElement(getId(), getEnabled()); if (result != null) { InternalLoadBalancerElementResponse routerResponse = _responseGenerator.createInternalLbElementResponse(result); routerResponse.setResponseName(getCommandName()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/CreateInternalLoadBalancerElementCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/CreateInternalLoadBalancerElementCmd.java index f11f081031a..924287b673b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/CreateInternalLoadBalancerElementCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/CreateInternalLoadBalancerElementCmd.java @@ -16,12 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.internallb; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; @@ -45,10 +39,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateInternalLoadBalancerElementCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateInternalLoadBalancerElementCmd.class.getName()); - - @Inject - private List _service; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -85,7 +75,8 @@ public class CreateInternalLoadBalancerElementCmd extends BaseAsyncCreateCmd { @Override public void execute() { CallContext.current().setEventDetails("Virtual router element Id: " + getEntityId()); - VirtualRouterProvider result = _service.get(0).getInternalLoadBalancerElement(getEntityId()); + InternalLoadBalancerElementService service = _networkService.getInternalLoadBalancerElementByNetworkServiceProviderId(getNspId()); + VirtualRouterProvider result = service.getInternalLoadBalancerElement(getEntityId()); if (result != null) { InternalLoadBalancerElementResponse response = _responseGenerator.createInternalLbElementResponse(result); response.setResponseName(getCommandName()); @@ -97,7 +88,8 @@ public class CreateInternalLoadBalancerElementCmd extends BaseAsyncCreateCmd { @Override public void create() throws ResourceAllocationException { - VirtualRouterProvider result = _service.get(0).addInternalLoadBalancerElement(getNspId()); + InternalLoadBalancerElementService service = _networkService.getInternalLoadBalancerElementByNetworkServiceProviderId(getNspId()); + VirtualRouterProvider result = service.addInternalLoadBalancerElement(getNspId()); if (result != null) { setEntityId(result.getId()); setEntityUuid(result.getUuid()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ListInternalLBVMsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ListInternalLBVMsCmd.java index f5756909706..0eb00234382 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ListInternalLBVMsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ListInternalLBVMsCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.internallb; import org.apache.commons.lang.BooleanUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -39,7 +38,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "listInternalLoadBalancerVMs", description = "List internal LB VMs.", responseObject = DomainRouterResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListInternalLBVMsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListInternalLBVMsCmd.class.getName()); private static final String s_name = "listinternallbvmsresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ListInternalLoadBalancerElementsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ListInternalLoadBalancerElementsCmd.java index 82d373e3119..b17cc22e746 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ListInternalLoadBalancerElementsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/ListInternalLoadBalancerElementsCmd.java @@ -17,12 +17,9 @@ package org.apache.cloudstack.api.command.admin.internallb; import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import javax.inject.Inject; - -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListCmd; @@ -46,10 +43,6 @@ import com.cloud.network.VirtualRouterProvider; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListInternalLoadBalancerElementsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListInternalLoadBalancerElementsCmd.class.getName()); - - @Inject - private InternalLoadBalancerElementService _service; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -88,12 +81,21 @@ public class ListInternalLoadBalancerElementsCmd extends BaseListCmd { @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { - List providers = _service.searchForInternalLoadBalancerElements(getId(), getNspId(), getEnabled()); + List services; + if (id == null && nspId == null) { + services = _networkService.getInternalLoadBalancerElements(); + } else { + InternalLoadBalancerElementService elementService = id != null ? _networkService.getInternalLoadBalancerElementById(id) : _networkService.getInternalLoadBalancerElementByNetworkServiceProviderId(nspId); + services = Collections.singletonList(elementService); + } ListResponse response = new ListResponse(); List providerResponses = new ArrayList(); - for (VirtualRouterProvider provider : providers) { - InternalLoadBalancerElementResponse providerResponse = _responseGenerator.createInternalLbElementResponse(provider); - providerResponses.add(providerResponse); + for (InternalLoadBalancerElementService service : services) { + List providers = service.searchForInternalLoadBalancerElements(getId(), getNspId(), getEnabled()); + for (VirtualRouterProvider provider : providers) { + InternalLoadBalancerElementResponse providerResponse = _responseGenerator.createInternalLbElementResponse(provider); + providerResponses.add(providerResponse); + } } response.setResponses(providerResponses); response.setResponseName(getCommandName()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/StartInternalLBVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/StartInternalLBVMCmd.java index fdec7947853..3dd7d2adf37 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/StartInternalLBVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/StartInternalLBVMCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.internallb; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -42,7 +41,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "startInternalLoadBalancerVM", responseObject = DomainRouterResponse.class, description = "Starts an existing internal lb vm.", entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class StartInternalLBVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StartInternalLBVMCmd.class.getName()); private static final String s_name = "startinternallbvmresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/StopInternalLBVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/StopInternalLBVMCmd.java index 76ad4d438d2..a746e5d906d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/StopInternalLBVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/internallb/StopInternalLBVMCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.internallb; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -41,7 +40,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "stopInternalLoadBalancerVM", description = "Stops an Internal LB vm.", responseObject = DomainRouterResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class StopInternalLBVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StopInternalLBVMCmd.class.getName()); private static final String s_name = "stopinternallbvmresponse"; // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/management/ListMgmtsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/management/ListMgmtsCmd.java index 3af772d332f..7b7eae1d0e9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/management/ListMgmtsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/management/ListMgmtsCmd.java @@ -23,12 +23,11 @@ import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ManagementServerResponse; -import org.apache.log4j.Logger; +import org.apache.commons.lang3.BooleanUtils; @APICommand(name = "listManagementServers", description = "Lists management servers.", responseObject = ManagementServerResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListMgmtsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListMgmtsCmd.class.getName()); ///////////////////////////////////////////////////// @@ -41,6 +40,11 @@ public class ListMgmtsCmd extends BaseListCmd { @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the name of the management server") private String hostName; + @Parameter(name = ApiConstants.PEERS, type = CommandType.BOOLEAN, + description = "Whether to return the management server peers or not. By default, the management server peers will not be returned.", + since = "4.20.1.0") + private Boolean peers; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -53,6 +57,10 @@ public class ListMgmtsCmd extends BaseListCmd { return hostName; } + public Boolean getPeers() { + return BooleanUtils.toBooleanDefaultIfNull(peers, false); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java index be0cd9f2fa7..33477297043 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java @@ -20,7 +20,6 @@ import java.util.Map; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -44,7 +43,6 @@ import com.cloud.utils.exception.CloudRuntimeException; responseObject = NetworkDeviceResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddNetworkDeviceCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddNetworkDeviceCmd.class); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java index 176375ce181..40a82239345 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.network; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -43,7 +42,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(AddNetworkServiceProviderCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateGuestNetworkIpv6PrefixCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateGuestNetworkIpv6PrefixCmd.java index d7c7bec99f9..f6b035c5783 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateGuestNetworkIpv6PrefixCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateGuestNetworkIpv6PrefixCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.DataCenterGuestIpv6PrefixResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenterGuestIpv6Prefix; import com.cloud.event.EventTypes; @@ -45,7 +44,6 @@ import com.cloud.user.Account; responseHasSensitiveInfo = false, authorized = {RoleType.Admin}) public class CreateGuestNetworkIpv6PrefixCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CreateGuestNetworkIpv6PrefixCmd.class); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForGuestNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForGuestNetworkCmd.java new file mode 100644 index 00000000000..a482cb1d4f2 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForGuestNetworkCmd.java @@ -0,0 +1,108 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.api.response.Ipv4SubnetForGuestNetworkResponse; + +import com.cloud.event.EventTypes; +import com.cloud.user.Account; +import org.apache.cloudstack.network.Ipv4GuestSubnetNetworkMap; + +@APICommand(name = "createIpv4SubnetForGuestNetwork", + description = "Creates a IPv4 subnet for guest networks.", + responseObject = Ipv4SubnetForGuestNetworkResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class CreateIpv4SubnetForGuestNetworkCmd extends BaseAsyncCmd { + + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name = ApiConstants.PARENT_ID, + type = CommandType.UUID, + entityType = DataCenterIpv4SubnetResponse.class, + required = true, + description = "The zone Ipv4 subnet which the IPv4 subnet belongs to.") + private Long parentId; + + @Parameter(name = ApiConstants.SUBNET, + type = CommandType.STRING, + description = "The CIDR of this Ipv4 subnet.") + private String subnet; + + @Parameter(name = ApiConstants.CIDR_SIZE, + type = CommandType.INTEGER, + description = "the CIDR size of IPv4 network. This is mutually exclusive with subnet.") + private Integer cidrSize; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + public Long getParentId() { + return parentId; + } + + public String getSubnet() { + return subnet; + } + + public Integer getCidrSize() { + return cidrSize; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_IP4_GUEST_SUBNET_CREATE; + } + + @Override + public String getEventDescription() { + return "Creating guest IPv4 subnet " + getSubnet() + " in zone subnet=" + getParentId(); + } + + @Override + public void execute() { + Ipv4GuestSubnetNetworkMap result = routedIpv4Manager.createIpv4SubnetForGuestNetwork(this); + if (result != null) { + Ipv4SubnetForGuestNetworkResponse response = routedIpv4Manager.createIpv4SubnetForGuestNetworkResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create zone guest IPv4 subnet."); + } + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForZoneCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForZoneCmd.java new file mode 100644 index 00000000000..5f48cf9c632 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForZoneCmd.java @@ -0,0 +1,125 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiArgValidator; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; + +import com.cloud.event.EventTypes; +import com.cloud.user.Account; + +@APICommand(name = "createIpv4SubnetForZone", + description = "Creates a IPv4 subnet for a zone.", + responseObject = DataCenterIpv4SubnetResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class CreateIpv4SubnetForZoneCmd extends BaseAsyncCmd { + + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name = ApiConstants.ZONE_ID, + type = CommandType.UUID, + entityType = ZoneResponse.class, + required = true, + description = "UUID of the zone which the IPv4 subnet belongs to.", + validations = {ApiArgValidator.PositiveNumber}) + private Long zoneId; + + @Parameter(name = ApiConstants.SUBNET, + type = CommandType.STRING, + required = true, + description = "The CIDR of the IPv4 subnet.") + private String subnet; + + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account who will own the IPv4 subnet") + private String accountName; + + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "project who will own the IPv4 subnet") + private Long projectId; + + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "domain ID of the account owning the IPv4 subnet") + private Long domainId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + public Long getZoneId() { + return zoneId; + } + + public String getSubnet() { + return subnet; + } + + public String getAccountName() { + return accountName; + } + + public Long getProjectId() { + return projectId; + } + + public Long getDomainId() { + return domainId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_ZONE_IP4_SUBNET_CREATE; + } + + @Override + public String getEventDescription() { + return "Creating guest IPv4 subnet " + getSubnet() + " for zone=" + getZoneId(); + } + + @Override + public void execute() { + DataCenterIpv4GuestSubnet result = routedIpv4Manager.createDataCenterIpv4GuestSubnet(this); + if (result != null) { + DataCenterIpv4SubnetResponse response = routedIpv4Manager.createDataCenterIpv4SubnetResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create zone guest IPv4 subnet."); + } + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateManagementNetworkIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateManagementNetworkIpRangeCmd.java index 2bab4f05352..85cfddfb714 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateManagementNetworkIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateManagementNetworkIpRangeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.ApiArgValidator; @@ -44,7 +43,6 @@ import com.cloud.user.Account; responseHasSensitiveInfo = false, authorized = {RoleType.Admin}) public class CreateManagementNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CreateManagementNetworkIpRangeCmd.class); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateNetworkCmdByAdmin.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateNetworkCmdByAdmin.java index 53b02718ea3..d8b57f79528 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateNetworkCmdByAdmin.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateNetworkCmdByAdmin.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.network; import org.apache.cloudstack.api.ApiArgValidator; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -25,14 +24,16 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ResponseObject.ResponseView; import org.apache.cloudstack.api.command.admin.AdminCmd; import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; +import org.apache.cloudstack.api.response.BgpPeerResponse; import org.apache.cloudstack.api.response.NetworkResponse; import com.cloud.network.Network; +import java.util.List; + @APICommand(name = "createNetwork", description = "Creates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Full, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateNetworkCmdByAdmin extends CreateNetworkCmd implements AdminCmd { - public static final Logger s_logger = Logger.getLogger(CreateNetworkCmdByAdmin.class.getName()); @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the ID or VID of the network") private String vlan; @@ -51,6 +52,14 @@ public class CreateNetworkCmdByAdmin extends CreateNetworkCmd implements AdminCm validations = {ApiArgValidator.NotNullOrEmpty}) private String routerIpv6; + @Parameter(name = ApiConstants.BGP_PEER_IDS, + type = CommandType.LIST, + collectionType = CommandType.UUID, + entityType = BgpPeerResponse.class, + description = "Ids of the Bgp Peer for the network", + since = "4.20.0") + private List bgpPeerIds; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -80,4 +89,8 @@ public class CreateNetworkCmdByAdmin extends CreateNetworkCmd implements AdminCm public String getRouterIpv6() { return routerIpv6; } + + public List getBgpPeerIds() { + return bgpPeerIds; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java index 2112be34543..af3db374a7c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java @@ -24,12 +24,15 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; +import com.cloud.network.Network; +import com.cloud.network.VirtualRouterProvider; import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -47,10 +50,19 @@ import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.user.Account; +import static com.cloud.network.Network.Service.Dhcp; +import static com.cloud.network.Network.Service.Dns; +import static com.cloud.network.Network.Service.Lb; +import static com.cloud.network.Network.Service.StaticNat; +import static com.cloud.network.Network.Service.SourceNat; +import static com.cloud.network.Network.Service.PortForwarding; +import static com.cloud.network.Network.Service.NetworkACL; +import static com.cloud.network.Network.Service.UserData; +import static com.cloud.network.Network.Service.Firewall; + @APICommand(name = "createNetworkOffering", description = "Creates a network offering.", responseObject = NetworkOfferingResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateNetworkOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateNetworkOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -128,6 +140,30 @@ public class CreateNetworkOfferingCmd extends BaseCmd { description = "true if network offering is meant to be used for VPC, false otherwise.") private Boolean forVpc; + @Parameter(name = ApiConstants.FOR_NSX, + type = CommandType.BOOLEAN, + description = "true if network offering is meant to be used for NSX, false otherwise.", + since = "4.20.0") + private Boolean forNsx; + + @Parameter(name = ApiConstants.NSX_SUPPORT_LB, + type = CommandType.BOOLEAN, + description = "true if network offering for NSX network offering supports Load balancer service.", + since = "4.20.0") + private Boolean nsxSupportsLbService; + + @Parameter(name = ApiConstants.NSX_SUPPORTS_INTERNAL_LB, + type = CommandType.BOOLEAN, + description = "true if network offering for NSX network offering supports Internal Load balancer service.", + since = "4.20.0") + private Boolean nsxSupportsInternalLbService; + + @Parameter(name = ApiConstants.NETWORK_MODE, + type = CommandType.STRING, + description = "Indicates the mode with which the network will operate. Valid option: NATTED or ROUTED", + since = "4.20.0") + private String networkMode; + @Parameter(name = ApiConstants.FOR_TUNGSTEN, type = CommandType.BOOLEAN, description = "true if network offering is meant to be used for Tungsten-Fabric, false otherwise.") @@ -175,6 +211,16 @@ public class CreateNetworkOfferingCmd extends BaseCmd { since = "4.16") private Boolean enable; + @Parameter(name = ApiConstants.SPECIFY_AS_NUMBER, type = CommandType.BOOLEAN, since = "4.20.0", + description = "true if network offering supports choosing AS number") + private Boolean specifyAsNumber; + + @Parameter(name = ApiConstants.ROUTING_MODE, + type = CommandType.STRING, + since = "4.20.0", + description = "the routing mode for the network offering. Supported types are: Static or Dynamic.") + private String routingMode; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -212,7 +258,27 @@ public class CreateNetworkOfferingCmd extends BaseCmd { } public List getSupportedServices() { - return supportedServices == null ? new ArrayList() : supportedServices; + if (!isForNsx()) { + return supportedServices == null ? new ArrayList() : supportedServices; + } else { + List services = new ArrayList<>(List.of( + Dhcp.getName(), + Dns.getName(), + StaticNat.getName(), + SourceNat.getName(), + PortForwarding.getName(), + UserData.getName() + )); + if (getNsxSupportsLbService()) { + services.add(Lb.getName()); + } + if (Boolean.TRUE.equals(forVpc)) { + services.add(NetworkACL.getName()); + } else { + services.add(Firewall.getName()); + } + return services; + } } public String getGuestIpType() { @@ -242,6 +308,22 @@ public class CreateNetworkOfferingCmd extends BaseCmd { return forVpc; } + public boolean isForNsx() { + return BooleanUtils.isTrue(forNsx); + } + + public String getNetworkMode() { + return networkMode; + } + + public boolean getNsxSupportsLbService() { + return BooleanUtils.isTrue(nsxSupportsLbService); + } + + public boolean getNsxSupportsInternalLbService() { + return BooleanUtils.isTrue(nsxSupportsInternalLbService); + } + public Boolean getForTungsten() { return forTungsten; } @@ -262,9 +344,8 @@ public class CreateNetworkOfferingCmd extends BaseCmd { } public Map> getServiceProviders() { - Map> serviceProviderMap = null; - if (serviceProviderList != null && !serviceProviderList.isEmpty()) { - serviceProviderMap = new HashMap>(); + Map> serviceProviderMap = new HashMap<>(); + if (serviceProviderList != null && !serviceProviderList.isEmpty() && !isForNsx()) { Collection servicesCollection = serviceProviderList.values(); Iterator iter = servicesCollection.iterator(); while (iter.hasNext()) { @@ -280,11 +361,37 @@ public class CreateNetworkOfferingCmd extends BaseCmd { providerList.add(provider); serviceProviderMap.put(service, providerList); } + } else if (Boolean.TRUE.equals(forNsx)) { + getServiceProviderMapForNsx(serviceProviderMap); } - return serviceProviderMap; } + private void getServiceProviderMapForNsx(Map> serviceProviderMap) { + String routerProvider = Boolean.TRUE.equals(getForVpc()) ? VirtualRouterProvider.Type.VPCVirtualRouter.name() : + VirtualRouterProvider.Type.VirtualRouter.name(); + List unsupportedServices = new ArrayList<>(List.of("Vpn", "SecurityGroup", "Connectivity", + "Gateway", "BaremetalPxeService")); + List routerSupported = List.of("Dhcp", "Dns", "UserData"); + List allServices = Service.listAllServices().stream().map(Service::getName).collect(Collectors.toList()); + if (routerProvider.equals(VirtualRouterProvider.Type.VPCVirtualRouter.name())) { + unsupportedServices.add("Firewall"); + } else { + unsupportedServices.add("NetworkACL"); + } + for (String service : allServices) { + if (unsupportedServices.contains(service)) + continue; + if (routerSupported.contains(service)) + serviceProviderMap.put(service, List.of(routerProvider)); + else + serviceProviderMap.put(service, List.of(Network.Provider.Nsx.getName())); + if (!getNsxSupportsLbService()) { + serviceProviderMap.remove(Lb.getName()); + } + } + } + public Map getServiceCapabilities(Service service) { Map capabilityMap = null; @@ -365,6 +472,14 @@ public class CreateNetworkOfferingCmd extends BaseCmd { return false; } + public boolean getSpecifyAsNumber() { + return BooleanUtils.toBoolean(specifyAsNumber); + } + + public String getRoutingMode() { + return routingMode; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java index 294ee047fe6..7eb52b92456 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.network; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -40,7 +39,6 @@ import com.cloud.user.Account; @APICommand(name = "createPhysicalNetwork", description = "Creates a physical network", responseObject = PhysicalNetworkResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreatePhysicalNetworkCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java index d2dc3d8688f..42262cc2bf1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -42,7 +41,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateStorageNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CreateStorageNetworkIpRangeCmd.class); ///////////////////////////////////////////////////// @@ -119,7 +117,7 @@ public class CreateStorageNetworkIpRangeCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (Exception e) { - s_logger.warn("Create storage network IP range failed", e); + logger.warn("Create storage network IP range failed", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DedicateGuestVlanRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DedicateGuestVlanRangeCmd.java index e6a289d096b..355f738679e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DedicateGuestVlanRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DedicateGuestVlanRangeCmd.java @@ -18,7 +18,6 @@ */ package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "dedicateGuestVlanRange", description = "Dedicates a guest vlan range to an account", responseObject = GuestVlanRangeResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DedicateGuestVlanRangeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DedicateGuestVlanRangeCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DedicateIpv4SubnetForZoneCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DedicateIpv4SubnetForZoneCmd.java new file mode 100644 index 00000000000..2df032c559c --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DedicateIpv4SubnetForZoneCmd.java @@ -0,0 +1,111 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "dedicateIpv4SubnetForZone", + description = "Dedicates an existing IPv4 subnet for a zone to an account or a domain.", + responseObject = DataCenterIpv4SubnetResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class DedicateIpv4SubnetForZoneCmd extends BaseAsyncCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DataCenterIpv4SubnetResponse.class, required = true, description = "Id of the guest network IPv4 subnet") + private Long id; + + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account who will own the IPv4 subnet") + private String accountName; + + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "project who will own the IPv4 subnet") + private Long projectId; + + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "domain ID of the account owning the IPv4 subnet") + private Long domainId; + + public Long getId() { + return id; + } + + public String getAccountName() { + return accountName; + } + + public Long getProjectId() { + return projectId; + } + + public Long getDomainId() { + return domainId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_ZONE_IP4_SUBNET_DEDICATE; + } + + @Override + public String getEventDescription() { + return "Dedicating zone IPv4 subnet " + getId(); + } + + @Override + public void execute() { + try { + DataCenterIpv4GuestSubnet result = routedIpv4Manager.dedicateDataCenterIpv4GuestSubnet(this); + if (result != null) { + DataCenterIpv4SubnetResponse response = routedIpv4Manager.createDataCenterIpv4SubnetResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to dedicate guest network IPv4 subnet:" + getId()); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteGuestNetworkIpv6PrefixCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteGuestNetworkIpv6PrefixCmd.java index 67d309456d6..e2ada4191a8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteGuestNetworkIpv6PrefixCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteGuestNetworkIpv6PrefixCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.DataCenterGuestIpv6PrefixResponse; import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -45,7 +44,6 @@ import com.cloud.utils.exception.CloudRuntimeException; responseHasSensitiveInfo = false, authorized = {RoleType.Admin}) public class DeleteGuestNetworkIpv6PrefixCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteGuestNetworkIpv6PrefixCmd.class); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForGuestNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForGuestNetworkCmd.java new file mode 100644 index 00000000000..28a646f9d03 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForGuestNetworkCmd.java @@ -0,0 +1,88 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.Ipv4SubnetForGuestNetworkResponse; +import org.apache.cloudstack.api.response.SuccessResponse; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "deleteIpv4SubnetForGuestNetwork", + description = "Deletes an existing IPv4 subnet for guest network.", + responseObject = SuccessResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class DeleteIpv4SubnetForGuestNetworkCmd extends BaseAsyncCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = Ipv4SubnetForGuestNetworkResponse.class, required = true, description = "Id of the guest network IPv4 subnet") + private Long id; + + public Long getId() { + return id; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_IP4_GUEST_SUBNET_DELETE; + } + + @Override + public String getEventDescription() { + return "Deleting guest IPv4 subnet " + getId(); + } + + @Override + public void execute() { + try { + boolean result = routedIpv4Manager.deleteIpv4SubnetForGuestNetwork(this); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete guest network IPv4 subnet:" + getId()); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForZoneCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForZoneCmd.java new file mode 100644 index 00000000000..222bc1bad98 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForZoneCmd.java @@ -0,0 +1,88 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.api.response.SuccessResponse; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "deleteIpv4SubnetForZone", + description = "Deletes an existing IPv4 subnet for a zone.", + responseObject = SuccessResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class DeleteIpv4SubnetForZoneCmd extends BaseAsyncCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DataCenterIpv4SubnetResponse.class, required = true, description = "Id of the guest network IPv4 subnet") + private Long id; + + public Long getId() { + return id; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_ZONE_IP4_SUBNET_DELETE; + } + + @Override + public String getEventDescription() { + return "Deleting zone IPv4 subnet " + getId(); + } + + @Override + public void execute() { + try { + boolean result = routedIpv4Manager.deleteDataCenterIpv4GuestSubnet(this); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete guest network IPv4 subnet:" + getId()); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteManagementNetworkIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteManagementNetworkIpRangeCmd.java index abb72eb2724..41cf5e518b3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteManagementNetworkIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteManagementNetworkIpRangeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.ApiArgValidator; @@ -42,7 +41,6 @@ import com.cloud.user.Account; responseHasSensitiveInfo = false, authorized = {RoleType.Admin}) public class DeleteManagementNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteManagementNetworkIpRangeCmd.class); ///////////////////////////////////////////////////// @@ -112,13 +110,13 @@ public class DeleteManagementNetworkIpRangeCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (Exception e) { - s_logger.warn("Failed to delete management ip range from " + getStartIp() + " to " + getEndIp() + " of Pod: " + getPodId(), e); + logger.warn("Failed to delete management ip range from " + getStartIp() + " to " + getEndIp() + " of Pod: " + getPodId(), e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java index d7e8744d6b7..89a36d0b94f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.network; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "deleteNetworkDevice", description = "Deletes network device.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteNetworkDeviceCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteNetworkDeviceCmd.class); @Inject ExternalNetworkDeviceManager nwDeviceMgr; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java index 80ce48cc7d9..e0598b71ea1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,7 +31,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteNetworkOffering", description = "Deletes a network offering.", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteNetworkOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteNetworkOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java index 1ccfff5d7ba..4b56612fdda 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteNetworkServiceProvider", description = "Deletes a Network Service Provider.", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteNetworkServiceProviderCmd.class.getName()); ///////////////////////////////////////////////////// @@ -78,10 +76,10 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete network service provider"); } } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java index 79f0685c6c6..3233130211c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "deletePhysicalNetwork", description = "Deletes a Physical Network.", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeletePhysicalNetworkCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java index b5de43dc5e2..454dfba92f2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteStorageNetworkIpRange", description = "Deletes a storage network IP Range.", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteStorageNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteStorageNetworkIpRangeCmd.class); ///////////////////////////////////////////////////// @@ -77,7 +75,7 @@ public class DeleteStorageNetworkIpRangeCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } catch (Exception e) { - s_logger.warn("Failed to delete storage network ip range " + getId(), e); + logger.warn("Failed to delete storage network ip range " + getId(), e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListDedicatedGuestVlanRangesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListDedicatedGuestVlanRangesCmd.java index 67324d81927..0247a306921 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListDedicatedGuestVlanRangesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListDedicatedGuestVlanRangesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -39,7 +38,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listDedicatedGuestVlanRanges", description = "Lists dedicated guest vlan ranges", responseObject = GuestVlanRangeResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListDedicatedGuestVlanRangesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListDedicatedGuestVlanRangesCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListGuestVlansCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListGuestVlansCmd.java index 1daeac9c53d..4b368f5e034 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListGuestVlansCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListGuestVlansCmd.java @@ -22,7 +22,6 @@ import java.util.List; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -39,7 +38,6 @@ import com.cloud.utils.Pair; since = "4.17.0", authorized = {RoleType.Admin}) public class ListGuestVlansCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListGuestVlansCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForGuestNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForGuestNetworkCmd.java new file mode 100644 index 00000000000..9761f6e89eb --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForGuestNetworkCmd.java @@ -0,0 +1,123 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.network; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.api.response.Ipv4SubnetForGuestNetworkResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.network.Ipv4GuestSubnetNetworkMap; + +@APICommand(name = "listIpv4SubnetsForGuestNetwork", + description = "Lists IPv4 subnets for guest networks.", + responseObject = Ipv4SubnetForGuestNetworkResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class ListIpv4SubnetsForGuestNetworkCmd extends BaseListCmd { + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + entityType = Ipv4SubnetForGuestNetworkResponse.class, + description = "UUID of the IPv4 subnet for guest network.") + private Long id; + + @Parameter(name = ApiConstants.PARENT_ID, + type = CommandType.UUID, + entityType = DataCenterIpv4SubnetResponse.class, + description = "UUID of zone Ipv4 subnet which the IPv4 subnet belongs to.") + private Long parentId; + + @Parameter(name = ApiConstants.SUBNET, + type = CommandType.STRING, + description = "The CIDR of the Ipv4 subnet.") + private String subnet; + + @Parameter(name = ApiConstants.ZONE_ID, + type = CommandType.UUID, + entityType = ZoneResponse.class, + description = "UUID of zone to which the IPv4 subnet belongs to.") + private Long zoneId; + + @Parameter(name = ApiConstants.NETWORK_ID, + type = CommandType.UUID, + entityType = NetworkResponse.class, + description = "UUID of network to which the IPv4 subnet is associated to.") + private Long networkId; + + @Parameter(name = ApiConstants.VPC_ID, + type = CommandType.UUID, + entityType = VpcResponse.class, + description = "UUID of VPC to which the IPv4 subnet is associated to.") + private Long vpcId; + + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getParentId() { + return parentId; + } + + public Long getZoneId() { + return zoneId; + } + + public String getSubnet() { + return subnet; + } + + public Long getNetworkId() { + return networkId; + } + + public Long getVpcId() { + return vpcId; + } + + @Override + public void execute() { + List subnets = routedIpv4Manager.listIpv4GuestSubnetsForGuestNetwork(this); + ListResponse response = new ListResponse<>(); + List subnetResponses = new ArrayList<>(); + for (Ipv4GuestSubnetNetworkMap subnet : subnets) { + Ipv4SubnetForGuestNetworkResponse subnetResponse = routedIpv4Manager.createIpv4SubnetForGuestNetworkResponse(subnet); + subnetResponses.add(subnetResponse); + } + + response.setResponses(subnetResponses, subnets.size()); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForZoneCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForZoneCmd.java new file mode 100644 index 00000000000..2c2182250ed --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForZoneCmd.java @@ -0,0 +1,120 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.network; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; + +@APICommand(name = "listIpv4SubnetsForZone", + description = "Lists IPv4 subnets for zone.", + responseObject = DataCenterIpv4SubnetResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class ListIpv4SubnetsForZoneCmd extends BaseListCmd { + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + entityType = DataCenterIpv4SubnetResponse.class, + description = "UUID of the IPv4 subnet.") + private Long id; + + @Parameter(name = ApiConstants.ZONE_ID, + type = CommandType.UUID, + entityType = ZoneResponse.class, + description = "UUID of zone to which the IPv4 subnet belongs to.") + private Long zoneId; + + @Parameter(name = ApiConstants.SUBNET, + type = CommandType.STRING, + description = "CIDR of the IPv4 subnet.") + private String subnet; + + @Parameter(name = ApiConstants.ACCOUNT, + type = CommandType.STRING, + description = "the account which the IPv4 subnet is dedicated to. Must be used with the domainId parameter.") + private String accountName; + + @Parameter(name = ApiConstants.PROJECT_ID, + type = CommandType.UUID, + entityType = ProjectResponse.class, + description = "project who which the IPv4 subnet is dedicated to") + private Long projectId; + + @Parameter(name = ApiConstants.DOMAIN_ID, + type = CommandType.UUID, + entityType = DomainResponse.class, + description = "the domain ID which the IPv4 subnet is dedicated to.") + private Long domainId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getZoneId() { + return zoneId; + } + + public String getSubnet() { + return subnet; + } + + public String getAccountName() { + return accountName; + } + + public Long getProjectId() { + return projectId; + } + + public Long getDomainId() { + return domainId; + } + + @Override + public void execute() { + List subnets = routedIpv4Manager.listDataCenterIpv4GuestSubnets(this); + ListResponse response = new ListResponse<>(); + List subnetResponses = new ArrayList<>(); + for (DataCenterIpv4GuestSubnet subnet : subnets) { + DataCenterIpv4SubnetResponse subnetResponse = routedIpv4Manager.createDataCenterIpv4SubnetResponse(subnet); + subnetResponses.add(subnetResponse); + } + + response.setResponses(subnetResponses, subnets.size()); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java index 405c2654bdf..768bab64108 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java @@ -22,7 +22,6 @@ import java.util.Map; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -45,7 +44,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "listNetworkDevice", description = "List network devices", responseObject = NetworkDeviceResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListNetworkDeviceCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListNetworkDeviceCmd.class); private static final String s_name = "listnetworkdevice"; @Inject diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java index 67fc8292a93..68495a62215 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.utils.Pair; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListNetworkServiceProvidersCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListNetworkServiceProvidersCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java index b8f30d3f7a1..51a6ddabd9f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listPhysicalNetworks", description = "Lists physical networks", responseObject = PhysicalNetworkResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListPhysicalNetworksCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListPhysicalNetworksCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java index c22ec8ee19b..556162ca360 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -42,7 +41,6 @@ import com.cloud.user.Account; @APICommand(name = "listStorageNetworkIpRange", description = "List a storage network IP range.", responseObject = StorageNetworkIpRangeResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListStorageNetworkIpRangeCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListStorageNetworkIpRangeCmd.class); String _name = "liststoragenetworkiprangeresponse"; @@ -99,7 +97,7 @@ public class ListStorageNetworkIpRangeCmd extends BaseListCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (Exception e) { - s_logger.warn("Failed to list storage network ip range for rangeId=" + getRangeId() + " podId=" + getPodId() + " zoneId=" + getZoneId()); + logger.warn("Failed to list storage network ip range for rangeId=" + getRangeId() + " podId=" + getPodId() + " zoneId=" + getZoneId()); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java index 361da2d0db4..120c6af41ad 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListSupportedNetworkServicesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListSupportedNetworkServicesCmd.class.getName()); @Parameter(name = ApiConstants.PROVIDER, type = CommandType.STRING, description = "network service provider name") private String providerName; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/MigrateNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/MigrateNetworkCmd.java index b38e8f453b0..8ef853b99da 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/MigrateNetworkCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/MigrateNetworkCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -48,7 +47,6 @@ import com.cloud.user.User; since = "4.11.0", authorized = {RoleType.Admin}) public class MigrateNetworkCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(MigrateNetworkCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/MigrateVPCCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/MigrateVPCCmd.java index cca367ce750..3e0801be40b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/MigrateVPCCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/MigrateVPCCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.network; import java.util.HashMap; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker; @@ -50,7 +49,6 @@ import com.cloud.user.User; since = "4.11.0", authorized = {RoleType.Admin}) public class MigrateVPCCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(MigrateVPCCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ReleaseDedicatedGuestVlanRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ReleaseDedicatedGuestVlanRangeCmd.java index 916357920a1..b3125ec3668 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ReleaseDedicatedGuestVlanRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ReleaseDedicatedGuestVlanRangeCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "releaseDedicatedGuestVlanRange", description = "Releases a dedicated guest vlan range to the system", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ReleaseDedicatedGuestVlanRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ReleaseDedicatedGuestVlanRangeCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ReleaseDedicatedIpv4SubnetForZoneCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ReleaseDedicatedIpv4SubnetForZoneCmd.java new file mode 100644 index 00000000000..3e151b9b58f --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/ReleaseDedicatedIpv4SubnetForZoneCmd.java @@ -0,0 +1,88 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "releaseIpv4SubnetForZone", + description = "Releases an existing dedicated IPv4 subnet for a zone.", + responseObject = DataCenterIpv4SubnetResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class ReleaseDedicatedIpv4SubnetForZoneCmd extends BaseAsyncCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DataCenterIpv4SubnetResponse.class, required = true, description = "Id of the guest network IPv4 subnet") + private Long id; + + public Long getId() { + return id; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_ZONE_IP4_SUBNET_RELEASE; + } + + @Override + public String getEventDescription() { + return "Releasing a dedicated zone IPv4 subnet " + getId(); + } + + @Override + public void execute() { + try { + DataCenterIpv4GuestSubnet result = routedIpv4Manager.releaseDedicatedDataCenterIpv4GuestSubnet(this); + if (result != null) { + DataCenterIpv4SubnetResponse response = routedIpv4Manager.createDataCenterIpv4SubnetResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to release guest network IPv4 subnet:" + getId()); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateIpv4SubnetForZoneCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateIpv4SubnetForZoneCmd.java new file mode 100644 index 00000000000..da7a23f50d9 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateIpv4SubnetForZoneCmd.java @@ -0,0 +1,98 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "updateIpv4SubnetForZone", + description = "Updates an existing IPv4 subnet for a zone.", + responseObject = DataCenterIpv4SubnetResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class UpdateIpv4SubnetForZoneCmd extends BaseAsyncCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DataCenterIpv4SubnetResponse.class, required = true, description = "Id of the guest network IPv4 subnet") + private Long id; + + @Parameter(name = ApiConstants.SUBNET, + type = CommandType.STRING, + required = true, + description = "The new CIDR of the IPv4 subnet.") + private String subnet; + + public Long getId() { + return id; + } + + public String getSubnet() { + return subnet; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_ZONE_IP4_SUBNET_UPDATE; + } + + @Override + public String getEventDescription() { + return "Updating zone IPv4 subnet " + getId(); + } + + @Override + public void execute() { + try { + DataCenterIpv4GuestSubnet result = routedIpv4Manager.updateDataCenterIpv4GuestSubnet(this); + if (result != null) { + DataCenterIpv4SubnetResponse response = routedIpv4Manager.createDataCenterIpv4SubnetResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update guest network IPv4 subnet:" + getId()); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java index e8f9e5f8cfe..75fb45e1f11 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.NetworkOfferingResponse; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.domain.Domain; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "updateNetworkOffering", description = "Updates a network offering.", responseObject = NetworkOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateNetworkOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java index 1bbf21b85ed..b4801d9368e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.network; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -40,7 +39,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateNetworkServiceProviderCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdatePhysicalNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdatePhysicalNetworkCmd.java index 24fd93f49d1..162116470bd 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdatePhysicalNetworkCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdatePhysicalNetworkCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.network; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "updatePhysicalNetwork", description = "Updates a physical network", responseObject = PhysicalNetworkResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdatePhysicalNetworkCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdatePodManagementNetworkIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdatePodManagementNetworkIpRangeCmd.java index 4e880f122d8..6f90a070f0d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdatePodManagementNetworkIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdatePodManagementNetworkIpRangeCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -42,7 +41,6 @@ import com.cloud.user.Account; authorized = {RoleType.Admin}) public class UpdatePodManagementNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdatePodManagementNetworkIpRangeCmd.class); ///////////////////////////////////////////////////// @@ -138,10 +136,10 @@ public class UpdatePodManagementNetworkIpRangeCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (Exception e) { - s_logger.warn("Failed to update pod management IP range " + getNewStartIP() + "-" + getNewEndIP() + " of Pod: " + getPodId(), e); + logger.warn("Failed to update pod management IP range " + getNewStartIP() + "-" + getNewEndIP() + " of Pod: " + getPodId(), e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java index 459c89debc9..65e2437417d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -41,7 +40,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateStorageNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateStorageNetworkIpRangeCmd.class); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -107,7 +105,7 @@ public class UpdateStorageNetworkIpRangeCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (Exception e) { - s_logger.warn("Update storage network IP range failed", e); + logger.warn("Update storage network IP range failed", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForNetworkCmd.java new file mode 100644 index 00000000000..1d6bffca342 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForNetworkCmd.java @@ -0,0 +1,109 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiArgValidator; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.admin.AdminCmd; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.api.response.NetworkResponse; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.Network; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +import java.util.List; + +@APICommand(name = "changeBgpPeersForNetwork", + description = "Change the BGP peers for a network.", + responseObject = BgpPeerResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class ChangeBgpPeersForNetworkCmd extends BaseAsyncCmd implements AdminCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.NETWORK_ID, + type = CommandType.UUID, + entityType = NetworkResponse.class, + required = true, + description = "UUID of the network which the Bgp Peers are associated to.", + validations = {ApiArgValidator.PositiveNumber}) + private Long networkId; + + @Parameter(name = ApiConstants.BGP_PEER_IDS, + type = CommandType.LIST, + collectionType = CommandType.UUID, + entityType = BgpPeerResponse.class, + description = "Ids of the Bgp Peer. If it is empty, all BGP peers will be unlinked.") + private List bgpPeerIds; + + public Long getNetworkId() { + return networkId; + } + + public List getBgpPeerIds() { + return bgpPeerIds; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_NETWORK_BGP_PEER_UPDATE; + } + + @Override + public String getEventDescription() { + return "Changing Bgp Peers for network " + getNetworkId(); + } + + @Override + public void execute() { + try { + Network result = routedIpv4Manager.changeBgpPeersForNetwork(this); + if (result != null) { + NetworkResponse response = _responseGenerator.createNetworkResponse(getResponseView(), result); + response.setResponseName(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to change BGP Peers for network"); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForVpcCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForVpcCmd.java new file mode 100644 index 00000000000..0c89f3f1d43 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForVpcCmd.java @@ -0,0 +1,109 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiArgValidator; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.admin.AdminCmd; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.api.response.VpcResponse; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.vpc.Vpc; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +import java.util.List; + +@APICommand(name = "changeBgpPeersForVpc", + description = "Change the BGP peers for a VPC.", + responseObject = BgpPeerResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class ChangeBgpPeersForVpcCmd extends BaseAsyncCmd implements AdminCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.VPC_ID, + type = CommandType.UUID, + entityType = VpcResponse.class, + required = true, + description = "UUID of the VPC which the Bgp Peers are associated to.", + validations = {ApiArgValidator.PositiveNumber}) + private Long vpcId; + + @Parameter(name = ApiConstants.BGP_PEER_IDS, + type = CommandType.LIST, + collectionType = CommandType.UUID, + entityType = BgpPeerResponse.class, + description = "Ids of the Bgp Peer. If it is empty, all BGP peers will be unlinked.") + private List bgpPeerIds; + + public Long getVpcId() { + return vpcId; + } + + public List getBgpPeerIds() { + return bgpPeerIds; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_VPC_BGP_PEER_UPDATE; + } + + @Override + public String getEventDescription() { + return "Changing Bgp Peers for VPC " + getVpcId(); + } + + @Override + public void execute() { + try { + Vpc result = routedIpv4Manager.changeBgpPeersForVpc(this); + if (result != null) { + VpcResponse response = _responseGenerator.createVpcResponse(getResponseView(), result); + response.setResponseName(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to change BGP Peers for vpc"); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/CreateBgpPeerCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/CreateBgpPeerCmd.java new file mode 100644 index 00000000000..80642124938 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/CreateBgpPeerCmd.java @@ -0,0 +1,168 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiArgValidator; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.commons.collections.MapUtils; + +import com.cloud.event.EventTypes; +import com.cloud.user.Account; + +import java.util.Collection; +import java.util.Map; + +@APICommand(name = "createBgpPeer", + description = "Creates a Bgp Peer for a zone.", + responseObject = BgpPeerResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = true, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class CreateBgpPeerCmd extends BaseAsyncCmd { + + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name = ApiConstants.ZONE_ID, + type = CommandType.UUID, + entityType = ZoneResponse.class, + required = true, + description = "UUID of the zone which the Bgp Peer belongs to.", + validations = {ApiArgValidator.PositiveNumber}) + private Long zoneId; + + @Parameter(name = ApiConstants.IP_ADDRESS, + type = CommandType.STRING, + description = "The IPv4 address of the Bgp Peer.") + private String ip4Address; + + @Parameter(name = ApiConstants.IP6_ADDRESS, + type = CommandType.STRING, + description = "The IPv6 address of the Bgp Peer.") + private String ip6Address; + + @Parameter(name = ApiConstants.AS_NUMBER, + type = CommandType.LONG, + required = true, + description = "The AS number of the Bgp Peer.") + private Long asNumber; + + @Parameter(name = ApiConstants.PASSWORD, + type = CommandType.STRING, + description = "The password of the Bgp Peer.") + private String password; + + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account who will own the Bgp Peer") + private String accountName; + + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "project who will own the Bgp Peer") + private Long projectId; + + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "domain ID of the account owning the Bgp Peer") + private Long domainId; + + @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, + description = "BGP peer details in key/value pairs.") + protected Map details; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + public Long getZoneId() { + return zoneId; + } + + public String getIp4Address() { + return ip4Address; + } + + public String getIp6Address() { + return ip6Address; + } + + public String getPassword() { + return password; + } + + public Long getAsNumber() { + return asNumber; + } + + public String getAccountName() { + return accountName; + } + + public Long getProjectId() { + return projectId; + } + + public Long getDomainId() { + return domainId; + } + + public Map getDetails() { + if (MapUtils.isEmpty(details)) { + return null; + } + Collection paramsCollection = this.details.values(); + return (Map) (paramsCollection.toArray())[0]; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_BGP_PEER_CREATE; + } + + @Override + public String getEventDescription() { + return "Creating Bgp Peer " + getAsNumber() + " for zone=" + getZoneId(); + } + + @Override + public void execute() { + BgpPeer result = routedIpv4Manager.createBgpPeer(this); + if (result != null) { + BgpPeerResponse response = routedIpv4Manager.createBgpPeerResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create Bgp Peer."); + } + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/DedicateBgpPeerCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/DedicateBgpPeerCmd.java new file mode 100644 index 00000000000..ec3d0ea1162 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/DedicateBgpPeerCmd.java @@ -0,0 +1,111 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.network.BgpPeer; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "dedicateBgpPeer", + description = "Dedicates an existing Bgp Peer to an account or a domain.", + responseObject = BgpPeerResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class DedicateBgpPeerCmd extends BaseAsyncCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = BgpPeerResponse.class, required = true, description = "Id of the Bgp Peer") + private Long id; + + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account who will own the Bgp Peer") + private String accountName; + + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "project who will own the Bgp Peer") + private Long projectId; + + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "domain ID of the account owning the Bgp Peer") + private Long domainId; + + public Long getId() { + return id; + } + + public String getAccountName() { + return accountName; + } + + public Long getProjectId() { + return projectId; + } + + public Long getDomainId() { + return domainId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_BGP_PEER_DEDICATE; + } + + @Override + public String getEventDescription() { + return "Dedicating Bgp Peer " + getId(); + } + + @Override + public void execute() { + try { + BgpPeer result = routedIpv4Manager.dedicateBgpPeer(this); + if (result != null) { + BgpPeerResponse response = routedIpv4Manager.createBgpPeerResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to dedicate Bgp Peer:" + getId()); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/DeleteBgpPeerCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/DeleteBgpPeerCmd.java new file mode 100644 index 00000000000..a01711efa44 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/DeleteBgpPeerCmd.java @@ -0,0 +1,88 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.api.response.SuccessResponse; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "deleteBgpPeer", + description = "Deletes an existing Bgp Peer.", + responseObject = SuccessResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class DeleteBgpPeerCmd extends BaseAsyncCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = BgpPeerResponse.class, required = true, description = "Id of the Bgp Peer") + private Long id; + + public Long getId() { + return id; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_BGP_PEER_DELETE; + } + + @Override + public String getEventDescription() { + return "Deleting Bgp Peer " + getId(); + } + + @Override + public void execute() { + try { + boolean result = routedIpv4Manager.deleteBgpPeer(this); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Bgp Peer:" + getId()); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ListBgpPeersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ListBgpPeersCmd.java new file mode 100644 index 00000000000..ea15f0970e8 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ListBgpPeersCmd.java @@ -0,0 +1,130 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.network.bgp; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.network.BgpPeer; + +@APICommand(name = "listBgpPeers", + description = "Lists Bgp Peers.", + responseObject = BgpPeerResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class ListBgpPeersCmd extends BaseListCmd { + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + entityType = BgpPeerResponse.class, + description = "UUID of the Bgp Peer.") + private Long id; + + @Parameter(name = ApiConstants.ZONE_ID, + type = CommandType.UUID, + entityType = ZoneResponse.class, + description = "UUID of zone to which the Bgp Peer belongs to.") + private Long zoneId; + + @Parameter(name = ApiConstants.AS_NUMBER, + type = CommandType.LONG, + description = "AS number of the Bgp Peer.") + private Long asNumber; + + @Parameter(name = ApiConstants.ACCOUNT, + type = CommandType.STRING, + description = "the account which the Bgp Peer is dedicated to. Must be used with the domainId parameter.") + private String accountName; + + @Parameter(name = ApiConstants.PROJECT_ID, + type = CommandType.UUID, + entityType = ProjectResponse.class, + description = "project who which the Bgp Peer is dedicated to") + private Long projectId; + + @Parameter(name = ApiConstants.DOMAIN_ID, + type = CommandType.UUID, + entityType = DomainResponse.class, + description = "the domain ID which the Bgp Peer is dedicated to.") + private Long domainId; + + @Parameter(name = ApiConstants.IS_DEDICATED, + type = CommandType.BOOLEAN, + description = "Lists only dedicated or non-dedicated Bgp Peers. If not set, lists all dedicated and non-dedicated BGP peers the domain/account can access.") + private Boolean isDedicated; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getZoneId() { + return zoneId; + } + + public Long getAsNumber() { + return asNumber; + } + + public String getAccountName() { + return accountName; + } + + public Long getProjectId() { + return projectId; + } + + public Long getDomainId() { + return domainId; + } + + public Boolean getDedicated() { + return isDedicated; + } + + @Override + public void execute() { + List subnets = routedIpv4Manager.listBgpPeers(this); + ListResponse response = new ListResponse<>(); + List subnetResponses = new ArrayList<>(); + for (BgpPeer subnet : subnets) { + BgpPeerResponse subnetResponse = routedIpv4Manager.createBgpPeerResponse(subnet); + subnetResponse.setObjectName("bgppeer"); + subnetResponses.add(subnetResponse); + } + + response.setResponses(subnetResponses, subnets.size()); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ReleaseDedicatedBgpPeerCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ReleaseDedicatedBgpPeerCmd.java new file mode 100644 index 00000000000..92610c233ef --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/ReleaseDedicatedBgpPeerCmd.java @@ -0,0 +1,88 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.network.BgpPeer; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "releaseBgpPeer", + description = "Releases an existing dedicated Bgp Peer.", + responseObject = BgpPeerResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class ReleaseDedicatedBgpPeerCmd extends BaseAsyncCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = BgpPeerResponse.class, required = true, description = "Id of the Bgp Peer") + private Long id; + + public Long getId() { + return id; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_BGP_PEER_RELEASE; + } + + @Override + public String getEventDescription() { + return "Releasing a dedicated Bgp Peer " + getId(); + } + + @Override + public void execute() { + try { + BgpPeer result = routedIpv4Manager.releaseDedicatedBgpPeer(this); + if (result != null) { + BgpPeerResponse response = routedIpv4Manager.createBgpPeerResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to release Bgp Peer:" + getId()); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/UpdateBgpPeerCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/UpdateBgpPeerCmd.java new file mode 100644 index 00000000000..ae44330ea03 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/network/bgp/UpdateBgpPeerCmd.java @@ -0,0 +1,149 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.network.BgpPeer; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; +import org.apache.commons.collections.MapUtils; + +import java.util.Collection; +import java.util.Map; + +@APICommand(name = "updateBgpPeer", + description = "Updates an existing Bgp Peer.", + responseObject = BgpPeerResponse.class, + since = "4.20.0", + requestHasSensitiveInfo = true, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}) +public class UpdateBgpPeerCmd extends BaseAsyncCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = BgpPeerResponse.class, required = true, description = "Id of the Bgp Peer") + private Long id; + + @Parameter(name = ApiConstants.IP_ADDRESS, + type = CommandType.STRING, + description = "The IPv4 address of the Bgp Peer.") + private String ip4Address; + + @Parameter(name = ApiConstants.IP6_ADDRESS, + type = CommandType.STRING, + description = "The IPv6 address of the Bgp Peer.") + private String ip6Address; + + @Parameter(name = ApiConstants.AS_NUMBER, + type = CommandType.LONG, + description = "The AS number of the Bgp Peer.") + private Long asNumber; + + @Parameter(name = ApiConstants.PASSWORD, + type = CommandType.STRING, + description = "The password of the Bgp Peer.") + private String password; + + @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, + description = "BGP peer details in key/value pairs.") + protected Map details; + + @Parameter(name = ApiConstants.CLEAN_UP_DETAILS, + type = CommandType.BOOLEAN, + description = "optional boolean field, which indicates if details should be cleaned up or not (if set to true, details are removed for this resource; if false or not set, no action)") + private Boolean cleanupDetails; + + public Long getId() { + return id; + } + + public String getIp4Address() { + return ip4Address; + } + + public String getIp6Address() { + return ip6Address; + } + + public Long getAsNumber() { + return asNumber; + } + + public String getPassword() { + return password; + } + + public Map getDetails() { + if (MapUtils.isEmpty(details)) { + return null; + } + Collection paramsCollection = this.details.values(); + return (Map) (paramsCollection.toArray())[0]; + } + + public boolean isCleanupDetails(){ + return cleanupDetails == null ? false : cleanupDetails.booleanValue(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_BGP_PEER_UPDATE; + } + + @Override + public String getEventDescription() { + return "Updating Bgp Peer " + getId(); + } + + @Override + public void execute() { + try { + BgpPeer result = routedIpv4Manager.updateBgpPeer(this); + if (result != null) { + BgpPeerResponse response = routedIpv4Manager.createBgpPeerResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update Bgp Peer:" + getId()); + } + } catch (InvalidParameterValueException ex) { + throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); + } catch (CloudRuntimeException ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java index c2d8b3b6839..c46e4cd6b44 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java @@ -37,7 +37,6 @@ import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; @@ -47,7 +46,6 @@ import com.cloud.user.Account; @APICommand(name = "createDiskOffering", description = "Creates a disk offering.", responseObject = DiskOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateDiskOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateDiskOfferingCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java index e3b2887ad33..8f6d5413d72 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java @@ -37,7 +37,6 @@ import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.offering.ServiceOffering; @@ -47,7 +46,6 @@ import com.cloud.user.Account; @APICommand(name = "createServiceOffering", description = "Creates a service offering.", responseObject = ServiceOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateServiceOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateServiceOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -248,6 +246,12 @@ public class CreateServiceOfferingCmd extends BaseCmd { @Parameter(name = ApiConstants.ENCRYPT_ROOT, type = CommandType.BOOLEAN, description = "VMs using this offering require root volume encryption", since="4.18") private Boolean encryptRoot; + @Parameter(name = ApiConstants.PURGE_RESOURCES, type = CommandType.BOOLEAN, + description = "Whether to cleanup instance and its associated resource from database upon expunge of the instance", + since="4.20") + private Boolean purgeResources; + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -275,7 +279,7 @@ public class CreateServiceOfferingCmd extends BaseCmd { public String getServiceOfferingName() { if (StringUtils.isEmpty(serviceOfferingName)) { - throw new InvalidParameterValueException("Failed to create service offering because offering name has not been spified."); + throw new InvalidParameterValueException("Failed to create service offering because offering name has not been specified."); } return serviceOfferingName; } @@ -483,6 +487,10 @@ public class CreateServiceOfferingCmd extends BaseCmd { return false; } + public boolean isPurgeResources() { + return Boolean.TRUE.equals(purgeResources); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java index 0159cd297f9..591b09c60a5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.offering; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,7 +31,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteDiskOffering", description = "Updates a disk offering.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteDiskOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteDiskOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java index 9b7f9d48e30..19203289d10 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.offering; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,7 +31,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteServiceOffering", description = "Deletes a service offering.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteServiceOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteServiceOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/IsAccountAllowedToCreateOfferingsWithTagsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/IsAccountAllowedToCreateOfferingsWithTagsCmd.java index e94bff1fce8..fcd6b03d3e5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/IsAccountAllowedToCreateOfferingsWithTagsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/IsAccountAllowedToCreateOfferingsWithTagsCmd.java @@ -29,7 +29,7 @@ import org.apache.cloudstack.api.response.IsAccountAllowedToCreateOfferingsWithT responseObject = IsAccountAllowedToCreateOfferingsWithTagsResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class IsAccountAllowedToCreateOfferingsWithTagsCmd extends BaseCmd { - @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AccountResponse.class, description = "Account UUID") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AccountResponse.class, description = "Account UUID", required = true) private Long id; @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java index 424ee1609ad..370453804cf 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.domain.Domain; @@ -41,7 +40,6 @@ import com.cloud.user.Account; @APICommand(name = "updateDiskOffering", description = "Updates a disk offering.", responseObject = DiskOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateDiskOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateDiskOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java index 2f3dba4d9c5..e580f0d9f41 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.domain.Domain; @@ -41,7 +40,6 @@ import com.cloud.user.Account; @APICommand(name = "updateServiceOffering", description = "Updates a service offering.", responseObject = ServiceOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateServiceOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateServiceOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -91,6 +89,11 @@ public class UpdateServiceOfferingCmd extends BaseCmd { description = "state of the service offering") private String serviceOfferingState; + @Parameter(name = ApiConstants.PURGE_RESOURCES, type = CommandType.BOOLEAN, + description = "Whether to cleanup VM and its associated resource upon expunge", + since="4.20") + private Boolean purgeResources; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -187,6 +190,10 @@ public class UpdateServiceOfferingCmd extends BaseCmd { return state; } + public boolean isPurgeResources() { + return Boolean.TRUE.equals(purgeResources); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java index b15854ca875..c1d9a6db429 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.pod; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "createPod", description = "Creates a new Pod.", responseObject = PodResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreatePodCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreatePodCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java index bdb9ef26694..c1de800d745 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.pod; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -33,7 +32,6 @@ import com.cloud.user.Account; @APICommand(name = "deletePod", description = "Deletes a Pod.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeletePodCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeletePodCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/ListPodsByCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/ListPodsByCmd.java index c0e26a32eee..10370b4c78a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/ListPodsByCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/ListPodsByCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.pod; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listPods", description = "Lists all Pods.", responseObject = PodResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListPodsByCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListPodsByCmd.class.getName()); ///////////////////////////////////////////////////// @@ -88,8 +86,8 @@ public class ListPodsByCmd extends BaseListCmd { @Override public void execute() { Pair, Integer> result = _mgr.searchForPods(this); - ListResponse response = new ListResponse(); - List podResponses = new ArrayList(); + ListResponse response = new ListResponse<>(); + List podResponses = new ArrayList<>(); for (Pod pod : result.first()) { PodResponse podResponse = _responseGenerator.createPodResponse(pod, showCapacities); podResponse.setObjectName("pod"); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java index 99ab5e1cee4..7dae6f4c7cf 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.pod; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -33,7 +32,6 @@ import com.cloud.user.Account; @APICommand(name = "updatePod", description = "Updates a Pod.", responseObject = PodResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdatePodCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdatePodCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java index 61bf32ab822..3a93a275042 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/AddRegionCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.region; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "addRegion", description = "Adds a Region", responseObject = RegionResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddRegionCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddRegionCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/CreatePortableIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/CreatePortableIpRangeCmd.java index 61deceb0691..fd103c83830 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/CreatePortableIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/CreatePortableIpRangeCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.region; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -43,7 +42,6 @@ import com.cloud.user.Account; responseHasSensitiveInfo = false) public class CreatePortableIpRangeCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreatePortableIpRangeCmd.class.getName()); ///////////////////////////////////////////////////// @@ -126,7 +124,7 @@ public class CreatePortableIpRangeCmd extends BaseAsyncCreateCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create portable public IP range"); } } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/DeletePortableIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/DeletePortableIpRangeCmd.java index 6cc884645e9..3ff46fcc94d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/DeletePortableIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/DeletePortableIpRangeCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.region; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "deletePortableIpRange", description = "deletes a range of portable public IP's associated with a region", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeletePortableIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeletePortableIpRangeCmd.class.getName()); private static final String s_name = "deleteportablepublicipresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/ListPortableIpRangesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/ListPortableIpRangesCmd.java index ed0ddd68aca..e654da6df44 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/ListPortableIpRangesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/ListPortableIpRangesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.region; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListPortableIpRangesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListPortableIpRangesCmd.class.getName()); private static final String s_name = "listportableipresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/RemoveRegionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/RemoveRegionCmd.java index 180e34c7a8f..3ea323eebfb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/RemoveRegionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/RemoveRegionCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.region; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "removeRegion", description = "Removes specified region", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RemoveRegionCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(RemoveRegionCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java index c772efd5e1f..4267f6a2c28 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/region/UpdateRegionCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.region; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "updateRegion", description = "Updates a region", responseObject = RegionResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateRegionCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateRegionCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ArchiveAlertsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ArchiveAlertsCmd.java index 003b823e106..dc8c15cf09d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ArchiveAlertsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ArchiveAlertsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.resource; import java.util.Date; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ArchiveAlertsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ArchiveAlertsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/CleanVMReservationsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/CleanVMReservationsCmd.java index 9acc71ce693..1ae8c944123 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/CleanVMReservationsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/CleanVMReservationsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.resource; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiErrorCode; @@ -31,7 +30,6 @@ import com.cloud.user.Account; @APICommand(name = "cleanVMReservations", description = "Cleanups VM reservations in the database.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CleanVMReservationsCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CleanVMReservationsCmd.class.getName()); private static final String s_name = "cleanvmreservationresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/DeleteAlertsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/DeleteAlertsCmd.java index eb384892758..9262a120f72 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/DeleteAlertsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/DeleteAlertsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.resource; import java.util.Date; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteAlertsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteAlertsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java index 3471ab60837..64cf691e6a7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java @@ -25,7 +25,6 @@ import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.AlertResponse; import org.apache.cloudstack.api.response.ListResponse; -import org.apache.log4j.Logger; import com.cloud.alert.Alert; import com.cloud.utils.Pair; @@ -34,7 +33,6 @@ import com.cloud.utils.Pair; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListAlertsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListAlertsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmd.java index fdc1087377f..e65326cd874 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmd.java @@ -21,7 +21,6 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.exception.InvalidParameterValueException; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListCapacityCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListCapacityCmd.class.getName()); private static final DecimalFormat s_percentFormat = new DecimalFormat("##.##"); @@ -73,6 +71,9 @@ public class ListCapacityCmd extends BaseListCmd { @Parameter(name = ApiConstants.SORT_BY, type = CommandType.STRING, since = "3.0.0", description = "Sort the results. Available values: Usage") private String sortBy; + @Parameter(name = ApiConstants.TAG, type = CommandType.STRING, description = "Tag for the resource type", since = "4.20.0") + private String tag; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -109,6 +110,10 @@ public class ListCapacityCmd extends BaseListCmd { return null; } + public String getTag() { + return tag; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/PurgeExpungedResourcesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/PurgeExpungedResourcesCmd.java new file mode 100644 index 00000000000..b6833f09733 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/PurgeExpungedResourcesCmd.java @@ -0,0 +1,131 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.resource; + + +import java.util.Date; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PurgeExpungedResourcesResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.resource.ResourceCleanupService; + +import com.cloud.event.EventTypes; + +@APICommand(name = "purgeExpungedResources", + description = "Purge expunged resources", + responseObject = SuccessResponse.class, + responseView = ResponseObject.ResponseView.Full, + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin}, + since = "4.20") +public class PurgeExpungedResourcesCmd extends BaseAsyncCmd { + + @Inject + ResourceCleanupService resourceCleanupService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.RESOURCE_TYPE, type = BaseCmd.CommandType.STRING, + description = "The type of the resource which need to be purged. Supported types: " + + "VirtualMachine") + private String resourceType; + + @Parameter(name = ApiConstants.BATCH_SIZE, type = CommandType.LONG, + description = "The size of batch used during purging") + private Long batchSize; + + @Parameter(name = ApiConstants.START_DATE, + type = CommandType.DATE, + description = "The start date range of the expunged resources used for purging " + + "(use format \"yyyy-MM-dd\" or \"yyyy-MM-dd HH:mm:ss\")") + private Date startDate; + + @Parameter(name = ApiConstants.END_DATE, + type = CommandType.DATE, + description = "The end date range of the expunged resources used for purging " + + "(use format \"yyyy-MM-dd\" or \"yyyy-MM-dd HH:mm:ss\")") + private Date endDate; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + public String getResourceType() { + return resourceType; + } + + public Long getBatchSize() { + return batchSize; + } + + public Date getStartDate() { + return startDate; + } + + public Date getEndDate() { + return endDate; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_PURGE_EXPUNGED_RESOURCES; + } + + @Override + public String getEventDescription() { + return "Purging expunged resources"; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() { + try { + long result = resourceCleanupService.purgeExpungedResources(this); + PurgeExpungedResourcesResponse response = new PurgeExpungedResourcesResponse(); + response.setResourceCount(result); + response.setObjectName(getCommandName().toLowerCase()); + setResponseObject(response); + } catch (Exception e) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getLocalizedMessage()); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/StartRollingMaintenanceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/StartRollingMaintenanceCmd.java index 7ee3e50e0cd..04fa1002611 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/StartRollingMaintenanceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/StartRollingMaintenanceCmd.java @@ -34,7 +34,6 @@ import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.RollingMaintenanceResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -55,7 +54,6 @@ public class StartRollingMaintenanceCmd extends BaseAsyncCmd { @Inject RollingMaintenanceManager manager; - public static final Logger s_logger = Logger.getLogger(StartRollingMaintenanceCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java index 5dfada57216..c5ae6890c3e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.resource; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; description = "Uploads a custom certificate for the console proxy VMs to use for SSL. Can be used to upload a single certificate signed by a known CA. Can also be used, through multiple calls, to upload a chain of certificates from CA to the custom certificate itself.", requestHasSensitiveInfo = true, responseHasSensitiveInfo = false) public class UploadCustomCertificateCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UploadCustomCertificateCmd.class.getName()); @Parameter(name = ApiConstants.CERTIFICATE, type = CommandType.STRING, required = true, description = "The certificate to be uploaded.", length = 65535) diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/DeleteResourceIconCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/DeleteResourceIconCmd.java index 8fb02ea7054..e97a68bddcb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/DeleteResourceIconCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/DeleteResourceIconCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import java.util.List; @@ -37,7 +36,6 @@ import java.util.List; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.DomainAdmin, RoleType.ResourceAdmin, RoleType.User}) public class DeleteResourceIconCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteResourceIconCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/ListResourceIconCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/ListResourceIconCmd.java index 0af11ceec22..6cc3173cf15 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/ListResourceIconCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/ListResourceIconCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ResourceIconResponse; -import org.apache.log4j.Logger; import java.util.List; @@ -35,7 +34,6 @@ import java.util.List; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.DomainAdmin, RoleType.ResourceAdmin, RoleType.User}) public class ListResourceIconCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ListResourceIconCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/UploadResourceIconCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/UploadResourceIconCmd.java index ea5d8995a2a..5a6acd961bf 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/UploadResourceIconCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/resource/icon/UploadResourceIconCmd.java @@ -31,7 +31,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import java.awt.image.BufferedImage; @@ -46,7 +45,6 @@ import java.util.List; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.DomainAdmin, RoleType.ResourceAdmin, RoleType.User}) public class UploadResourceIconCmd extends BaseCmd { - public static final Logger LOGGER = Logger.getLogger(UploadResourceIconCmd.class.getName()); ///////////////////////////////////////////////////// @@ -120,7 +118,7 @@ public class UploadResourceIconCmd extends BaseCmd { return false; } } catch (Exception e) { - LOGGER.warn("Data uploaded not a valid image"); + logger.warn("Data uploaded not a valid image"); return false; } return true; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java index a1b01a1c04f..4a8c0bc3a3b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ConfigureOvsElementCmd.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.OvsProviderResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -42,8 +41,6 @@ import com.cloud.user.Account; @APICommand(name = "configureOvsElement", responseObject = OvsProviderResponse.class, description = "Configures an ovs element.", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ConfigureOvsElementCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger - .getLogger(ConfigureOvsElementCmd.class.getName()); @Inject private List _service; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java index b7f7a050d07..aa119f3aca7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java @@ -20,7 +20,6 @@ import java.util.List; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -43,7 +42,6 @@ import com.cloud.user.Account; @APICommand(name = "configureVirtualRouterElement", responseObject = VirtualRouterProviderResponse.class, description = "Configures a virtual router element.", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ConfigureVirtualRouterElementCmd.class.getName()); @Inject private List _service; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java index f93ca35a06a..e85531c83c4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java @@ -20,7 +20,6 @@ import java.util.List; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -43,7 +42,6 @@ import com.cloud.user.Account; @APICommand(name = "createVirtualRouterElement", responseObject = VirtualRouterProviderResponse.class, description = "Create a virtual router element.", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateVirtualRouterElementCmd.class.getName()); @Inject private List _service; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java index d2dce6b9ff3..39ccee47fbe 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.router; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -38,7 +37,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "destroyRouter", description = "Destroys a router.", responseObject = DomainRouterResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DestroyRouterCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DestroyRouterCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/GetRouterHealthCheckResultsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/GetRouterHealthCheckResultsCmd.java index 93a48eba49c..4bef26e0555 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/GetRouterHealthCheckResultsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/GetRouterHealthCheckResultsCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.api.response.RouterHealthCheckResultResponse; import org.apache.cloudstack.api.response.RouterHealthCheckResultsListResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang.BooleanUtils; -import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; @@ -47,7 +46,6 @@ import com.cloud.vm.VirtualMachine; responseHasSensitiveInfo = false, since = "4.14.0") public class GetRouterHealthCheckResultsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(GetRouterHealthCheckResultsCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java index 89b39f87e44..a267aa52669 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListOvsElementsCmd.java @@ -26,11 +26,9 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.OvsProviderResponse; import org.apache.cloudstack.api.response.ProviderResponse; -import org.apache.log4j.Logger; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -42,8 +40,7 @@ import com.cloud.network.element.VirtualRouterElementService; @APICommand(name = "listOvsElements", description = "Lists all available ovs elements.", responseObject = OvsProviderResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListOvsElementsCmd extends BaseListCmd { - public static final Logger s_logger = Logger - .getLogger(ListNetworkOfferingsCmd.class.getName()); + @Inject private List _service; // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java index 6e955e46212..9e34c05ce21 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java @@ -16,9 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.router; -import org.apache.commons.lang.BooleanUtils; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; @@ -33,14 +30,16 @@ import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +import com.cloud.cpu.CPU; import com.cloud.network.router.VirtualRouter.Role; import com.cloud.vm.VirtualMachine; @APICommand(name = "listRouters", description = "List routers.", responseObject = DomainRouterResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListRoutersCmd.class.getName()); ///////////////////////////////////////////////////// @@ -88,6 +87,11 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { description = "if true is passed for this parameter, also fetch last executed health check results for the router. Default is false") private Boolean fetchHealthCheckResults; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "CPU arch of the router", + since = "4.20.1") + private String arch; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -148,6 +152,10 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { return BooleanUtils.isTrue(fetchHealthCheckResults); } + public CPU.CPUArch getArch() { + return StringUtils.isBlank(arch) ? null : CPU.CPUArch.fromType(arch); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java index 6eb24dce074..424b8c29d04 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java @@ -21,7 +21,6 @@ import java.util.List; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -42,7 +41,6 @@ import com.cloud.network.element.VirtualRouterElementService; @APICommand(name = "listVirtualRouterElements", description = "Lists all available virtual router elements.", responseObject = VirtualRouterProviderResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListVirtualRouterElementsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListVirtualRouterElementsCmd.class.getName()); // TODO, VirtualRouterElementServer is not singleton in system! @Inject diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java index 6e334d7e442..1d97dd80309 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.router; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -39,7 +38,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "rebootRouter", description = "Starts a router.", responseObject = DomainRouterResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RebootRouterCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RebootRouterCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java index 121b2a1bd11..24ab7881037 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.router; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -41,7 +40,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "startRouter", responseObject = DomainRouterResponse.class, description = "Starts a router.", entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class StartRouterCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StartRouterCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java index 2da38d90426..971086a57cf 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.router; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -40,7 +39,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "stopRouter", description = "Stops a router.", responseObject = DomainRouterResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class StopRouterCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StopRouterCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java index 2d5255614c6..3265a089d67 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.router; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "changeServiceForRouter", description = "Upgrades domain router to a new service offering", responseObject = DomainRouterResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpgradeRouterCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpgradeRouterCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/UpgradeRouterTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/UpgradeRouterTemplateCmd.java index fa0fe5800ee..74464cab315 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/router/UpgradeRouterTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/router/UpgradeRouterTemplateCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.router; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -43,7 +42,6 @@ import com.cloud.user.Account; @APICommand(name = "upgradeRouterTemplate", description = "Upgrades router to use newer template", responseObject = BaseResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpgradeRouterTemplateCmd extends org.apache.cloudstack.api.BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpgradeRouterTemplateCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java index b8ab1461a2b..7c8f0e21afb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreCmd.java @@ -21,7 +21,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "addImageStore", description = "Adds backup image store.", responseObject = ImageStoreResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddImageStoreCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddImageStoreCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -137,7 +135,7 @@ public class AddImageStoreCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage"); } } catch (DiscoveryException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java index 34ff171b91f..2fe3c7cd106 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddImageStoreS3CMD.java @@ -38,7 +38,6 @@ import java.util.HashMap; import java.util.Map; import com.cloud.utils.storage.S3.ClientOptions; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -59,7 +58,6 @@ import com.cloud.storage.ImageStore; @APICommand(name = "addImageStoreS3", description = "Adds S3 Image Store", responseObject = ImageStoreResponse.class, since = "4.7.0", requestHasSensitiveInfo = true, responseHasSensitiveInfo = false) public final class AddImageStoreS3CMD extends BaseCmd implements ClientOptions { - public static final Logger s_logger = Logger.getLogger(AddImageStoreS3CMD.class.getName()); private static final String s_name = "addImageStoreS3Response"; @@ -141,7 +139,7 @@ public final class AddImageStoreS3CMD extends BaseCmd implements ClientOptions { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add S3 Image Store."); } } catch (DiscoveryException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddObjectStoragePoolCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddObjectStoragePoolCmd.java index a538962e076..b779ba2a2b4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddObjectStoragePoolCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/AddObjectStoragePoolCmd.java @@ -25,7 +25,6 @@ import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ObjectStoreResponse; -import org.apache.log4j.Logger; import java.util.Collection; import java.util.HashMap; @@ -35,7 +34,6 @@ import java.util.Map; @APICommand(name = "addObjectStoragePool", description = "Adds a object storage pool", responseObject = ObjectStoreResponse.class, since = "4.19.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddObjectStoragePoolCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddObjectStoragePoolCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -125,7 +123,7 @@ public class AddObjectStoragePoolCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add object storage"); } } catch (Exception ex) { - s_logger.error("Exception: ", ex); + logger.error("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java index a694aba30fb..7e925f286d0 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.storage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "cancelStorageMaintenance", description = "Cancels maintenance for primary storage", responseObject = StoragePoolResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CancelPrimaryStorageMaintenanceCmd.class.getName()); private static final String s_name = "cancelprimarystoragemaintenanceresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CreateSecondaryStagingStoreCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CreateSecondaryStagingStoreCmd.java index 08069446893..5776eb6464c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CreateSecondaryStagingStoreCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CreateSecondaryStagingStoreCmd.java @@ -21,7 +21,6 @@ package org.apache.cloudstack.api.command.admin.storage; import java.util.HashMap; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.user.Account; @APICommand(name = "createSecondaryStagingStore", description = "create secondary staging store.", responseObject = ImageStoreResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateSecondaryStagingStoreCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateSecondaryStagingStoreCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -113,7 +111,7 @@ public class CreateSecondaryStagingStoreCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage"); } } catch (Exception ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java index 477d7570dfa..75813a7aabf 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.storage; import java.net.UnknownHostException; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -41,7 +40,6 @@ import com.cloud.user.Account; @APICommand(name = "createStoragePool", description = "Creates a storage pool.", responseObject = StoragePoolResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateStoragePoolCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateStoragePoolCmd.class.getName()); ///////////////////////////////////////////////////// @@ -170,13 +168,13 @@ public class CreateStoragePoolCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add storage pool"); } } catch (ResourceUnavailableException ex1) { - s_logger.warn("Exception: ", ex1); + logger.warn("Exception: ", ex1); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex1.getMessage()); } catch (ResourceInUseException ex2) { - s_logger.warn("Exception: ", ex2); + logger.warn("Exception: ", ex2); throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, ex2.getMessage()); } catch (UnknownHostException ex3) { - s_logger.warn("Exception: ", ex3); + logger.warn("Exception: ", ex3); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex3.getMessage()); } catch (Exception ex4) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex4.getMessage()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteImageStoreCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteImageStoreCmd.java index 194f0baf603..50a9d9a6f39 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteImageStoreCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteImageStoreCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.storage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,7 +31,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteImageStore", description = "Deletes an image store or Secondary Storage.", responseObject = SuccessResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteImageStoreCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteImageStoreCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteObjectStoragePoolCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteObjectStoragePoolCmd.java index ed305d9689d..6cb38d4c862 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteObjectStoragePoolCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteObjectStoragePoolCmd.java @@ -25,12 +25,10 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ObjectStoreResponse; import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.log4j.Logger; @APICommand(name = "deleteObjectStoragePool", description = "Deletes an Object Storage Pool", responseObject = SuccessResponse.class, since = "4.19.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteObjectStoragePoolCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteObjectStoragePoolCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java index d87768e7f39..28f71e0740f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.storage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteStoragePool", description = "Deletes a storage pool.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeletePoolCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeletePoolCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteSecondaryStagingStoreCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteSecondaryStagingStoreCmd.java index 34a26461fa8..a0c2731ccda 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteSecondaryStagingStoreCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/DeleteSecondaryStagingStoreCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.storage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,7 +31,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteSecondaryStagingStore", description = "Deletes a secondary staging store .", responseObject = SuccessResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteSecondaryStagingStoreCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteSecondaryStagingStoreCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/FindStoragePoolsForMigrationCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/FindStoragePoolsForMigrationCmd.java index b19fa78bdd4..a45f72766dc 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/FindStoragePoolsForMigrationCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/FindStoragePoolsForMigrationCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.storage.StoragePool; import com.cloud.utils.Pair; @@ -38,7 +37,6 @@ import com.cloud.utils.Pair; @APICommand(name = "findStoragePoolsForMigration", description = "Lists storage pools available for migration of a volume.", responseObject = StoragePoolResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class FindStoragePoolsForMigrationCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(FindStoragePoolsForMigrationCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListImageStoresCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListImageStoresCmd.java index a9eac3ed76d..5270569de44 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListImageStoresCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListImageStoresCmd.java @@ -23,12 +23,10 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ImageStoreResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; @APICommand(name = "listImageStores", description = "Lists image stores.", responseObject = ImageStoreResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListImageStoresCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListImageStoresCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListObjectStoragePoolsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListObjectStoragePoolsCmd.java index 9d8d8eccc3c..005a1a54444 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListObjectStoragePoolsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListObjectStoragePoolsCmd.java @@ -23,13 +23,11 @@ import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ObjectStoreResponse; -import org.apache.log4j.Logger; @APICommand(name = "listObjectStoragePools", description = "Lists object storage pools.", responseObject = ObjectStoreResponse.class, since = "4.19.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class ListObjectStoragePoolsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListObjectStoragePoolsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListSecondaryStagingStoresCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListSecondaryStagingStoresCmd.java index e315c8a6d47..0cad16a247f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListSecondaryStagingStoresCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListSecondaryStagingStoresCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.storage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -29,7 +28,6 @@ import org.apache.cloudstack.api.response.ZoneResponse; @APICommand(name = "listSecondaryStagingStores", description = "Lists secondary staging stores.", responseObject = ImageStoreResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListSecondaryStagingStoresCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListSecondaryStagingStoresCmd.class.getName()); private static final String s_name = "listsecondarystagingstoreresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java index 3da99de050b..57a87939b6b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.storage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -33,7 +32,6 @@ import org.apache.cloudstack.api.response.ZoneResponse; @APICommand(name = "listStoragePools", description = "Lists storage pools.", responseObject = StoragePoolResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListStoragePoolsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListStoragePoolsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStorageProvidersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStorageProvidersCmd.java index 347b66061f6..efe7a23b5cb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStorageProvidersCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStorageProvidersCmd.java @@ -20,7 +20,6 @@ package org.apache.cloudstack.api.command.admin.storage; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.exception.ResourceUnavailableException; @APICommand(name = "listStorageProviders", description = "Lists storage providers.", responseObject = StorageProviderResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListStorageProvidersCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListStorageProvidersCmd.class.getName()); @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, description = "the type of storage provider: either primary or image", required = true) private String type; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStorageTagsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStorageTagsCmd.java index 43981ee1a3d..d9bb5d4cd93 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStorageTagsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/ListStorageTagsCmd.java @@ -18,7 +18,6 @@ */ package org.apache.cloudstack.api.command.admin.storage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.BaseListCmd; @@ -27,7 +26,6 @@ import org.apache.cloudstack.api.response.StorageTagResponse; @APICommand(name = "listStorageTags", description = "Lists storage tags", responseObject = StorageTagResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListStorageTagsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListStorageTagsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/MigrateSecondaryStorageDataCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/MigrateSecondaryStorageDataCmd.java index de9b55a9ff1..8f5a7aced3f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/MigrateSecondaryStorageDataCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/MigrateSecondaryStorageDataCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ImageStoreResponse; import org.apache.cloudstack.api.response.MigrationResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; @@ -41,7 +40,6 @@ import com.cloud.event.EventTypes; authorized = {RoleType.Admin}) public class MigrateSecondaryStorageDataCmd extends BaseAsyncCmd { - public static final Logger LOGGER = Logger.getLogger(MigrateSecondaryStorageDataCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java index ddabefb14c8..818b3a5bbea 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.storage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "enableStorageMaintenance", description = "Puts storage pool into maintenance state", responseObject = StoragePoolResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class PreparePrimaryStorageForMaintenanceCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(PreparePrimaryStorageForMaintenanceCmd.class.getName()); private static final String s_name = "prepareprimarystorageformaintenanceresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/SyncStoragePoolCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/SyncStoragePoolCmd.java index d7a783a4ff4..9f81f2f6c86 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/SyncStoragePoolCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/SyncStoragePoolCmd.java @@ -33,7 +33,6 @@ import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.context.CallContext; -import java.util.logging.Logger; @APICommand(name = "syncStoragePool", description = "Sync storage pool with management server (currently supported for Datastore Cluster in VMware and syncs the datastores in it)", @@ -45,7 +44,6 @@ import java.util.logging.Logger; ) public class SyncStoragePoolCmd extends BaseAsyncCmd { - public static final Logger LOGGER = Logger.getLogger(SyncStoragePoolCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateCloudToUseObjectStoreCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateCloudToUseObjectStoreCmd.java index 3351d389c6f..5ac34f27bad 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateCloudToUseObjectStoreCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateCloudToUseObjectStoreCmd.java @@ -21,7 +21,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.user.Account; @APICommand(name = "updateCloudToUseObjectStore", description = "Migrate current NFS secondary storages to use object store.", responseObject = ImageStoreResponse.class, since = "4.3.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateCloudToUseObjectStoreCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateCloudToUseObjectStoreCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -130,7 +128,7 @@ public class UpdateCloudToUseObjectStoreCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage"); } } catch (DiscoveryException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateImageStoreCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateImageStoreCmd.java index 87d056cabf7..0e1631a46ba 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateImageStoreCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateImageStoreCmd.java @@ -25,14 +25,12 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ImageStoreResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.storage.ImageStore; @APICommand(name = UpdateImageStoreCmd.APINAME, description = "Updates image store read-only status", responseObject = ImageStoreResponse.class, entityType = {ImageStore.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.15.0") public class UpdateImageStoreCmd extends BaseCmd { - private static final Logger LOG = Logger.getLogger(UpdateImageStoreCmd.class.getName()); public static final String APINAME = "updateImageStore"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStorageCapabilitiesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStorageCapabilitiesCmd.java index 8403d3c6241..716c95b45c3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStorageCapabilitiesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStorageCapabilitiesCmd.java @@ -29,14 +29,12 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; @APICommand(name = "updateStorageCapabilities", description = "Syncs capabilities of storage pools", responseObject = StoragePoolResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.16.0") public class UpdateStorageCapabilitiesCmd extends BaseCmd { - private static final Logger LOG = Logger.getLogger(UpdateStorageCapabilitiesCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java index 7a907e0f76a..6f522fe1e8c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java @@ -20,7 +20,6 @@ import java.util.List; import java.util.Map; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,12 +31,13 @@ import org.apache.cloudstack.api.response.StoragePoolResponse; import com.cloud.storage.StoragePool; import com.cloud.user.Account; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.ObjectUtils; @SuppressWarnings("rawtypes") @APICommand(name = "updateStoragePool", description = "Updates a storage pool.", responseObject = StoragePoolResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateStoragePoolCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateStoragePoolCmd.class.getName()); ///////////////////////////////////////////////////// @@ -149,7 +149,19 @@ public class UpdateStoragePoolCmd extends BaseCmd { @Override public void execute() { - StoragePool result = _storageService.updateStoragePool(this); + StoragePool result = null; + if (ObjectUtils.anyNotNull(name, capacityIops, capacityBytes, url, isTagARule, tags) || + MapUtils.isNotEmpty(details)) { + result = _storageService.updateStoragePool(this); + } else { + result = _storageService.getStoragePool(getId()); + } + + if (enabled != null) { + result = enabled ? _storageService.enablePrimaryStoragePool(id) + : _storageService.disablePrimaryStoragePool(id); + } + if (result != null) { StoragePoolResponse response = _responseGenerator.createStoragePoolResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/heuristics/RemoveSecondaryStorageSelectorCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/heuristics/RemoveSecondaryStorageSelectorCmd.java index 79554f44782..468c87d4d99 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/heuristics/RemoveSecondaryStorageSelectorCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/heuristics/RemoveSecondaryStorageSelectorCmd.java @@ -27,7 +27,7 @@ import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.secstorage.heuristics.Heuristic; @APICommand(name = "removeSecondaryStorageSelector", description = "Removes an existing secondary storage selector.", since = "4.19.0", responseObject = - SecondaryStorageHeuristicsResponse.class, requestHasSensitiveInfo = false, entityType = {Heuristic.class}, responseHasSensitiveInfo = false, authorized = {RoleType.Admin}) + SuccessResponse.class, requestHasSensitiveInfo = false, entityType = {Heuristic.class}, responseHasSensitiveInfo = false, authorized = {RoleType.Admin}) public class RemoveSecondaryStorageSelectorCmd extends BaseCmd { @Parameter(name = ApiConstants.ID, type = BaseCmd.CommandType.UUID, entityType = SecondaryStorageHeuristicsResponse.class, required = true, description = "The unique identifier of the secondary storage selector to be removed.") diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java index 7eb87006d0d..bd72f3213de 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.swift; import java.util.HashMap; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "addSwift", description = "Adds Swift.", responseObject = ImageStoreResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddSwiftCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddSwiftCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -102,7 +100,7 @@ public class AddSwiftCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Swift secondary storage"); } } catch (DiscoveryException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java index 6d7bfbaf1b1..e21a23349bb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.swift; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -31,7 +30,6 @@ import com.cloud.user.Account; @APICommand(name = "listSwifts", description = "List Swift.", responseObject = ImageStoreResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListSwiftsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListSwiftsCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java index 7ed536f6d4c..7e0faab2fb5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.systemvm; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -37,7 +36,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "destroySystemVm", responseObject = SystemVmResponse.class, description = "Destroys a system virtual machine.", entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DestroySystemVmCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DestroySystemVmCmd.class.getName()); @ACL(accessType = AccessType.OperateEntry) diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/ListSystemVMsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/ListSystemVMsCmd.java index b6f8c92fa17..13113e17ea4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/ListSystemVMsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/ListSystemVMsCmd.java @@ -19,8 +19,6 @@ package org.apache.cloudstack.api.command.admin.systemvm; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; @@ -32,14 +30,15 @@ import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.SystemVmResponse; import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.commons.lang3.StringUtils; +import com.cloud.cpu.CPU; import com.cloud.utils.Pair; import com.cloud.vm.VirtualMachine; @APICommand(name = "listSystemVms", description = "List system virtual machines.", responseObject = SystemVmResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListSystemVMsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListSystemVMsCmd.class.getName()); ///////////////////////////////////////////////////// @@ -76,6 +75,11 @@ public class ListSystemVMsCmd extends BaseListCmd { since = "3.0.1") private Long storageId; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "CPU arch of the system VM", + since = "4.20.1") + private String arch; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -112,6 +116,10 @@ public class ListSystemVMsCmd extends BaseListCmd { return storageId; } + public CPU.CPUArch getArch() { + return StringUtils.isBlank(arch) ? null : CPU.CPUArch.fromType(arch); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java index f0f7aca16c8..ccc6093aa83 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java @@ -31,7 +31,6 @@ import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.SystemVmResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang.BooleanUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -47,7 +46,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "migrateSystemVm", description = "Attempts Migration of a system virtual machine to the host specified.", responseObject = SystemVmResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class MigrateSystemVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(MigrateSystemVMCmd.class.getName()); ///////////////////////////////////////////////////// @@ -171,16 +169,16 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to migrate the system vm"); } } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } catch (ManagementServerException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } catch (VirtualMachineMigrationException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/PatchSystemVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/PatchSystemVMCmd.java index ae3c36b4948..4f4b2631667 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/PatchSystemVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/PatchSystemVMCmd.java @@ -30,13 +30,11 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.SystemVmResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; @APICommand(name = "patchSystemVm", description = "Attempts to live patch systemVMs - CPVM, SSVM ", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = { RoleType.Admin }, since = "4.17.0") public class PatchSystemVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(PatchSystemVMCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java index 0ba7e0c2edf..30bd51184ac 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.systemvm; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -37,7 +36,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "rebootSystemVm", description = "Reboots a system VM.", responseObject = SystemVmResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RebootSystemVmCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RebootSystemVmCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java index 264806f0350..d822d4fc26e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/ScaleSystemVMCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.systemvm; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -46,7 +45,6 @@ import com.cloud.vm.VirtualMachine; + "The system vm must be in a \"Stopped\" state for " + "this command to take effect.", entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ScaleSystemVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ScaleSystemVMCmd.class.getName()); private static final String s_name = "changeserviceforsystemvmresponse"; ///////////////////////////////////////////////////// @@ -111,16 +109,16 @@ public class ScaleSystemVMCmd extends BaseAsyncCmd { try { result = _mgr.upgradeSystemVM(this); } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (ManagementServerException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (VirtualMachineMigrationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } if (result != null) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java index 0cb517f4058..eac3d64ab59 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.systemvm; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -37,7 +36,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "startSystemVm", responseObject = SystemVmResponse.class, description = "Starts a system virtual machine.", entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class StartSystemVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StartSystemVMCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java index 4bb533ce5b6..1d84382f5d2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.systemvm; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -39,7 +38,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "stopSystemVm", description = "Stops a system VM.", responseObject = SystemVmResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class StopSystemVmCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StopSystemVmCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java index 95d9ab562bf..a42f0052249 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.systemvm; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -41,7 +40,6 @@ import com.cloud.vm.VirtualMachine; + "The system vm must be in a \"Stopped\" state for " + "this command to take effect.", entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpgradeSystemVMCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpgradeSystemVMCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java index 9b8d402864a..9a59efb19f2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.template; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -38,7 +37,6 @@ import com.cloud.user.Account; @APICommand(name = "prepareTemplate", responseObject = TemplateResponse.class, description = "load template into primary storage", entityType = {VirtualMachineTemplate.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class PrepareTemplateCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(PrepareTemplateCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficMonitorCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficMonitorCmd.java index 95593714feb..5c0f1fc1cd2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficMonitorCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficMonitorCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.usage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "addTrafficMonitor", description = "Adds Traffic Monitor Host for Direct Network Usage", responseObject = TrafficMonitorResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddTrafficMonitorCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddTrafficMonitorCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java index 809129402a8..b1810676b74 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.usage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "addTrafficType", description = "Adds traffic type to a physical network", responseObject = TrafficTypeResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(AddTrafficTypeCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficMonitorCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficMonitorCmd.java index ff371d6e83d..8fdb3af399c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficMonitorCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficMonitorCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.usage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -33,7 +32,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteTrafficMonitor", description = "Deletes an traffic monitor host.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteTrafficMonitorCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteTrafficMonitorCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java index a728690a09d..a1e4ebda09a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.usage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteTrafficType", description = "Deletes traffic type of a physical network", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteTrafficTypeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteTrafficTypeCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/GenerateUsageRecordsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/GenerateUsageRecordsCmd.java index 65b864f2ab6..a0314586d92 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/GenerateUsageRecordsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/GenerateUsageRecordsCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.usage; import java.util.Date; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class GenerateUsageRecordsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(GenerateUsageRecordsCmd.class.getName()); ///////////////////////////////////////////////////// @@ -49,13 +47,13 @@ public class GenerateUsageRecordsCmd extends BaseCmd { @Parameter(name = ApiConstants.END_DATE, type = CommandType.DATE, - required = true, + required = false, description = "End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.") private Date endDate; @Parameter(name = ApiConstants.START_DATE, type = CommandType.DATE, - required = true, + required = false, description = "Start date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-01.") private Date startDate; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficMonitorsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficMonitorsCmd.java index f3a65bbfffd..ed42bc42dbd 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficMonitorsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficMonitorsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.usage; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.host.Host; @APICommand(name = "listTrafficMonitors", description = "List traffic monitor Hosts.", responseObject = TrafficMonitorResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListTrafficMonitorsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListTrafficMonitorsCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java index 97f43155be6..1ad8872db96 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.usage; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -44,7 +43,6 @@ import com.cloud.utils.Pair; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListTrafficTypeImplementorsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListTrafficTypeImplementorsCmd.class); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java index 6e36ca3bd8d..d106a736fca 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.usage; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listTrafficTypes", description = "Lists traffic types of a given physical network.", responseObject = ProviderResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListTrafficTypesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListTrafficTypesCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListUsageRecordsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListUsageRecordsCmd.java index 3cb148c2af0..9ce1fcb2bc9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListUsageRecordsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListUsageRecordsCmd.java @@ -53,16 +53,12 @@ public class ListUsageRecordsCmd extends BaseListCmd { @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "List usage records for the specified domain.") private Long domainId; - @Parameter(name = ApiConstants.END_DATE, - type = CommandType.DATE, - required = true, - description = "End date range for usage record query (use format \"yyyy-MM-dd\" or the new format \"yyyy-MM-dd HH:mm:ss\", e.g. startDate=2015-01-01 or startdate=2015-01-01 10:30:00).") + @Parameter(name = ApiConstants.END_DATE, type = CommandType.DATE, required = true, description = "End date range for usage record query. " + + ApiConstants.PARAMETER_DESCRIPTION_END_DATE_POSSIBLE_FORMATS) private Date endDate; - @Parameter(name = ApiConstants.START_DATE, - type = CommandType.DATE, - required = true, - description = "Start date range for usage record query (use format \"yyyy-MM-dd\" or the new format \"yyyy-MM-dd HH:mm:ss\", e.g. startDate=2015-01-01 or startdate=2015-01-01 11:00:00).") + @Parameter(name = ApiConstants.START_DATE, type = CommandType.DATE, required = true, description = "Start date range for usage record query. " + + ApiConstants.PARAMETER_DESCRIPTION_START_DATE_POSSIBLE_FORMATS) private Date startDate; @Parameter(name = ApiConstants.ACCOUNT_ID, type = CommandType.UUID, entityType = AccountResponse.class, description = "List usage records for the specified account") @@ -137,11 +133,11 @@ public class ListUsageRecordsCmd extends BaseListCmd { } public void setEndDate(Date endDate) { - this.endDate = endDate == null ? null : new Date(endDate.getTime()); + this.endDate = endDate; } public void setStartDate(Date startDate) { - this.startDate = startDate == null ? null : new Date(startDate.getTime()); + this.startDate = startDate; } public void setAccountId(Long accountId) { @@ -167,8 +163,8 @@ public class ListUsageRecordsCmd extends BaseListCmd { @Override public void execute() { Pair, Integer> usageRecords = _usageService.getUsageRecords(this); - ListResponse response = new ListResponse(); - List usageResponses = new ArrayList(); + ListResponse response = new ListResponse<>(); + List usageResponses = new ArrayList<>(); Map> resourceTagResponseMap = null; if (usageRecords != null) { //read the resource tags details for all the resources in usage data and store in Map diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListUsageTypesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListUsageTypesCmd.java index 15f9dd20e29..b993735dba7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListUsageTypesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListUsageTypesCmd.java @@ -18,19 +18,18 @@ package org.apache.cloudstack.api.command.admin.usage; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.UsageTypeResponse; +import org.apache.cloudstack.usage.UsageTypes; import com.cloud.user.Account; @APICommand(name = "listUsageTypes", description = "List Usage Types", responseObject = UsageTypeResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListUsageTypesCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ListUsageTypesCmd.class.getName()); @Override public long getEntityOwnerId() { @@ -39,8 +38,8 @@ public class ListUsageTypesCmd extends BaseCmd { @Override public void execute() { - List result = _usageService.listUsageTypes(); - ListResponse response = new ListResponse(); + List result = UsageTypes.listUsageTypes(); + ListResponse response = new ListResponse<>(); response.setResponses(result); response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/RemoveRawUsageRecordsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/RemoveRawUsageRecordsCmd.java index 710a11c0d7f..3e698e61442 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/RemoveRawUsageRecordsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/RemoveRawUsageRecordsCmd.java @@ -29,11 +29,9 @@ import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.log4j.Logger; @APICommand(name = "removeRawUsageRecords", description = "Safely removes raw records from cloud_usage table", responseObject = SuccessResponse.class, since = "4.6.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RemoveRawUsageRecordsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(RemoveRawUsageRecordsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java index 103e58c4e03..c7b3c2b433b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.usage; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "updateTrafficType", description = "Updates traffic type of a physical network", responseObject = TrafficTypeResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateTrafficTypeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateTrafficTypeCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java index e8f5944e407..e2a2baecc86 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.user.Account; import com.cloud.user.User; @@ -35,7 +34,6 @@ import com.cloud.user.User; @APICommand(name = "createUser", description = "Creates a user for an account that already exists", responseObject = UserResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = true) public class CreateUserCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateUserCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java index a4f13d5e9c7..ddf21affb53 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.user; import javax.inject.Inject; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.user.User; @APICommand(name = "deleteUser", description = "Deletes a user for an account", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteUserCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteUserCmd.class.getName()); ///////////////////////////////////////////////////// @@ -86,11 +84,10 @@ public class DeleteUserCmd extends BaseCmd { public void execute() { CallContext.current().setEventDetails("UserId: " + getId()); boolean result = _regionService.deleteUser(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - this.setResponseObject(response); - } else { + if (!result) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete user"); } + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java index f7a51d0b1d3..974c1c7bebe 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.user; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -39,7 +38,6 @@ import com.cloud.user.UserAccount; @APICommand(name = "disableUser", description = "Disables a user account", responseObject = UserResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class DisableUserCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DisableUserCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java index f13eac8f2a9..77d8d530daf 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.admin.user; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.UserAccount; @APICommand(name = "enableUser", description = "Enables a user account", responseObject = UserResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class EnableUserCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(EnableUserCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/GetUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/GetUserCmd.java index 5fcad8068b1..3427cef3366 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/GetUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/GetUserCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.user; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -30,7 +29,6 @@ import com.cloud.user.UserAccount; @APICommand(name = "getUser", description = "Find user account by API key", responseObject = UserResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class GetUserCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(GetUserCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/GetUserKeysCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/GetUserKeysCmd.java index 253a55652ea..cdd239f72b5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/GetUserKeysCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/GetUserKeysCmd.java @@ -20,6 +20,7 @@ package org.apache.cloudstack.api.command.admin.user; import com.cloud.user.Account; import com.cloud.user.User; +import com.cloud.utils.Pair; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -29,7 +30,6 @@ import org.apache.cloudstack.api.response.RegisterResponse; import org.apache.cloudstack.api.response.UserResponse; import java.util.Map; -import org.apache.log4j.Logger; @APICommand(name = "getUserKeys", description = "This command allows the user to query the seceret and API keys for the account", @@ -44,7 +44,6 @@ public class GetUserKeysCmd extends BaseCmd{ @Parameter(name= ApiConstants.ID, type = CommandType.UUID, entityType = UserResponse.class, required = true, description = "ID of the user whose keys are required") private Long id; - public static final Logger s_logger = Logger.getLogger(GetUserKeysCmd.class.getName()); public Long getID(){ return id; @@ -56,11 +55,13 @@ public class GetUserKeysCmd extends BaseCmd{ else return Account.ACCOUNT_ID_SYSTEM; } public void execute(){ - Map keys = _accountService.getKeys(this); + Pair> keys = _accountService.getKeys(this); + RegisterResponse response = new RegisterResponse(); if(keys != null){ - response.setApiKey(keys.get("apikey")); - response.setSecretKey(keys.get("secretkey")); + response.setApiKeyAccess(keys.first()); + response.setApiKey(keys.second().get("apikey")); + response.setSecretKey(keys.second().get("secretkey")); } response.setObjectName("userkeys"); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/ListUsersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/ListUsersCmd.java index a516a30e769..27a78c738c9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/ListUsersCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/ListUsersCmd.java @@ -19,22 +19,23 @@ package org.apache.cloudstack.api.command.admin.user; import com.cloud.server.ResourceIcon; import com.cloud.server.ResourceTag; import com.cloud.user.Account; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.ResourceIconResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListAccountResourcesCmd; import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject.ResponseView; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.UserResponse; import java.util.List; @APICommand(name = "listUsers", description = "Lists user accounts", responseObject = UserResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) -public class ListUsersCmd extends BaseListAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListUsersCmd.class.getName()); + responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) +public class ListUsersCmd extends BaseListAccountResourcesCmd implements UserCmd { ///////////////////////////////////////////////////// @@ -55,6 +56,9 @@ public class ListUsersCmd extends BaseListAccountResourcesCmd { @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, description = "List user by the username") private String username; + @Parameter(name = ApiConstants.API_KEY_ACCESS, type = CommandType.STRING, description = "List users by the Api key access value", since = "4.20.1.0", authorized = {RoleType.Admin}) + private String apiKeyAccess; + @Parameter(name = ApiConstants.SHOW_RESOURCE_ICON, type = CommandType.BOOLEAN, description = "flag to display the resource icon for users") private Boolean showIcon; @@ -79,6 +83,10 @@ public class ListUsersCmd extends BaseListAccountResourcesCmd { return username; } + public String getApiKeyAccess() { + return apiKeyAccess; + } + public Boolean getShowIcon() { return showIcon != null ? showIcon : false; } @@ -89,7 +97,7 @@ public class ListUsersCmd extends BaseListAccountResourcesCmd { @Override public void execute() { - ListResponse response = _queryService.searchForUsers(this); + ListResponse response = _queryService.searchForUsers(getResponseView(), this); response.setResponseName(getCommandName()); this.setResponseObject(response); if (response != null && response.getCount() > 0 && getShowIcon()) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java index df6ef4f7b0b..5c8bff0732a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.user; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -33,7 +32,6 @@ import com.cloud.user.UserAccount; @APICommand(name = "lockUser", description = "Locks a user account", responseObject = UserResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class LockUserCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(LockUserCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/MoveUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/MoveUserCmd.java index b7090977d96..e57258a4571 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/MoveUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/MoveUserCmd.java @@ -32,7 +32,6 @@ import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.region.RegionService; import org.apache.commons.lang3.ObjectUtils; -import org.apache.log4j.Logger; import com.cloud.user.Account; import com.cloud.user.User; @@ -46,7 +45,6 @@ import com.google.common.base.Preconditions; since = "4.11", authorized = {RoleType.Admin}) public class MoveUserCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(MoveUserCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/RegisterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/RegisterCmd.java index 4199015b9ca..b3e7d2bec82 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/RegisterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/RegisterCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.user; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.User; description = "This command allows a user to register for the developer API, returning a secret key and an API key. This request is made through the integration API port, so it is a privileged command and must be made on behalf of a user. It is up to the implementer just how the username and password are entered, and then how that translates to an integration API request. Both secret key and API key should be returned to the user", requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class RegisterCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(RegisterCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java index cb9f6e189f0..3d7f51ae220 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java @@ -18,6 +18,7 @@ package org.apache.cloudstack.api.command.admin.user; import javax.inject.Inject; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; @@ -28,7 +29,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.region.RegionService; -import org.apache.log4j.Logger; import com.cloud.user.Account; import com.cloud.user.User; @@ -37,7 +37,6 @@ import com.cloud.user.UserAccount; @APICommand(name = "updateUser", description = "Updates a user account", responseObject = UserResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = true) public class UpdateUserCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateUserCmd.class.getName()); ///////////////////////////////////////////////////// @@ -68,9 +67,12 @@ public class UpdateUserCmd extends BaseCmd { @Parameter(name = ApiConstants.CURRENT_PASSWORD, type = CommandType.STRING, description = "Current password that was being used by the user. You must inform the current password when updating the password.", acceptedOnAdminPort = false) private String currentPassword; - @Parameter(name = ApiConstants.SECRET_KEY, type = CommandType.STRING, description = "The secret key for the user. Must be specified with userApiKey") + @Parameter(name = ApiConstants.USER_SECRET_KEY, type = CommandType.STRING, description = "The secret key for the user. Must be specified with userApiKey") private String secretKey; + @Parameter(name = ApiConstants.API_KEY_ACCESS, type = CommandType.STRING, description = "Determines if Api key access for this user is enabled, disabled or inherits the value from its parent, the owning account", since = "4.20.1.0", authorized = {RoleType.Admin}) + private String apiKeyAccess; + @Parameter(name = ApiConstants.TIMEZONE, type = CommandType.STRING, description = "Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") @@ -122,6 +124,10 @@ public class UpdateUserCmd extends BaseCmd { return secretKey; } + public String getApiKeyAccess() { + return apiKeyAccess; + } + public String getTimezone() { return timezone; } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java index feef18bbed1..c0ba99a8233 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.vlan; import com.cloud.utils.net.NetUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,10 +39,11 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; +import java.util.Objects; + @APICommand(name = "createVlanIpRange", description = "Creates a VLAN IP range.", responseObject = VlanIpRangeResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateVlanIpRangeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateVlanIpRangeCmd.class.getName()); ///////////////////////////////////////////////////// @@ -114,6 +114,9 @@ public class CreateVlanIpRangeCmd extends BaseCmd { @Parameter(name = ApiConstants.FOR_SYSTEM_VMS, type = CommandType.BOOLEAN, description = "true if IP range is set to system vms, false if not") private Boolean forSystemVms; + @Parameter(name = ApiConstants.FOR_NSX, type = CommandType.BOOLEAN, description = "true if the IP range is used for NSX resource", since = "4.20.0") + private boolean forNsx; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -154,7 +157,14 @@ public class CreateVlanIpRangeCmd extends BaseCmd { return startIp; } + public boolean isForNsx() { + return !Objects.isNull(forNsx) && forNsx; + } + public String getVlan() { + if ((vlan == null || vlan.isEmpty()) && !isForNsx()) { + vlan = "untagged"; + } return vlan; } @@ -223,10 +233,10 @@ public class CreateVlanIpRangeCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create vlan ip range"); } } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { - s_logger.info(ex); + logger.info(ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/DedicatePublicIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/DedicatePublicIpRangeCmd.java index 7c122dfc22e..cac029f3aa1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/DedicatePublicIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/DedicatePublicIpRangeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.vlan; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "dedicatePublicIpRange", description = "Dedicates a Public IP range to an account", responseObject = VlanIpRangeResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DedicatePublicIpRangeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DedicatePublicIpRangeCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java index 390759c2c06..7ab0b053004 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.vlan; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,7 +31,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteVlanIpRange", description = "Deletes a VLAN IP range.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteVlanIpRangeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVlanIpRangeCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/ListVlanIpRangesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/ListVlanIpRangesCmd.java index 3b5370e3f15..c11b505c684 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/ListVlanIpRangesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/ListVlanIpRangesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.vlan; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listVlanIpRanges", description = "Lists all VLAN IP ranges.", responseObject = VlanIpRangeResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListVlanIpRangesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListVlanIpRangesCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/ReleasePublicIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/ReleasePublicIpRangeCmd.java index 846433a60fc..be4cea41cd8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/ReleasePublicIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/ReleasePublicIpRangeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.vlan; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,7 +31,6 @@ import com.cloud.user.Account; @APICommand(name = "releasePublicIpRange", description = "Releases a Public IP range back to the system pool", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ReleasePublicIpRangeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ReleasePublicIpRangeCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/UpdateVlanIpRangeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/UpdateVlanIpRangeCmd.java index caaf4c5ae01..df6d99f8e2a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/UpdateVlanIpRangeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vlan/UpdateVlanIpRangeCmd.java @@ -24,7 +24,6 @@ import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.VlanIpRangeResponse; -import org.apache.log4j.Logger; import com.cloud.dc.Vlan; import com.cloud.exception.ConcurrentOperationException; @@ -39,7 +38,6 @@ import com.cloud.utils.net.NetUtils; authorized = {RoleType.Admin}) public class UpdateVlanIpRangeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVlanIpRangeCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -149,7 +147,7 @@ public class UpdateVlanIpRangeCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to Update vlan ip range"); } } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java index 1d53bbb39ad..6f6a5237b3d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.vm; import java.util.List; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -46,7 +45,6 @@ import com.cloud.vm.VirtualMachine; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class AssignVMCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AssignVMCmd.class.getName()); ///////////////////////////////////////////////////// @@ -122,27 +120,16 @@ public class AssignVMCmd extends BaseCmd { @Override public void execute() { try { - UserVm userVm = _userVmService.moveVMToUser(this); - if (userVm == null) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to move vm"); - } + UserVm userVm = _userVmService.moveVmToUser(this); UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Full, "virtualmachine", userVm).get(0); response.setResponseName(getCommandName()); setResponseObject(response); - } catch (InvalidParameterValueException e){ - e.printStackTrace(); - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } catch (Exception e) { - s_logger.error("Failed to move vm due to: " + e.getStackTrace()); - if (e.getMessage() != null) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to move vm due to " + e.getMessage()); - } else if (e.getCause() != null) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to move vm due to " + e.getCause()); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to move vm"); - } + ApiErrorCode errorCode = e instanceof InvalidParameterValueException ? ApiErrorCode.PARAM_ERROR : ApiErrorCode.INTERNAL_ERROR; + String msg = String.format("Failed to move VM [%s].", getVmId()); + logger.error(msg, e); + throw new ServerApiException(errorCode, msg); } - } @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/DeployVMCmdByAdmin.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/DeployVMCmdByAdmin.java index acdc0e07427..6bb7657b86b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/DeployVMCmdByAdmin.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/DeployVMCmdByAdmin.java @@ -20,7 +20,6 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.PodResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ResponseObject.ResponseView; @@ -34,7 +33,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "deployVirtualMachine", description = "Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject = UserVmResponse.class, responseView = ResponseView.Full, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class DeployVMCmdByAdmin extends DeployVMCmd implements AdminCmd { - public static final Logger s_logger = Logger.getLogger(DeployVMCmdByAdmin.class.getName()); @Parameter(name = ApiConstants.POD_ID, type = CommandType.UUID, entityType = PodResponse.class, description = "destination Pod ID to deploy the VM to - parameter available for root admin only", since = "4.13") diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ExpungeVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ExpungeVMCmd.java index 4cd7f541c4e..a964e873bad 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ExpungeVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ExpungeVMCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.vm; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -43,7 +42,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "expungeVirtualMachine", description = "Expunge a virtual machine. Once expunged, it cannot be recoverd.", responseObject = SuccessResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExpungeVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ExpungeVMCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/GetVMUserDataCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/GetVMUserDataCmd.java index 98af820201c..8745ef12ce4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/GetVMUserDataCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/GetVMUserDataCmd.java @@ -24,7 +24,6 @@ import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VMUserDataResponse; -import org.apache.log4j.Logger; import com.cloud.user.Account; import com.cloud.uservm.UserVm; @@ -32,7 +31,6 @@ import com.cloud.uservm.UserVm; @APICommand(name = "getVirtualMachineUserData", description = "Returns user data associated with the VM", responseObject = VMUserDataResponse.class, since = "4.4", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class GetVMUserDataCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(GetVMUserDataCmd.class); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportUnmanagedInstanceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportUnmanagedInstanceCmd.java index 3d8b23318dd..ae6ceff26c7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportUnmanagedInstanceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportUnmanagedInstanceCmd.java @@ -41,7 +41,6 @@ import org.apache.cloudstack.vm.VmImportService; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -65,7 +64,6 @@ import com.cloud.vm.VmDetailConstants; authorized = {RoleType.Admin}, since = "4.14.0") public class ImportUnmanagedInstanceCmd extends BaseAsyncCmd { - public static final Logger LOGGER = Logger.getLogger(ImportUnmanagedInstanceCmd.class); @Inject public VmImportService vmImportService; @@ -203,8 +201,8 @@ public class ImportUnmanagedInstanceCmd extends BaseAsyncCmd { for (Map entry : (Collection>)nicNetworkList.values()) { String nic = entry.get(VmDetailConstants.NIC); String networkUuid = entry.get(VmDetailConstants.NETWORK); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("nic, '%s', goes on net, '%s'", nic, networkUuid)); + if (logger.isDebugEnabled()) { + logger.debug(String.format("nic, '%s', goes on net, '%s'", nic, networkUuid)); } if (StringUtils.isAnyEmpty(nic, networkUuid) || _entityMgr.findByUuid(Network.class, networkUuid) == null) { throw new InvalidParameterValueException(String.format("Network ID: %s for NIC ID: %s is invalid", networkUuid, nic)); @@ -221,8 +219,8 @@ public class ImportUnmanagedInstanceCmd extends BaseAsyncCmd { for (Map entry : (Collection>)nicIpAddressList.values()) { String nic = entry.get(VmDetailConstants.NIC); String ipAddress = StringUtils.defaultIfEmpty(entry.get(VmDetailConstants.IP4_ADDRESS), null); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("nic, '%s', gets ip, '%s'", nic, ipAddress)); + if (logger.isDebugEnabled()) { + logger.debug(String.format("nic, '%s', gets ip, '%s'", nic, ipAddress)); } if (StringUtils.isEmpty(nic)) { throw new InvalidParameterValueException(String.format("NIC ID: '%s' is invalid for IP address mapping", nic)); @@ -246,8 +244,8 @@ public class ImportUnmanagedInstanceCmd extends BaseAsyncCmd { for (Map entry : (Collection>)dataDiskToDiskOfferingList.values()) { String disk = entry.get(VmDetailConstants.DISK); String offeringUuid = entry.get(VmDetailConstants.DISK_OFFERING); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace(String.format("disk, '%s', gets offering, '%s'", disk, offeringUuid)); + if (logger.isTraceEnabled()) { + logger.trace(String.format("disk, '%s', gets offering, '%s'", disk, offeringUuid)); } if (StringUtils.isAnyEmpty(disk, offeringUuid) || _entityMgr.findByUuid(DiskOffering.class, offeringUuid) == null) { throw new InvalidParameterValueException(String.format("Disk offering ID: %s for disk ID: %s is invalid", offeringUuid, disk)); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportVmCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportVmCmd.java index 5c82e5bbd97..db43b53ab9a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportVmCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportVmCmd.java @@ -40,7 +40,6 @@ import org.apache.cloudstack.vm.VmImportService; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import javax.inject.Inject; @@ -53,7 +52,6 @@ import javax.inject.Inject; authorized = {RoleType.Admin}, since = "4.19.0") public class ImportVmCmd extends ImportUnmanagedInstanceCmd { - public static final Logger LOGGER = Logger.getLogger(ImportVmCmd.class); @Inject public VmImportService vmImportService; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListUnmanagedInstancesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListUnmanagedInstancesCmd.java index 13b6748c74d..6932aa383fa 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListUnmanagedInstancesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListUnmanagedInstancesCmd.java @@ -32,7 +32,6 @@ import org.apache.cloudstack.api.response.UnmanagedInstanceResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.vm.UnmanagedInstanceTO; import org.apache.cloudstack.vm.VmImportService; -import org.apache.log4j.Logger; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -51,7 +50,6 @@ import com.cloud.user.Account; authorized = {RoleType.Admin}, since = "4.14.0") public class ListUnmanagedInstancesCmd extends BaseListCmd { - public static final Logger LOGGER = Logger.getLogger(ListUnmanagedInstancesCmd.class.getName()); @Inject public VmImportService vmImportService; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListVMsCmdByAdmin.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListVMsCmdByAdmin.java index 5b3e607416b..b48941e7d17 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListVMsCmdByAdmin.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListVMsCmdByAdmin.java @@ -27,14 +27,12 @@ import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.UserVmResponse; -import org.apache.log4j.Logger; import com.cloud.vm.VirtualMachine; @APICommand(name = "listVirtualMachines", description = "List the virtual machines owned by the account.", responseObject = UserVmResponse.class, responseView = ResponseView.Full, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class ListVMsCmdByAdmin extends ListVMsCmd implements AdminCmd { - public static final Logger s_logger = Logger.getLogger(ListVMsCmdByAdmin.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListVmsForImportCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListVmsForImportCmd.java index 88df04d9ef5..f40f1c0cb4a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListVmsForImportCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListVmsForImportCmd.java @@ -36,7 +36,6 @@ import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.vm.UnmanagedInstanceTO; import org.apache.cloudstack.vm.VmImportService; -import org.apache.log4j.Logger; import javax.inject.Inject; @@ -50,7 +49,6 @@ import javax.inject.Inject; authorized = {RoleType.Admin}, since = "4.19.0") public class ListVmsForImportCmd extends BaseListCmd { - public static final Logger LOGGER = Logger.getLogger(ListVmsForImportCmd.class.getName()); @Inject public VmImportService vmImportService; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java index b685b366cd1..8881a2bc354 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.vm; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -50,7 +49,6 @@ import com.cloud.vm.VirtualMachine; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class MigrateVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(MigrateVMCmd.class.getName()); ///////////////////////////////////////////////////// @@ -184,10 +182,10 @@ public class MigrateVMCmd extends BaseAsyncCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to migrate vm"); } } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (VirtualMachineMigrationException | ConcurrentOperationException | ManagementServerException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/MigrateVirtualMachineWithVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/MigrateVirtualMachineWithVolumeCmd.java index 549d02b4579..b736e860636 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/MigrateVirtualMachineWithVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/MigrateVirtualMachineWithVolumeCmd.java @@ -33,7 +33,6 @@ import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.SystemVmResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.commons.collections.MapUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -52,7 +51,6 @@ import com.cloud.vm.VirtualMachine; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class MigrateVirtualMachineWithVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(MigrateVirtualMachineWithVolumeCmd.class.getName()); ///////////////////////////////////////////////////// @@ -157,7 +155,7 @@ public class MigrateVirtualMachineWithVolumeCmd extends BaseAsyncCmd { Host destinationHost = _resourceService.getHost(getHostId()); // OfflineVmwareMigration: destination host would have to not be a required parameter for stopped VMs if (destinationHost == null) { - s_logger.error(String.format("Unable to find the host with ID [%s].", getHostId())); + logger.error(String.format("Unable to find the host with ID [%s].", getHostId())); throw new InvalidParameterValueException("Unable to find the specified host to migrate the VM."); } return destinationHost; @@ -193,10 +191,10 @@ public class MigrateVirtualMachineWithVolumeCmd extends BaseAsyncCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to migrate vm"); } } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException | ManagementServerException | VirtualMachineMigrationException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java index b0698ed1e7a..f34d555dc70 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.vm; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -38,7 +37,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "recoverVirtualMachine", description = "Recovers a virtual machine.", responseObject = UserVmResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class RecoverVMCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(RecoverVMCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/UnmanageVMInstanceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/UnmanageVMInstanceCmd.java index 20c7c536c45..bbcb8840f66 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/UnmanageVMInstanceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/UnmanageVMInstanceCmd.java @@ -40,7 +40,6 @@ import org.apache.cloudstack.api.response.UnmanageVMInstanceResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.vm.UnmanagedVMsManager; -import org.apache.log4j.Logger; import javax.inject.Inject; @@ -53,7 +52,6 @@ import javax.inject.Inject; since = "4.15.0") public class UnmanageVMInstanceCmd extends BaseAsyncCmd { - public static final Logger LOGGER = Logger.getLogger(UnmanageVMInstanceCmd.class); @Inject private UnmanagedVMsManager unmanagedVMsManager; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/volume/DestroyVolumeCmdByAdmin.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/volume/DestroyVolumeCmdByAdmin.java index 44ce32f90c2..0840b4ce6f9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/volume/DestroyVolumeCmdByAdmin.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/volume/DestroyVolumeCmdByAdmin.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.volume; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -37,7 +36,6 @@ import com.cloud.storage.Volume; responseHasSensitiveInfo = true) public class DestroyVolumeCmdByAdmin extends DestroyVolumeCmd implements AdminCmd { - public static final Logger s_logger = Logger.getLogger(DestroyVolumeCmdByAdmin.class.getName()); @Override public void execute() { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/volume/RecoverVolumeCmdByAdmin.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/volume/RecoverVolumeCmdByAdmin.java index f51aeec9719..e276c8a00b6 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/volume/RecoverVolumeCmdByAdmin.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/volume/RecoverVolumeCmdByAdmin.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.volume; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -36,7 +35,6 @@ import com.cloud.storage.Volume; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class RecoverVolumeCmdByAdmin extends RecoverVolumeCmd implements AdminCmd { - public static final Logger s_logger = Logger.getLogger(RecoverVolumeCmdByAdmin.class.getName()); @Override public void execute() { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayByAdminCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayByAdminCmd.java index b5ba70cf5e2..1b2163853ec 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayByAdminCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayByAdminCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.vpc; import org.apache.commons.lang3.BooleanUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.network.vpc.VpcGateway; since = "4.17.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreatePrivateGatewayByAdminCmd extends CreatePrivateGatewayCmd implements AdminCmd { - public static final Logger s_logger = Logger.getLogger(CreatePrivateGatewayByAdminCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCCmdByAdmin.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCCmdByAdmin.java index bd00876ed36..9dc31f8cefe 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCCmdByAdmin.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCCmdByAdmin.java @@ -17,13 +17,31 @@ package org.apache.cloudstack.api.command.admin.vpc; import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ResponseObject.ResponseView; import org.apache.cloudstack.api.command.admin.AdminCmd; import org.apache.cloudstack.api.command.user.vpc.CreateVPCCmd; +import org.apache.cloudstack.api.response.BgpPeerResponse; import org.apache.cloudstack.api.response.VpcResponse; import com.cloud.network.vpc.Vpc; +import java.util.List; + @APICommand(name = "createVPC", description = "Creates a VPC", responseObject = VpcResponse.class, responseView = ResponseView.Full, entityType = {Vpc.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class CreateVPCCmdByAdmin extends CreateVPCCmd implements AdminCmd {} +public class CreateVPCCmdByAdmin extends CreateVPCCmd implements AdminCmd { + @Parameter(name = ApiConstants.BGP_PEER_IDS, + type = CommandType.LIST, + collectionType = CommandType.UUID, + entityType = BgpPeerResponse.class, + description = "Ids of the Bgp Peer for the VPC", + since = "4.20.0") + private List bgpPeerIds; + + + public List getBgpPeerIds() { + return bgpPeerIds; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java index b69e7f4a828..73b4f5df196 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java @@ -24,12 +24,16 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.Network; +import com.cloud.network.VirtualRouterProvider; import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -45,10 +49,18 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.network.vpc.VpcOffering; import com.cloud.user.Account; +import static com.cloud.network.Network.Service.Dhcp; +import static com.cloud.network.Network.Service.Dns; +import static com.cloud.network.Network.Service.Lb; +import static com.cloud.network.Network.Service.StaticNat; +import static com.cloud.network.Network.Service.SourceNat; +import static com.cloud.network.Network.Service.PortForwarding; +import static com.cloud.network.Network.Service.NetworkACL; +import static com.cloud.network.Network.Service.UserData; + @APICommand(name = "createVPCOffering", description = "Creates VPC offering", responseObject = VpcOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateVPCOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -62,7 +74,6 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.SUPPORTED_SERVICES, type = CommandType.LIST, - required = true, collectionType = CommandType.STRING, description = "services supported by the vpc offering") private List supportedServices; @@ -101,12 +112,40 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd { since = "4.13") private List zoneIds; + @Parameter(name = ApiConstants.FOR_NSX, + type = CommandType.BOOLEAN, + description = "true if network offering is meant to be used for NSX, false otherwise.", + since = "4.20.0") + private Boolean forNsx; + + @Parameter(name = ApiConstants.NSX_SUPPORT_LB, + type = CommandType.BOOLEAN, + description = "true if network offering for NSX VPC offering supports Load balancer service.", + since = "4.20.0") + private Boolean nsxSupportsLbService; + @Parameter(name = ApiConstants.ENABLE, type = CommandType.BOOLEAN, description = "set to true if the offering is to be enabled during creation. Default is false", since = "4.16") private Boolean enable; + @Parameter(name = ApiConstants.NETWORK_MODE, + type = CommandType.STRING, + description = "Indicates the mode with which the network will operate. Valid option: NATTED or ROUTED", + since = "4.20.0") + private String networkMode; + + @Parameter(name = ApiConstants.SPECIFY_AS_NUMBER, type = CommandType.BOOLEAN, since = "4.20.0", + description = "true if the VPC offering supports choosing AS number") + private Boolean specifyAsNumber; + + @Parameter(name = ApiConstants.ROUTING_MODE, + type = CommandType.STRING, + since = "4.20.0", + description = "the routing mode for the VPC offering. Supported types are: Static or Dynamic.") + private String routingMode; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -120,21 +159,49 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd { } public List getSupportedServices() { + if (!isForNsx() && CollectionUtils.isEmpty(supportedServices)) { + throw new InvalidParameterValueException("Supported services needs to be provided"); + } + if (isForNsx()) { + supportedServices = new ArrayList<>(List.of( + Dhcp.getName(), + Dns.getName(), + StaticNat.getName(), + SourceNat.getName(), + NetworkACL.getName(), + PortForwarding.getName(), + UserData.getName() + )); + if (getNsxSupportsLbService()) { + supportedServices.add(Lb.getName()); + } + } return supportedServices; } + public boolean isForNsx() { + return BooleanUtils.isTrue(forNsx); + } + + public String getNetworkMode() { + return networkMode; + } + + public boolean getNsxSupportsLbService() { + return org.apache.commons.lang3.BooleanUtils.isTrue(nsxSupportsLbService); + } + public Map> getServiceProviders() { - Map> serviceProviderMap = null; - if (serviceProviderList != null && !serviceProviderList.isEmpty()) { - serviceProviderMap = new HashMap>(); + Map> serviceProviderMap = new HashMap<>(); + if (serviceProviderList != null && !serviceProviderList.isEmpty() && !isForNsx()) { Collection> servicesCollection = serviceProviderList.values(); Iterator> iter = servicesCollection.iterator(); while (iter.hasNext()) { Map obj = iter.next(); - if (s_logger.isTraceEnabled()) { - s_logger.trace("service provider entry specified: " + obj); + if (logger.isTraceEnabled()) { + logger.trace("service provider entry specified: " + obj); } - HashMap services = (HashMap)obj; + HashMap services = (HashMap) obj; String service = services.get("service"); String provider = services.get("provider"); List providerList = null; @@ -146,11 +213,31 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd { providerList.add(provider); serviceProviderMap.put(service, providerList); } + } else if (Boolean.TRUE.equals(forNsx)) { + getServiceProviderMapForNsx(serviceProviderMap); } return serviceProviderMap; } + private void getServiceProviderMapForNsx(Map> serviceProviderMap) { + List unsupportedServices = List.of("Vpn", "BaremetalPxeService", "SecurityGroup", "Connectivity", + "Gateway", "Firewall"); + List routerSupported = List.of("Dhcp", "Dns", "UserData"); + List allServices = Network.Service.listAllServices().stream().map(Network.Service::getName).collect(Collectors.toList()); + for (String service : allServices) { + if (unsupportedServices.contains(service)) + continue; + if (routerSupported.contains(service)) + serviceProviderMap.put(service, List.of(VirtualRouterProvider.Type.VPCVirtualRouter.name())); + else + serviceProviderMap.put(service, List.of(Network.Provider.Nsx.getName())); + } + if (!getNsxSupportsLbService()) { + serviceProviderMap.remove(Lb.getName()); + } + } + public Map> getServiceCapabilityList() { return serviceCapabilityList; } @@ -188,6 +275,14 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd { return false; } + public Boolean getSpecifyAsNumber() { + return BooleanUtils.toBoolean(specifyAsNumber); + } + + public String getRoutingMode() { + return routingMode; + } + @Override public void create() throws ResourceAllocationException { VpcOffering vpcOff = _vpcProvSvc.createVpcOffering(this); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java index d6c3cac68c7..d104edc381b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.vpc; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -41,7 +40,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class DeletePrivateGatewayCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeletePrivateGatewayCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java index aba4c857b0b..6aa0c3f3afc 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.vpc; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteVPCOffering", description = "Deletes VPC offering", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteVPCOfferingCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVPCOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/ListPrivateGatewaysCmdByAdminCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/ListPrivateGatewaysCmdByAdminCmd.java index 13a63e9cdd8..1211bd3311c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/ListPrivateGatewaysCmdByAdminCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/ListPrivateGatewaysCmdByAdminCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.vpc; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ResponseObject; @@ -30,6 +29,5 @@ import com.cloud.network.vpc.VpcGateway; responseView = ResponseObject.ResponseView.Full, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListPrivateGatewaysCmdByAdminCmd extends ListPrivateGatewaysCmd implements AdminCmd { - public static final Logger s_logger = Logger.getLogger(ListPrivateGatewaysCmdByAdminCmd.class.getName()); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java index 12babad504e..b59837281ef 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.domain.Domain; @@ -40,7 +39,6 @@ import com.cloud.user.Account; @APICommand(name = "updateVPCOffering", description = "Updates VPC offering", responseObject = VpcOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateVPCOfferingCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVPCOfferingCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java index aca3e00d095..24660e41ed9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.zone; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "createZone", description = "Creates a Zone.", responseObject = ZoneResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateZoneCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateZoneCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java index c530e999bf8..b89636c6fe5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.admin.zone; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -33,7 +32,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteZone", description = "Deletes a Zone.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteZoneCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteZoneCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java index 264aea3f449..5d3f5dcd47f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.admin.zone; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "markDefaultZoneForAccount", description = "Marks a default zone for this account", responseObject = AccountResponse.class, since = "4.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class MarkDefaultZoneForAccountCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(MarkDefaultZoneForAccountCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java index 1379050cbf7..1b2793d3e15 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.admin.zone; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "updateZone", description = "Updates a Zone.", responseObject = ZoneResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateZoneCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateZoneCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java index 57c0e484843..2fbcb6df1cc 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java @@ -24,7 +24,6 @@ import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.response.ProjectRoleResponse; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -44,7 +43,6 @@ import com.cloud.projects.ProjectAccount; @APICommand(name = "addAccountToProject", description = "Adds account to a project", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddAccountToProjectCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(AddAccountToProjectCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java index 34935f506ec..5e0977938a3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.account; import java.util.List; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.projects.Project; @APICommand(name = "deleteAccountFromProject", description = "Deletes account from the project", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteAccountFromProjectCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/account/DeleteUserFromProjectCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/account/DeleteUserFromProjectCmd.java index fbcffb7332c..0731d837804 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/account/DeleteUserFromProjectCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/account/DeleteUserFromProjectCmd.java @@ -32,7 +32,6 @@ import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +40,6 @@ import com.cloud.projects.Project; @APICommand(name = "deleteUserFromProject", description = "Deletes user from the project", responseObject = SuccessResponse.class, since = "4.15.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.DomainAdmin, RoleType.ResourceAdmin, RoleType.User}) public class DeleteUserFromProjectCmd extends BaseAsyncCmd { - public static final Logger LOGGER = Logger.getLogger(DeleteUserFromProjectCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/account/ListAccountsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/account/ListAccountsCmd.java index 66a4d91172a..bd9ab30f4f1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/account/ListAccountsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/account/ListAccountsCmd.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.EnumSet; import java.util.List; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; @@ -31,7 +32,7 @@ import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ResourceIconResponse; -import org.apache.log4j.Logger; +import org.apache.commons.collections.CollectionUtils; import com.cloud.exception.InvalidParameterValueException; import com.cloud.server.ResourceIcon; @@ -41,7 +42,6 @@ import com.cloud.user.Account; @APICommand(name = "listAccounts", description = "Lists accounts and provides detailed account information for listed accounts", responseObject = AccountResponse.class, responseView = ResponseView.Restricted, entityType = {Account.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class ListAccountsCmd extends BaseListDomainResourcesCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListAccountsCmd.class.getName()); private static final String s_name = "listaccountsresponse"; ///////////////////////////////////////////////////// @@ -71,10 +71,16 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd implements UserC description = "comma separated list of account details requested, value can be a list of [ all, resource, min]") private List viewDetails; + @Parameter(name = ApiConstants.API_KEY_ACCESS, type = CommandType.STRING, description = "List accounts by the Api key access value", since = "4.20.1.0", authorized = {RoleType.Admin}) + private String apiKeyAccess; + @Parameter(name = ApiConstants.SHOW_RESOURCE_ICON, type = CommandType.BOOLEAN, description = "flag to display the resource icon for accounts") private Boolean showIcon; + @Parameter(name = ApiConstants.TAG, type = CommandType.STRING, description = "Tag for resource type to return usage", since = "4.20.0") + private String tag; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -118,10 +124,18 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd implements UserC return dv; } - public Boolean getShowIcon() { + public String getApiKeyAccess() { + return apiKeyAccess; + } + + public boolean getShowIcon() { return showIcon != null ? showIcon : false; } + public String getTag() { + return tag; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -136,12 +150,20 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd implements UserC ListResponse response = _queryService.searchForAccounts(this); response.setResponseName(getCommandName()); setResponseObject(response); - if (response != null && response.getCount() > 0 && getShowIcon()) { - updateAccountResponse(response.getResponses()); - } + updateAccountResponse(response.getResponses()); } - private void updateAccountResponse(List response) { + protected void updateAccountResponse(List response) { + if (CollectionUtils.isEmpty(response)) { + return; + } + EnumSet details = getDetails(); + if (details.contains(DomainDetails.all) || details.contains(DomainDetails.resource)) { + _resourceLimitService.updateTaggedResourceLimitsAndCountsForAccounts(response, getTag()); + } + if (!getShowIcon()) { + return; + } for (AccountResponse accountResponse : response) { ResourceIcon resourceIcon = resourceIconManager.getByResourceTypeAndUuid(ResourceTag.ResourceObjectType.Account, accountResponse.getObjectId()); if (resourceIcon == null) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/account/ListProjectAccountsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/account/ListProjectAccountsCmd.java index 3d50fc553b8..21aedc7d772 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/account/ListProjectAccountsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/account/ListProjectAccountsCmd.java @@ -26,14 +26,12 @@ import org.apache.cloudstack.api.response.ProjectAccountResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ProjectRoleResponse; import org.apache.cloudstack.api.response.UserResponse; -import org.apache.log4j.Logger; import com.cloud.user.Account; @APICommand(name = "listProjectAccounts", description = "Lists project's accounts", responseObject = ProjectResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListProjectAccountsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListProjectAccountsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java index 75b83b40f3e..5ea14478516 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.address; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -65,7 +64,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AssociateIPAddrCmd extends BaseAsyncCreateCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(AssociateIPAddrCmd.class.getName()); private static final String s_name = "associateipaddressresponse"; ///////////////////////////////////////////////////// @@ -325,11 +323,11 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd implements UserCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to allocate IP address"); } } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientAddressCapacityException ex) { - s_logger.info(ex); - s_logger.trace(ex); + logger.info(ex); + logger.trace(ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java index f9bfcb253b4..f4c06e512f0 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.address; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "disassociateIpAddress", description = "Disassociates an IP address from the account.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, entityType = { IpAddress.class }) public class DisassociateIPAddrCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DisassociateIPAddrCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/address/ListPublicIpAddressesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/address/ListPublicIpAddressesCmd.java index 22eb70cc0c2..5760ca3ba1c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/address/ListPublicIpAddressesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/address/ListPublicIpAddressesCmd.java @@ -19,7 +19,7 @@ package org.apache.cloudstack.api.command.user.address; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; +import org.apache.commons.lang.BooleanUtils; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -43,7 +43,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listPublicIpAddresses", description = "Lists all public IP addresses", responseObject = IPAddressResponse.class, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, entityType = { IpAddress.class }) public class ListPublicIpAddressesCmd extends BaseListRetrieveOnlyResourceCountCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListPublicIpAddressesCmd.class.getName()); private static final String s_name = "listpublicipaddressesresponse"; @@ -106,6 +105,9 @@ public class ListPublicIpAddressesCmd extends BaseListRetrieveOnlyResourceCountC @Parameter(name = ApiConstants.FOR_DISPLAY, type = CommandType.BOOLEAN, description = "list resources by display flag; only ROOT admin is eligible to pass this parameter", since = "4.4", authorized = {RoleType.Admin}) private Boolean display; + @Parameter(name = ApiConstants.FOR_SYSTEM_VMS, type = CommandType.BOOLEAN, description = "true if range is dedicated for system VMs", since = "4.20.0") + private Boolean forSystemVMs; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -177,6 +179,10 @@ public class ListPublicIpAddressesCmd extends BaseListRetrieveOnlyResourceCountC return state; } + public boolean getForSystemVMs() { + return BooleanUtils.isTrue(forSystemVMs); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/address/ReleaseIPAddrCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/address/ReleaseIPAddrCmd.java index eb908300283..effe45c51ed 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/address/ReleaseIPAddrCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/address/ReleaseIPAddrCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.address; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -41,7 +40,6 @@ import com.cloud.network.IpAddress; responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class ReleaseIPAddrCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ReleaseIPAddrCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/address/ReserveIPAddrCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/address/ReserveIPAddrCmd.java index 5e72986fb58..e323d413b9a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/address/ReserveIPAddrCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/address/ReserveIPAddrCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.address; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -51,7 +50,6 @@ import com.cloud.user.Account; responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class ReserveIPAddrCmd extends BaseCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ReserveIPAddrCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/address/UpdateIPAddrCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/address/UpdateIPAddrCmd.java index 7055e1d5cb2..194967e2e4a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/address/UpdateIPAddrCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/address/UpdateIPAddrCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.address; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -42,7 +41,6 @@ import com.cloud.user.Account; @APICommand(name = "updateIpAddress", description = "Updates an IP address", responseObject = IPAddressResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, entityType = { IpAddress.class }) public class UpdateIPAddrCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateIPAddrCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/CreateAffinityGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/CreateAffinityGroupCmd.java index 60dbc2a6e9a..ee0a38ef35d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/CreateAffinityGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/CreateAffinityGroupCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.affinitygroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.affinity.AffinityGroup; import org.apache.cloudstack.affinity.AffinityGroupResponse; import org.apache.cloudstack.api.APICommand; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "createAffinityGroup", responseObject = AffinityGroupResponse.class, description = "Creates an affinity/anti-affinity group", entityType = {AffinityGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateAffinityGroupCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateAffinityGroupCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/DeleteAffinityGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/DeleteAffinityGroupCmd.java index c8967b08020..2f24158cadb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/DeleteAffinityGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/DeleteAffinityGroupCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.affinitygroup; import org.apache.cloudstack.api.response.ProjectResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.affinity.AffinityGroup; import org.apache.cloudstack.affinity.AffinityGroupResponse; @@ -40,7 +39,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteAffinityGroup", description = "Deletes affinity group", responseObject = SuccessResponse.class, entityType = {AffinityGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteAffinityGroupCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteAffinityGroupCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupTypesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupTypesCmd.java index 2d6f45cc06e..c90294171b3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupTypesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupTypesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.affinitygroup; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.affinity.AffinityGroupTypeResponse; import org.apache.cloudstack.api.APICommand; @@ -31,7 +30,6 @@ import com.cloud.user.Account; @APICommand(name = "listAffinityGroupTypes", description = "Lists affinity group types available", responseObject = AffinityGroupTypeResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListAffinityGroupTypesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListAffinityGroupTypesCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java index ed6c3145198..ee23e3794ce 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.affinitygroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.affinity.AffinityGroup; import org.apache.cloudstack.affinity.AffinityGroupResponse; @@ -31,7 +30,6 @@ import org.apache.cloudstack.api.response.UserVmResponse; @APICommand(name = "listAffinityGroups", description = "Lists affinity groups", responseObject = AffinityGroupResponse.class, entityType = {AffinityGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListAffinityGroupsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListAffinityGroupsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/UpdateVMAffinityGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/UpdateVMAffinityGroupCmd.java index c70e4fbda66..6cd9bce6259 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/UpdateVMAffinityGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/affinitygroup/UpdateVMAffinityGroupCmd.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.EnumSet; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.affinity.AffinityGroupResponse; @@ -55,7 +54,6 @@ import com.cloud.vm.VirtualMachine; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class UpdateVMAffinityGroupCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVMAffinityGroupCmd.class.getName()); private static final String s_name = "updatevirtualmachineresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java index eff93522b62..a000e265f93 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -43,7 +42,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateAutoScalePolicyCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateAutoScalePolicyCmd.class.getName()); private static final String s_name = "autoscalepolicyresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java index cdbe153f017..7c9362d4b69 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -45,7 +44,6 @@ import com.cloud.network.rules.LoadBalancer; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateAutoScaleVmGroupCmd.class.getName()); private static final String s_name = "autoscalevmgroupresponse"; @@ -233,7 +231,7 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd { } } catch (Exception ex) { // TODO what will happen if Resource Layer fails in a step in between - s_logger.warn("Failed to create autoscale vm group", ex); + logger.warn("Failed to create autoscale vm group", ex); } finally { if (!success || vmGroup == null) { _autoScaleService.deleteAutoScaleVmGroup(getEntityId(), true); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java index 8c1d38c1375..2d84b20c582 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java @@ -20,7 +20,6 @@ import java.util.HashMap; import java.util.Map; import org.apache.commons.collections.MapUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -51,7 +50,6 @@ import com.cloud.network.as.AutoScaleVmProfile; responseHasSensitiveInfo = false) @SuppressWarnings("rawtypes") public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateAutoScaleVmProfileCmd.class.getName()); private static final String s_name = "autoscalevmprofileresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java index 77bc15b1e0f..0ffb9afdac4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.autoscale; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -39,7 +38,6 @@ import com.cloud.network.as.Condition; @APICommand(name = "createCondition", description = "Creates a condition for VM auto scaling", responseObject = ConditionResponse.class, entityType = {Condition.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateConditionCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateConditionCmd.class.getName()); private static final String s_name = "conditionresponse"; // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java index cf5ff366096..cee9460dbe6 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.autoscale; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -38,7 +37,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteAutoScalePolicy", description = "Deletes a autoscale policy.", responseObject = SuccessResponse.class, entityType = {AutoScalePolicy.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteAutoScalePolicyCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteAutoScalePolicyCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// @@ -93,7 +91,7 @@ public class DeleteAutoScalePolicyCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); setResponseObject(response); } else { - s_logger.warn("Failed to delete autoscale policy " + getId()); + logger.warn("Failed to delete autoscale policy " + getId()); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete AutoScale Policy"); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java index badfcc0957e..6bf2157533e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.autoscale; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -38,7 +37,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteAutoScaleVmGroup", description = "Deletes a autoscale vm group.", responseObject = SuccessResponse.class, entityType = {AutoScaleVmGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteAutoScaleVmGroupCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteAutoScaleVmGroupCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// @@ -103,7 +101,7 @@ public class DeleteAutoScaleVmGroupCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); setResponseObject(response); } else { - s_logger.warn("Failed to delete autoscale vm group " + getId()); + logger.warn("Failed to delete autoscale vm group " + getId()); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete autoscale vm group"); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java index 06bf7a9d378..b90f6aa8ffa 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.autoscale; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -38,7 +37,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteAutoScaleVmProfile", description = "Deletes a autoscale vm profile.", responseObject = SuccessResponse.class, entityType = {AutoScaleVmProfile.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteAutoScaleVmProfileCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteAutoScaleVmProfileCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// @@ -92,7 +90,7 @@ public class DeleteAutoScaleVmProfileCmd extends BaseAsyncCmd { SuccessResponse response = new SuccessResponse(getCommandName()); setResponseObject(response); } else { - s_logger.warn("Failed to delete autoscale vm profile " + getId()); + logger.warn("Failed to delete autoscale vm profile " + getId()); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete autoscale vm profile"); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java index 840484e45ad..9590012e037 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.autoscale; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteCondition", description = "Removes a condition for VM auto scaling", responseObject = SuccessResponse.class, entityType = {Condition.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteConditionCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteConditionCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// @@ -59,14 +57,14 @@ public class DeleteConditionCmd extends BaseAsyncCmd { try { result = _autoScaleService.deleteCondition(getId()); } catch (ResourceInUseException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, ex.getMessage()); } if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); setResponseObject(response); } else { - s_logger.warn("Failed to delete condition " + getId()); + logger.warn("Failed to delete condition " + getId()); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete condition."); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java index b0daf2ec664..2414c0d82b6 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.autoscale; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "disableAutoScaleVmGroup", description = "Disables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class, entityType = {AutoScaleVmGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DisableAutoScaleVmGroupCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DisableAutoScaleVmGroupCmd.class.getName()); private static final String s_name = "disableautoscalevmGroupresponse"; // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java index b6f2a82ac49..96d329d3e0c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.autoscale; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "enableAutoScaleVmGroup", description = "Enables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class, entityType = {AutoScaleVmGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class EnableAutoScaleVmGroupCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(EnableAutoScaleVmGroupCmd.class.getName()); private static final String s_name = "enableautoscalevmGroupresponse"; // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScalePoliciesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScalePoliciesCmd.java index dc0baf4c786..4935889c525 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScalePoliciesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScalePoliciesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.network.as.AutoScalePolicy; @APICommand(name = "listAutoScalePolicies", description = "Lists autoscale policies.", responseObject = AutoScalePolicyResponse.class, entityType = {AutoScalePolicy.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListAutoScalePoliciesCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListAutoScalePoliciesCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmGroupsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmGroupsCmd.java index 8404fbbb49f..6aa4abcccd8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmGroupsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmGroupsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -39,7 +38,6 @@ import com.cloud.network.as.AutoScaleVmGroup; @APICommand(name = "listAutoScaleVmGroups", description = "Lists autoscale vm groups.", responseObject = AutoScaleVmGroupResponse.class, entityType = {AutoScaleVmGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListAutoScaleVmGroupsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListAutoScaleVmGroupsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java index 435471faf13..bcaea273ce8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -37,7 +36,6 @@ import com.cloud.network.as.AutoScaleVmProfile; @APICommand(name = "listAutoScaleVmProfiles", description = "Lists autoscale vm profiles.", responseObject = AutoScaleVmProfileResponse.class, entityType = {AutoScaleVmProfile.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListAutoScaleVmProfilesCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListAutoScaleVmProfilesCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListConditionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListConditionsCmd.java index fc1ca7097c8..febf937d75f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListConditionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListConditionsCmd.java @@ -20,7 +20,6 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -36,7 +35,6 @@ import com.cloud.network.as.Condition; @APICommand(name = "listConditions", description = "List Conditions for VM auto scaling", responseObject = ConditionResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListConditionsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListConditionsCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListCountersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListCountersCmd.java index 7da8bd40b61..d03584fd63d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListCountersCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/ListCountersCmd.java @@ -20,7 +20,6 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "listCounters", description = "List the counters for VM auto scaling", responseObject = CounterResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListCountersCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListCountersCmd.class.getName()); private static final String s_name = "counterresponse"; // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java index a64b5cb1680..927a9191fcc 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -41,7 +40,6 @@ import com.cloud.user.Account; @APICommand(name = "updateAutoScalePolicy", description = "Updates an existing autoscale policy.", responseObject = AutoScalePolicyResponse.class, entityType = {AutoScalePolicy.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateAutoScalePolicyCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateAutoScalePolicyCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java index 87cd1fd3f4e..69ae8aa36aa 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -42,7 +41,6 @@ import com.cloud.user.Account; @APICommand(name = "updateAutoScaleVmGroup", description = "Updates an existing autoscale vm group.", responseObject = AutoScaleVmGroupResponse.class, entityType = {AutoScaleVmGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateAutoScaleVmGroupCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateAutoScaleVmGroupCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java index 34c81bfc483..0b73fd91b52 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java @@ -20,7 +20,6 @@ package org.apache.cloudstack.api.command.user.autoscale; import java.util.HashMap; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -46,7 +45,6 @@ import com.cloud.user.Account; @APICommand(name = "updateAutoScaleVmProfile", description = "Updates an existing autoscale vm profile.", responseObject = AutoScaleVmProfileResponse.class, entityType = {AutoScaleVmProfile.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateAutoScaleVmProfileCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateAutoScaleVmProfileCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateConditionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateConditionCmd.java index e946dd370c1..4ed8244ff0c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateConditionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/autoscale/UpdateConditionCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.autoscale; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -41,7 +40,6 @@ import com.cloud.user.Account; authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.18.0") public class UpdateConditionCmd extends BaseAsyncCmd { - public static final Logger LOGGER = Logger.getLogger(UpdateConditionCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// @@ -69,7 +67,7 @@ public class UpdateConditionCmd extends BaseAsyncCmd { response.setResponseName(getCommandName()); setResponseObject(response); } catch (ResourceInUseException ex) { - LOGGER.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/DeleteBackupScheduleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/DeleteBackupScheduleCmd.java index 0245f228b89..548f4d67b23 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/DeleteBackupScheduleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/DeleteBackupScheduleCmd.java @@ -26,6 +26,7 @@ import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.BackupScheduleResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.backup.BackupManager; @@ -54,10 +55,16 @@ public class DeleteBackupScheduleCmd extends BaseCmd { @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, - required = true, description = "ID of the VM") private Long vmId; + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + entityType = BackupScheduleResponse.class, + description = "ID of the schedule", + since = "4.20.1") + private Long id; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -66,6 +73,9 @@ public class DeleteBackupScheduleCmd extends BaseCmd { return vmId; } + public Long getId() { return id; } + + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -73,7 +83,7 @@ public class DeleteBackupScheduleCmd extends BaseCmd { @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { try { - boolean result = backupManager.deleteBackupSchedule(getVmId()); + boolean result = backupManager.deleteBackupSchedule(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); response.setResponseName(getCommandName()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmd.java index 6cc765328f6..fa6e3ea5d45 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmd.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command.user.backup; import javax.inject.Inject; +import com.amazonaws.util.CollectionUtils; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -27,6 +28,7 @@ import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.BackupScheduleResponse; +import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.backup.BackupManager; import org.apache.cloudstack.backup.BackupSchedule; @@ -39,6 +41,9 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.utils.exception.CloudRuntimeException; +import java.util.ArrayList; +import java.util.List; + @APICommand(name = "listBackupSchedule", description = "List backup schedule of a VM", responseObject = BackupScheduleResponse.class, since = "4.14.0", @@ -74,9 +79,14 @@ public class ListBackupScheduleCmd extends BaseCmd { @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { try{ - BackupSchedule schedule = backupManager.listBackupSchedule(getVmId()); - if (schedule != null) { - BackupScheduleResponse response = _responseGenerator.createBackupScheduleResponse(schedule); + List schedules = backupManager.listBackupSchedule(getVmId()); + ListResponse response = new ListResponse<>(); + List scheduleResponses = new ArrayList<>(); + if (!CollectionUtils.isNullOrEmpty(schedules)) { + for (BackupSchedule schedule : schedules) { + scheduleResponses.add(_responseGenerator.createBackupScheduleResponse(schedule)); + } + response.setResponses(scheduleResponses, schedules.size()); response.setResponseName(getCommandName()); setResponseObject(response); } else { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupsCmd.java index 57a1de2f105..7d87cc37e6c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupsCmd.java @@ -36,7 +36,6 @@ import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.backup.Backup; import org.apache.cloudstack.backup.BackupManager; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -50,7 +49,6 @@ import com.cloud.utils.Pair; responseObject = BackupResponse.class, since = "4.14.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class ListBackupsCmd extends BaseListProjectAndAccountResourcesCmd { - private static final Logger s_logger = Logger.getLogger(ListBackupsCmd.class); @Inject private BackupManager backupManager; @@ -118,7 +116,7 @@ public class ListBackupsCmd extends BaseListProjectAndAccountResourcesCmd { Pair, Integer> result = backupManager.listBackups(this); setupResponseBackupList(result.first(), result.second()); } catch (Exception e) { - s_logger.debug("Exception while listing backups", e); + logger.debug("Exception while listing backups", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java new file mode 100644 index 00000000000..5d0c838bc37 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java @@ -0,0 +1,137 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.user.backup.repository; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.BackupRepositoryResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.backup.BackupRepository; +import org.apache.cloudstack.backup.BackupRepositoryService; +import org.apache.cloudstack.context.CallContext; + +import javax.inject.Inject; + +@APICommand(name = "addBackupRepository", + description = "Adds a backup repository to store NAS backups", + responseObject = BackupRepositoryResponse.class, since = "4.20.0", + authorized = {RoleType.Admin}) +public class AddBackupRepositoryCmd extends BaseCmd { + + @Inject + private BackupRepositoryService backupRepositoryService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "name of the backup repository") + private String name; + + @Parameter(name = ApiConstants.ADDRESS, type = CommandType.STRING, required = true, description = "address of the backup repository") + private String address; + + @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, required = true, description = "type of the backup repository storage. Supported values: nfs, cephfs, cifs") + private String type; + + @Parameter(name = ApiConstants.PROVIDER, type = CommandType.STRING, description = "backup repository provider") + private String provider; + + @Parameter(name = ApiConstants.MOUNT_OPTIONS, type = CommandType.STRING, description = "shared storage mount options") + private String mountOptions; + + @Parameter(name = ApiConstants.ZONE_ID, + type = CommandType.UUID, + entityType = ZoneResponse.class, + required = true, + description = "ID of the zone where the backup repository is to be added") + private Long zoneId; + + @Parameter(name = ApiConstants.CAPACITY_BYTES, type = CommandType.LONG, description = "capacity of this backup repository") + private Long capacityBytes; + + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public BackupRepositoryService getBackupRepositoryService() { + return backupRepositoryService; + } + + public String getName() { + return name; + } + + public String getType() { + if ("cephfs".equalsIgnoreCase(type)) { + return "ceph"; + } + return type.toLowerCase(); + } + + public String getAddress() { + return address; + } + + public String getProvider() { + return provider; + } + + public String getMountOptions() { + return mountOptions == null ? "" : mountOptions; + } + + public Long getZoneId() { + return zoneId; + } + + public Long getCapacityBytes() { + return capacityBytes; + } + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() { + try { + BackupRepository result = backupRepositoryService.addBackupRepository(this); + if (result != null) { + BackupRepositoryResponse response = _responseGenerator.createBackupRepositoryResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add backup repository"); + } + } catch (Exception ex4) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex4.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/DeleteBackupRepositoryCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/DeleteBackupRepositoryCmd.java new file mode 100644 index 00000000000..912170eb4ca --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/DeleteBackupRepositoryCmd.java @@ -0,0 +1,76 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.user.backup.repository; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.BackupRepositoryResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.backup.BackupRepositoryService; + +import javax.inject.Inject; + +@APICommand(name = "deleteBackupRepository", + description = "delete a backup repository", + responseObject = SuccessResponse.class, since = "4.20.0", + authorized = {RoleType.Admin}) +public class DeleteBackupRepositoryCmd extends BaseCmd { + + @Inject + BackupRepositoryService backupRepositoryService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + entityType = BackupRepositoryResponse.class, + required = true, + description = "ID of the backup repository to be deleted") + private Long id; + + + ///////////////////////////////////////////////////// + //////////////// Accessors ////////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + @Override + public void execute() { + boolean result = backupRepositoryService.deleteBackupRepository(this); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete backup repository"); + } + } + + @Override + public long getEntityOwnerId() { + return 0; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/ListBackupRepositoriesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/ListBackupRepositoriesCmd.java new file mode 100644 index 00000000000..8293afb657d --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/ListBackupRepositoriesCmd.java @@ -0,0 +1,110 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.user.backup.repository; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.utils.Pair; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.BackupRepositoryResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.backup.BackupRepository; +import org.apache.cloudstack.backup.BackupRepositoryService; + +import javax.inject.Inject; +import java.util.ArrayList; +import java.util.List; + +@APICommand(name = "listBackupRepositories", + description = "Lists all backup repositories", + responseObject = BackupRepositoryResponse.class, since = "4.20.0", + authorized = {RoleType.Admin}) +public class ListBackupRepositoriesCmd extends BaseListCmd { + + @Inject + BackupRepositoryService backupRepositoryService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "name of the backup repository") + private String name; + + @Parameter(name = ApiConstants.ZONE_ID, + type = CommandType.UUID, + entityType = ZoneResponse.class, + description = "ID of the zone where the backup repository is to be added") + private Long zoneId; + + @Parameter(name = ApiConstants.PROVIDER, type = CommandType.STRING, description = "the backup repository provider") + private String provider; + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = BackupRepositoryResponse.class, description = "ID of the backup repository") + private Long id; + + ///////////////////////////////////////////////////// + //////////////// Accessors ////////////////////////// + ///////////////////////////////////////////////////// + + + public String getName() { + return name; + } + + public Long getZoneId() { + return zoneId; + } + + public String getProvider() { + return provider; + } + + public Long getId() { + return id; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { + try { + Pair, Integer> repositoriesPair = backupRepositoryService.listBackupRepositories(this); + List backupRepositories = repositoriesPair.first(); + ListResponse response = new ListResponse<>(); + List responses = new ArrayList<>(); + for (BackupRepository repository : backupRepositories) { + responses.add(_responseGenerator.createBackupRepositoryResponse(repository)); + } + response.setResponses(responses, repositoriesPair.second()); + response.setResponseName(getCommandName()); + setResponseObject(response); + } catch (Exception e) { + String msg = String.format("Error listing backup repositories, due to: %s", e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, msg); + } + + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/bgp/ListASNumbersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/bgp/ListASNumbersCmd.java new file mode 100644 index 00000000000..b835f7225df --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/bgp/ListASNumbersCmd.java @@ -0,0 +1,134 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.bgp; + +import com.cloud.bgp.ASNumber; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.utils.Pair; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ASNRangeResponse; +import org.apache.cloudstack.api.response.ASNumberResponse; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + +import java.util.ArrayList; +import java.util.List; + +@APICommand(name = "listASNumbers", + description = "List Autonomous Systems Numbers", + responseObject = ASNumberResponse.class, + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}, + since = "4.20.0") +public class ListASNumbersCmd extends BaseListCmd { + + @Parameter(name = ApiConstants.ZONE_ID, type = BaseCmd.CommandType.UUID, entityType = ZoneResponse.class, + description = "the zone ID") + private Long zoneId; + + @Parameter(name = ApiConstants.ASN_RANGE_ID, type = BaseCmd.CommandType.UUID, entityType = ASNRangeResponse.class, + description = "the AS Number range ID") + private Long asNumberRangeId; + + @Parameter(name = ApiConstants.AS_NUMBER, type = CommandType.INTEGER, entityType = ASNumberResponse.class, + description = "AS number") + private Integer asNumber; + + @Parameter(name = ApiConstants.IS_ALLOCATED, type = CommandType.BOOLEAN, + description = "to indicate if the AS number is allocated to any network") + private Boolean allocated; + + @Parameter(name = ApiConstants.NETWORK_ID, type = CommandType.UUID, entityType = NetworkResponse.class, + description = "the network id") + private Long networkId; + + @Parameter(name = ApiConstants.VPC_ID, type = CommandType.UUID, entityType = VpcResponse.class, + description = "the vpc id") + private Long vpcId; + + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, entityType = AccountResponse.class, + description = "account name") + private String account; + + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, + description = "domain id") + private Long domainId; + + public Long getZoneId() { + return zoneId; + } + + public Long getAsNumberRangeId() { + return asNumberRangeId; + } + + public Boolean getAllocated() { + return allocated; + } + + public Integer getAsNumber() { return asNumber; } + + public Long getNetworkId() { + return networkId; + } + + public String getAccount() { + return account; + } + + public Long getDomainId() { + return domainId; + } + + public Long getVpcId() { + return vpcId; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { + try { + Pair, Integer> pair = bgpService.listASNumbers(this); + List asNumbers = pair.first(); + ListResponse response = new ListResponse<>(); + List responses = new ArrayList<>(); + for (ASNumber asn : asNumbers) { + responses.add(_responseGenerator.createASNumberResponse(asn)); + } + response.setResponses(responses, pair.second()); + response.setResponseName(getCommandName()); + setResponseObject(response); + } catch (Exception e) { + String msg = String.format("Error listing AS Numbers, due to: %s", e.getMessage()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, msg); + } + + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/CreateBucketCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/CreateBucketCmd.java index e9a140cf46e..d2c91e57871 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/CreateBucketCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/CreateBucketCmd.java @@ -34,14 +34,12 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ObjectStoreResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; @APICommand(name = "createBucket", responseObject = BucketResponse.class, description = "Creates a bucket in the specified object storage pool. ", responseView = ResponseView.Restricted, entityType = {Bucket.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.19.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class CreateBucketCmd extends BaseAsyncCreateCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(CreateBucketCmd.class.getName()); private static final String s_name = "createbucketresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/DeleteBucketCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/DeleteBucketCmd.java index bf9552b779e..8cd2790e4ae 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/DeleteBucketCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/DeleteBucketCmd.java @@ -30,13 +30,11 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.BucketResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; @APICommand(name = "deleteBucket", description = "Deletes an empty Bucket.", responseObject = SuccessResponse.class, entityType = {Bucket.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.19.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class DeleteBucketCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteBucketCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/ListBucketsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/ListBucketsCmd.java index 897b9fc6696..bda0c7ed381 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/ListBucketsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/ListBucketsCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.BucketResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; -import org.apache.log4j.Logger; import java.util.List; @@ -36,7 +35,6 @@ import java.util.List; Bucket.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.19.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class ListBucketsCmd extends BaseListTaggedResourcesCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListBucketsCmd.class.getName()); private static final String s_name = "listbucketsresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/UpdateBucketCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/UpdateBucketCmd.java index b3b7e00770d..8e281b20e91 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/UpdateBucketCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/bucket/UpdateBucketCmd.java @@ -32,13 +32,11 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.BucketResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; @APICommand(name = "updateBucket", description = "Updates Bucket properties", responseObject = SuccessResponse.class, entityType = {Bucket.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.19.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class UpdateBucketCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateBucketCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java index 4f036e89a64..7553ccffa7d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java @@ -23,14 +23,12 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.response.CapabilitiesResponse; import org.apache.cloudstack.config.ApiServiceConfiguration; -import org.apache.log4j.Logger; import com.cloud.user.Account; @APICommand(name = "listCapabilities", description = "Lists capabilities", responseObject = CapabilitiesResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListCapabilitiesCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ListCapabilitiesCmd.class.getName()); @Override @@ -57,6 +55,7 @@ public class ListCapabilitiesCmd extends BaseCmd { response.setAllowUserExpungeRecoverVM((Boolean)capabilities.get("allowUserExpungeRecoverVM")); response.setAllowUserExpungeRecoverVolume((Boolean)capabilities.get("allowUserExpungeRecoverVolume")); response.setAllowUserViewAllDomainAccounts((Boolean)capabilities.get("allowUserViewAllDomainAccounts")); + response.setAllowUserForceStopVM((Boolean)capabilities.get(ApiConstants.ALLOW_USER_FORCE_STOP_VM)); response.setKubernetesServiceEnabled((Boolean)capabilities.get("kubernetesServiceEnabled")); response.setKubernetesClusterExperimentalFeaturesEnabled((Boolean)capabilities.get("kubernetesClusterExperimentalFeaturesEnabled")); response.setCustomHypervisorDisplayName((String) capabilities.get("customHypervisorDisplayName")); @@ -71,7 +70,10 @@ public class ListCapabilitiesCmd extends BaseCmd { response.setInstancesStatsUserOnly((Boolean) capabilities.get(ApiConstants.INSTANCES_STATS_USER_ONLY)); response.setInstancesDisksStatsRetentionEnabled((Boolean) capabilities.get(ApiConstants.INSTANCES_DISKS_STATS_RETENTION_ENABLED)); response.setInstancesDisksStatsRetentionTime((Integer) capabilities.get(ApiConstants.INSTANCES_DISKS_STATS_RETENTION_TIME)); + response.setSharedFsVmMinCpuCount((Integer)capabilities.get(ApiConstants.SHAREDFSVM_MIN_CPU_COUNT)); + response.setSharedFsVmMinRamSize((Integer)capabilities.get(ApiConstants.SHAREDFSVM_MIN_RAM_SIZE)); response.setDynamicScalingEnabled((Boolean) capabilities.get(ApiConstants.DYNAMIC_SCALING_ENABLED)); + response.setAdditionalConfigEnabled((Boolean) capabilities.get(ApiConstants.ADDITONAL_CONFIG_ENABLED)); response.setObjectName("capability"); response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/consoleproxy/CreateConsoleEndpointCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/consoleproxy/CreateConsoleEndpointCmd.java index 11e84f1bef9..63b47e163b6 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/consoleproxy/CreateConsoleEndpointCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/consoleproxy/CreateConsoleEndpointCmd.java @@ -35,7 +35,6 @@ import org.apache.cloudstack.consoleproxy.ConsoleAccessManager; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.utils.consoleproxy.ConsoleAccessUtils; import org.apache.commons.collections.MapUtils; -import org.apache.log4j.Logger; import javax.inject.Inject; import java.util.Map; @@ -46,7 +45,6 @@ import java.util.Map; authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class CreateConsoleEndpointCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateConsoleEndpointCmd.class.getName()); @Inject private ConsoleAccessManager consoleManager; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/event/ArchiveEventsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/event/ArchiveEventsCmd.java index cdff7882e65..669b1782e9e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/event/ArchiveEventsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/event/ArchiveEventsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.event; import java.util.Date; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -39,7 +38,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ArchiveEventsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ArchiveEventsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/event/DeleteEventsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/event/DeleteEventsCmd.java index 9d049ac5f06..c9c3f1d6955 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/event/DeleteEventsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/event/DeleteEventsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.event; import java.util.Date; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -39,7 +38,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteEventsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteEventsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/event/ListEventTypesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/event/ListEventTypesCmd.java index dd0f5179278..e3f14f711ce 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/event/ListEventTypesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/event/ListEventTypesCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.event; import java.util.ArrayList; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseCmd; @@ -30,7 +29,6 @@ import com.cloud.user.Account; @APICommand(name = "listEventTypes", description = "List Event Types", responseObject = EventTypeResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListEventTypesCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ListEventTypesCmd.class.getName()); @Override public long getEntityOwnerId() { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/event/ListEventsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/event/ListEventsCmd.java index 89f1c7090e0..b5273c64922 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/event/ListEventsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/event/ListEventsCmd.java @@ -24,14 +24,12 @@ import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.ListResponse; -import org.apache.log4j.Logger; import com.cloud.event.Event; @APICommand(name = "listEvents", description = "A command to list events.", responseObject = EventResponse.class, entityType = {Event.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListEventsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListEventsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreateEgressFirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreateEgressFirewallRuleCmd.java index bedb073b880..8cbbcea6a59 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreateEgressFirewallRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreateEgressFirewallRuleCmd.java @@ -21,7 +21,6 @@ import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -48,7 +47,6 @@ import com.cloud.utils.net.NetUtils; @APICommand(name = "createEgressFirewallRule", description = "Creates a egress firewall rule for a given network ", responseObject = FirewallResponse.class, entityType = {FirewallRule.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateEgressFirewallRuleCmd extends BaseAsyncCreateCmd implements FirewallRule { - public static final Logger s_logger = Logger.getLogger(CreateEgressFirewallRuleCmd.class.getName()); // /////////////////////////////////////////////////// @@ -257,10 +255,10 @@ public class CreateEgressFirewallRuleCmd extends BaseAsyncCreateCmd implements F } } catch (NetworkRuleConflictException ex) { String message = "Network rule conflict: "; - if (!s_logger.isTraceEnabled()) { - s_logger.info(message + ex.getMessage()); + if (!logger.isTraceEnabled()) { + logger.info(message + ex.getMessage()); } else { - s_logger.trace(message, ex); + logger.trace(message, ex); } throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java index 0809c935c4b..efccb5c09b0 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java @@ -20,8 +20,6 @@ import java.util.ArrayList; import java.util.List; import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -43,12 +41,12 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; import com.cloud.network.rules.FirewallRule; import com.cloud.user.Account; +import com.cloud.utils.StringUtils; import com.cloud.utils.net.NetUtils; @APICommand(name = "createFirewallRule", description = "Creates a firewall rule for a given IP address", responseObject = FirewallResponse.class, entityType = {FirewallRule.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements FirewallRule { - public static final Logger s_logger = Logger.getLogger(CreateFirewallRuleCmd.class.getName()); // /////////////////////////////////////////////////// @@ -98,11 +96,35 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal return ipAddressId; } + public void setIpAddressId(Long ipAddressId) { + this.ipAddressId = ipAddressId; + } + @Override public String getProtocol() { return protocol.trim(); } + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public Integer getPublicStartPort() { + return publicStartPort; + } + + public void setPublicStartPort(Integer publicStartPort) { + this.publicStartPort = publicStartPort; + } + + public Integer getPublicEndPort() { + return publicEndPort; + } + + public void setPublicEndPort(Integer publicEndPort) { + this.publicEndPort = publicEndPort; + } + @Override public List getSourceCidrList() { if (CollectionUtils.isNotEmpty(cidrlist) && !(cidrlist.size() == 1 && StringUtils.isBlank(cidrlist.get(0)))) { @@ -249,7 +271,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal setEntityUuid(result.getUuid()); } } catch (NetworkRuleConflictException ex) { - s_logger.trace("Network Rule Conflict: ", ex); + logger.trace("Network Rule Conflict: ", ex); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage(), ex); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java index 05d627fe577..9d1fe176019 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.firewall; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -54,7 +53,6 @@ import com.cloud.vm.VirtualMachine; VirtualMachine.class, IpAddress.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements PortForwardingRule { - public static final Logger s_logger = Logger.getLogger(CreatePortForwardingRuleCmd.class.getName()); // /////////////////////////////////////////////////// @@ -348,7 +346,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P setEntityId(result.getId()); setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException ex) { - s_logger.trace("Network Rule Conflict: ", ex); + logger.trace("Network Rule Conflict: ", ex); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage(), ex); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeleteEgressFirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeleteEgressFirewallRuleCmd.java index f0ba8a92d01..b93d943eab9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeleteEgressFirewallRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeleteEgressFirewallRuleCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.firewall; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -41,7 +40,6 @@ import com.cloud.network.rules.FirewallRule; @APICommand(name = "deleteEgressFirewallRule", description = "Deletes an egress firewall rule", responseObject = SuccessResponse.class, entityType = {FirewallRule.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteEgressFirewallRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteEgressFirewallRuleCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java index da1f6b62eca..c4a4dfd75cb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.firewall; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -40,7 +39,6 @@ import com.cloud.network.rules.FirewallRule; @APICommand(name = "deleteFirewallRule", description = "Deletes a firewall rule", responseObject = SuccessResponse.class, entityType = {FirewallRule.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteFirewallRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteFirewallRuleCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java index aebf8da159b..267d18d8a8a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.firewall; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -39,7 +38,6 @@ import com.cloud.network.rules.PortForwardingRule; @APICommand(name = "deletePortForwardingRule", description = "Deletes a port forwarding rule", responseObject = SuccessResponse.class, entityType = {PortForwardingRule.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeletePortForwardingRuleCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListEgressFirewallRulesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListEgressFirewallRulesCmd.java index c8c0e85252b..aa0fd28fdec 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListEgressFirewallRulesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListEgressFirewallRulesCmd.java @@ -20,7 +20,6 @@ package org.apache.cloudstack.api.command.user.firewall; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -39,7 +38,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listEgressFirewallRules", description = "Lists all egress firewall rules for network ID.", responseObject = FirewallResponse.class, entityType = {FirewallRule.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListEgressFirewallRulesCmd extends BaseListTaggedResourcesCmd implements IListFirewallRulesCmd { - public static final Logger s_logger = Logger.getLogger(ListEgressFirewallRulesCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListFirewallRulesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListFirewallRulesCmd.java index f79b77893d2..19a05b15890 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListFirewallRulesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListFirewallRulesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.firewall; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -38,7 +37,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listFirewallRules", description = "Lists all firewall rules for an IP address.", responseObject = FirewallResponse.class, entityType = {FirewallRule.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListFirewallRulesCmd extends BaseListTaggedResourcesCmd implements IListFirewallRulesCmd { - public static final Logger s_logger = Logger.getLogger(ListFirewallRulesCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java index 3a942c485fc..a2e9152a9e4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.firewall; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -37,7 +36,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listPortForwardingRules", description = "Lists all port forwarding rules for an IP address.", responseObject = FirewallRuleResponse.class, entityType = {PortForwardingRule.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListPortForwardingRulesCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListPortForwardingRulesCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdateEgressFirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdateEgressFirewallRuleCmd.java index 1aa06074367..a8db4ec2b29 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdateEgressFirewallRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdateEgressFirewallRuleCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.FirewallResponse; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -37,7 +36,6 @@ import com.cloud.network.rules.FirewallRule.TrafficType; @APICommand(name = "updateEgressFirewallRule", description = "Updates egress firewall rule ", responseObject = FirewallResponse.class, since = "4.4", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateEgressFirewallRuleCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateEgressFirewallRuleCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdateFirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdateFirewallRuleCmd.java index b39efa01350..89c9bc891eb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdateFirewallRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdateFirewallRuleCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.FirewallResponse; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -37,7 +36,6 @@ import com.cloud.network.rules.FirewallRule.TrafficType; @APICommand(name = "updateFirewallRule", description = "Updates firewall rule ", responseObject = FirewallResponse.class, since = "4.4", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateFirewallRuleCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateFirewallRuleCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java index da02aa4b174..ee4bd18ad40 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java @@ -24,7 +24,6 @@ import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.UserVmResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -40,7 +39,6 @@ import java.util.List; description = "Updates a port forwarding rule. Only the private port and the virtual machine can be updated.", entityType = {PortForwardingRule.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdatePortForwardingRuleCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdatePortForwardingRuleCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/guest/ListGuestOsCategoriesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/guest/ListGuestOsCategoriesCmd.java index 18a209011c1..c74514d662c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/guest/ListGuestOsCategoriesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/guest/ListGuestOsCategoriesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.guest; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listOsCategories", description = "Lists all supported OS categories for this cloud.", responseObject = GuestOSCategoryResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListGuestOsCategoriesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListGuestOsCategoriesCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/guest/ListGuestOsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/guest/ListGuestOsCmd.java index 9d6cd438561..b31a4669220 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/guest/ListGuestOsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/guest/ListGuestOsCmd.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.BooleanUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -37,7 +36,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listOsTypes", description = "Lists all supported OS types for this cloud.", responseObject = GuestOSResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListGuestOsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListGuestOsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/CreateIpv6FirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/CreateIpv6FirewallRuleCmd.java index d4c59cd8d47..18af5b2973e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/CreateIpv6FirewallRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/CreateIpv6FirewallRuleCmd.java @@ -32,7 +32,6 @@ import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -44,13 +43,12 @@ import com.cloud.user.Account; import com.cloud.utils.net.NetUtils; @APICommand(name = "createIpv6FirewallRule", - description = "Creates an Ipv6 firewall rule in the given network (the network has to belong to VPC)", + description = "Creates an Ipv6 firewall rule in the given network (the network must not belong to VPC)", responseObject = FirewallRuleResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class CreateIpv6FirewallRuleCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateIpv6FirewallRuleCmd.class.getName()); // /////////////////////////////////////////////////// @@ -224,7 +222,7 @@ public class CreateIpv6FirewallRuleCmd extends BaseAsyncCreateCmd { setEntityId(result.getId()); setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException e) { - s_logger.trace("Network Rule Conflict: ", e); + logger.trace("Network Rule Conflict: ", e); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage(), e); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/DeleteIpv6FirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/DeleteIpv6FirewallRuleCmd.java index 5e176a3fabf..aaee19b5948 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/DeleteIpv6FirewallRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/DeleteIpv6FirewallRuleCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceUnavailableException; @@ -41,7 +40,6 @@ import com.cloud.user.Account; responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class DeleteIpv6FirewallRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteIpv6FirewallRuleCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/ListIpv6FirewallRulesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/ListIpv6FirewallRulesCmd.java index 23941316275..7ade2e3ed04 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/ListIpv6FirewallRulesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/ListIpv6FirewallRulesCmd.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.api.response.FirewallResponse; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.NetworkResponse; -import org.apache.log4j.Logger; import com.cloud.network.rules.FirewallRule; import com.cloud.utils.Pair; @@ -41,7 +40,6 @@ import com.cloud.utils.Pair; responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class ListIpv6FirewallRulesCmd extends BaseListTaggedResourcesCmd implements IListFirewallRulesCmd { - public static final Logger s_logger = Logger.getLogger(ListIpv6FirewallRulesCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/UpdateIpv6FirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/UpdateIpv6FirewallRuleCmd.java index 49765c58daf..2d63d703dc5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/UpdateIpv6FirewallRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/ipv6/UpdateIpv6FirewallRuleCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.FirewallResponse; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceUnavailableException; @@ -41,7 +40,6 @@ import com.cloud.user.Account; responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class UpdateIpv6FirewallRuleCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateIpv6FirewallRuleCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java index cdc72de4a10..d795fbabb52 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.iso; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -39,7 +38,6 @@ import com.cloud.uservm.UserVm; @APICommand(name = "attachIso", description = "Attaches an ISO to a virtual machine.", responseObject = UserVmResponse.class, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class AttachIsoCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(AttachIsoCmd.class.getName()); private static final String s_name = "attachisoresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/CopyIsoCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/CopyIsoCmd.java index b7c13ce4adb..2db7b7e1eb9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/CopyIsoCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/CopyIsoCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.iso; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ResponseObject.ResponseView; @@ -26,6 +25,5 @@ import org.apache.cloudstack.api.response.TemplateResponse; @APICommand(name = "copyIso", description = "Copies an ISO from one zone to another.", responseObject = TemplateResponse.class, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CopyIsoCmd extends CopyTemplateCmd { - public static final Logger s_logger = Logger.getLogger(CopyIsoCmd.class.getName()); private static final String s_name = "copyisoresponse"; } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java index 504e7c1b5cf..feae31026b9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.iso; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteIso", description = "Deletes an ISO file.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteIsoCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteIsoCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java index e3b22c4a49f..292e1c6f099 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.iso; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.uservm.UserVm; @APICommand(name = "detachIso", description = "Detaches any ISO file (if any) currently attached to a virtual machine.", responseObject = UserVmResponse.class, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class DetachIsoCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(DetachIsoCmd.class.getName()); private static final String s_name = "detachisoresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java index 03ba2fab722..4d11f0dc3d2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java @@ -16,8 +16,8 @@ // under the License. package org.apache.cloudstack.api.command.user.iso; -import org.apache.log4j.Logger; +import com.cloud.dc.DataCenter; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "extractIso", description = "Extracts an ISO", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractIsoCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ExtractIsoCmd.class.getName()); ///////////////////////////////////////////////////// @@ -103,7 +102,15 @@ public class ExtractIsoCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "extracting ISO: " + getId() + " from zone: " + getZoneId(); + String isoId = this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()); + String baseDescription = String.format("Extracting ISO: %s", isoId); + + Long zoneId = getZoneId(); + if (zoneId == null) { + return baseDescription; + } + + return String.format("%s from zone: %s", baseDescription, this._uuidMgr.getUuid(DataCenter.class, zoneId)); } @Override @@ -122,7 +129,7 @@ public class ExtractIsoCmd extends BaseAsyncCmd { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { - ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); + ExtractResponse response = _responseGenerator.createImageExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); response.setObjectName("iso"); this.setResponseObject(response); @@ -130,7 +137,7 @@ public class ExtractIsoCmd extends BaseAsyncCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract ISO"); } } catch (InternalErrorException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/GetUploadParamsForIsoCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/GetUploadParamsForIsoCmd.java index e1759566299..01a47f22b72 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/GetUploadParamsForIsoCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/GetUploadParamsForIsoCmd.java @@ -117,7 +117,7 @@ public class GetUploadParamsForIsoCmd extends AbstractGetUploadParamsCmd { response.setResponseName(getCommandName()); setResponseObject(response); } catch (ResourceAllocationException | MalformedURLException e) { - s_logger.error("Exception while registering ISO", e); + logger.error("Exception while registering ISO", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Exception while registering ISO: " + e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ListIsoPermissionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ListIsoPermissionsCmd.java index fbbe0880aef..6f220c774b8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ListIsoPermissionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ListIsoPermissionsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.iso; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; @@ -40,10 +39,6 @@ public class ListIsoPermissionsCmd extends BaseListTemplateOrIsoPermissionsCmd i return "iso"; } - @Override - protected Logger getLogger() { - return Logger.getLogger(ListIsoPermissionsCmd.class.getName()); - } @Override protected boolean templateIsCorrectType(VirtualMachineTemplate template) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java index f723cb93ae9..5c4d606a93c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java @@ -16,10 +16,10 @@ // under the License. package org.apache.cloudstack.api.command.user.iso; +import com.cloud.cpu.CPU; import com.cloud.server.ResourceIcon; import com.cloud.server.ResourceTag; import org.apache.cloudstack.api.response.ResourceIconResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -35,13 +35,13 @@ import org.apache.cloudstack.context.CallContext; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; +import org.apache.commons.lang3.StringUtils; import java.util.List; @APICommand(name = "listIsos", description = "Lists all available ISO files.", responseObject = TemplateResponse.class, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListIsosCmd extends BaseListTaggedResourcesCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListIsosCmd.class.getName()); private static final String s_name = "listisosresponse"; @@ -90,6 +90,11 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd implements UserCmd { @Parameter(name = ApiConstants.SHOW_RESOURCE_ICON, type = CommandType.BOOLEAN, description = "flag to display the resource image for the isos") private Boolean showIcon; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "the CPU arch of the ISO. Valid options are: x86_64, aarch64", + since = "4.20") + private String arch; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -161,6 +166,13 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd implements UserCmd { return onlyReady; } + public CPU.CPUArch getArch() { + if (StringUtils.isBlank(arch)) { + return null; + } + return CPU.CPUArch.fromType(arch); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java index 1d750038042..81f52552289 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java @@ -18,6 +18,7 @@ package org.apache.cloudstack.api.command.user.iso; import java.util.List; +import com.cloud.cpu.CPU; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +36,6 @@ import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.exception.ResourceAllocationException; import com.cloud.template.VirtualMachineTemplate; @@ -43,7 +43,6 @@ import com.cloud.template.VirtualMachineTemplate; @APICommand(name = "registerIso", responseObject = TemplateResponse.class, description = "Registers an existing ISO into the CloudStack Cloud.", responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RegisterIsoCmd extends BaseCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(RegisterIsoCmd.class.getName()); private static final String s_name = "registerisoresponse"; @@ -120,6 +119,11 @@ public class RegisterIsoCmd extends BaseCmd implements UserCmd { description = "true if password reset feature is supported; default is false") private Boolean passwordEnabled; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "the CPU arch of the ISO. Valid options are: x86_64, aarch64", + since = "4.20") + private String arch; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -231,6 +235,14 @@ public class RegisterIsoCmd extends BaseCmd implements UserCmd { return passwordEnabled == null ? false : passwordEnabled; } + public void setArch(String arch) { + this.arch = arch; + } + + public CPU.CPUArch getArch() { + return CPU.CPUArch.fromType(arch); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java index 58c475c661e..95d9feed7e3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.iso; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiErrorCode; @@ -33,7 +32,6 @@ import com.cloud.user.Account; @APICommand(name = "updateIso", description = "Updates an ISO file.", responseObject = TemplateResponse.class, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateIsoCmd extends BaseUpdateTemplateOrIsoCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(UpdateIsoCmd.class.getName()); private static final String s_name = "updateisoresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/UpdateIsoPermissionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/UpdateIsoPermissionsCmd.java index dd07faf9a87..02ada253fd2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/UpdateIsoPermissionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/UpdateIsoPermissionsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.iso; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; @@ -33,10 +32,6 @@ public class UpdateIsoPermissionsCmd extends BaseUpdateTemplateOrIsoPermissionsC return "updateisopermissionsresponse"; } - @Override - protected Logger getLogger() { - return Logger.getLogger(UpdateIsoPermissionsCmd.class.getName()); - } @Override public long getEntityOwnerId() { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/job/QueryAsyncJobResultCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/job/QueryAsyncJobResultCmd.java index f578078e3a1..3d328543dc2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/job/QueryAsyncJobResultCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/job/QueryAsyncJobResultCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.job; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -29,7 +28,6 @@ import com.cloud.user.Account; @APICommand(name = "queryAsyncJobResult", description = "Retrieves the current status of asynchronous job.", responseObject = AsyncJobResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class QueryAsyncJobResultCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(QueryAsyncJobResultCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/AssignCertToLoadBalancerCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/AssignCertToLoadBalancerCmd.java index 50d69c8d3ae..4f9d2f37d13 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/AssignCertToLoadBalancerCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/AssignCertToLoadBalancerCmd.java @@ -17,7 +17,6 @@ // under the License. package org.apache.cloudstack.api.command.user.loadbalancer; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -42,7 +41,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AssignCertToLoadBalancerCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(AssignCertToLoadBalancerCmd.class.getName()); @Parameter(name = ApiConstants.LBID, diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java index dc27587b917..c4424b1d937 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Map; import com.cloud.utils.exception.CloudRuntimeException; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -51,7 +50,6 @@ import com.cloud.vm.VirtualMachine; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(AssignToLoadBalancerRuleCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateApplicationLoadBalancerCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateApplicationLoadBalancerCmd.java index 8c63c8f7951..2199dfb4e8b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateApplicationLoadBalancerCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateApplicationLoadBalancerCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.response.ApplicationLoadBalancerResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.network.lb.ApplicationLoadBalancerRule; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientAddressCapacityException; @@ -44,7 +43,6 @@ import com.cloud.utils.net.NetUtils; @APICommand(name = "createLoadBalancer", description = "Creates an internal load balancer", responseObject = ApplicationLoadBalancerResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateApplicationLoadBalancerCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateApplicationLoadBalancerCmd.class.getName()); ///////////////////////////////////////////////////// @@ -202,7 +200,7 @@ public class CreateApplicationLoadBalancerCmd extends BaseAsyncCreateCmd { setResponseObject(lbResponse); lbResponse.setResponseName(getCommandName()); } catch (Exception ex) { - s_logger.warn("Failed to create load balancer due to exception ", ex); + logger.warn("Failed to create load balancer due to exception ", ex); } finally { if (rule == null) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create load balancer"); @@ -220,13 +218,13 @@ public class CreateApplicationLoadBalancerCmd extends BaseAsyncCreateCmd { this.setEntityId(result.getId()); this.setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } catch (InsufficientAddressCapacityException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, e.getMessage()); } catch (InsufficientVirtualNetworkCapacityException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBHealthCheckPolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBHealthCheckPolicyCmd.java index 57cb8078738..c24a5f19f07 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBHealthCheckPolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBHealthCheckPolicyCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.LBHealthCheckResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -44,7 +43,6 @@ import com.cloud.user.Account; responseHasSensitiveInfo = false) @SuppressWarnings("rawtypes") public class CreateLBHealthCheckPolicyCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateLBHealthCheckPolicyCmd.class.getName()); // /////////////////////////////////////////////////// @@ -181,7 +179,7 @@ public class CreateLBHealthCheckPolicyCmd extends BaseAsyncCreateCmd { this.setEntityId(result.getId()); this.setEntityUuid(result.getUuid()); } catch (InvalidParameterValueException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.MALFORMED_PARAMETER_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java index 66a15984ae4..c6b5036bc95 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.LBStickinessResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -44,7 +43,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) @SuppressWarnings("rawtypes") public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateLBStickinessPolicyCmd.class.getName()); private static final String s_name = "createLBStickinessPolicy"; @@ -164,7 +162,7 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { this.setEntityId(result.getId()); this.setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java index b741310cb16..34798c4efe1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java @@ -33,7 +33,6 @@ import org.apache.cloudstack.api.response.LoadBalancerResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -52,7 +51,6 @@ import com.cloud.utils.net.NetUtils; @APICommand(name = "createLoadBalancerRule", description = "Creates a load balancer rule", responseObject = LoadBalancerResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements LoadBalancer */{ - public static final Logger s_logger = Logger.getLogger(CreateLoadBalancerRuleCmd.class.getName()); ///////////////////////////////////////////////////// @@ -284,7 +282,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements L } lbResponse.setResponseName(getCommandName()); } catch (Exception ex) { - s_logger.warn("Failed to create LB rule due to exception ", ex); + logger.warn("Failed to create LB rule due to exception ", ex); } finally { if (!success || rule == null) { @@ -309,10 +307,10 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements L this.setEntityId(result.getId()); this.setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } catch (InsufficientAddressCapacityException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, e.getMessage()); } catch (InvalidParameterValueException e) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.getMessage()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteApplicationLoadBalancerCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteApplicationLoadBalancerCmd.java index 912c760168b..410df086393 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteApplicationLoadBalancerCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteApplicationLoadBalancerCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.loadbalancer; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -36,7 +35,6 @@ import com.cloud.exception.InvalidParameterValueException; @APICommand(name = "deleteLoadBalancer", description = "Deletes an internal load balancer", responseObject = SuccessResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteApplicationLoadBalancerCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteApplicationLoadBalancerCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBHealthCheckPolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBHealthCheckPolicyCmd.java index 159d6b21cbc..3cf1f345037 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBHealthCheckPolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBHealthCheckPolicyCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.loadbalancer; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteLBHealthCheckPolicy", description = "Deletes a load balancer health check policy.", responseObject = SuccessResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteLBHealthCheckPolicyCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteLBHealthCheckPolicyCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java index 10c342911b4..5d04de3cae5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.loadbalancer; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteLBStickinessPolicy", description = "Deletes a load balancer stickiness policy.", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteLBStickinessPolicyCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteLBStickinessPolicyCmd.class.getName()); private static final String s_name = "deleteLBstickinessrruleresponse"; // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java index f05d4cd2be3..b4079430ee3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.loadbalancer; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteLoadBalancerRule", description = "Deletes a load balancer rule.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteLoadBalancerRuleCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteSslCertCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteSslCertCmd.java index 3db733182a1..887007e537e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteSslCertCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/DeleteSslCertCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.loadbalancer; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "deleteSslCert", description = "Delete a certificate to CloudStack", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteSslCertCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteSslCertCmd.class.getName()); @Inject diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListApplicationLoadBalancersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListApplicationLoadBalancersCmd.java index ad68b301844..d54f3e1155e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListApplicationLoadBalancersCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListApplicationLoadBalancersCmd.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.network.lb.ApplicationLoadBalancerRule; -import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.LoadBalancerContainer.Scheme; @@ -38,7 +37,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listLoadBalancers", description = "Lists internal load balancers", responseObject = ApplicationLoadBalancerResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListApplicationLoadBalancersCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListApplicationLoadBalancersCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLBHealthCheckPoliciesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLBHealthCheckPoliciesCmd.java index 1c1f5d1f9af..cb2cdb446d1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLBHealthCheckPoliciesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLBHealthCheckPoliciesCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.LBHealthCheckResponse; import org.apache.cloudstack.api.response.ListResponse; -import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; @@ -37,7 +36,6 @@ import com.cloud.network.rules.LoadBalancer; @APICommand(name = "listLBHealthCheckPolicies", description = "Lists load balancer health check policies.", responseObject = LBHealthCheckResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListLBHealthCheckPoliciesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListLBHealthCheckPoliciesCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java index 3d08d925797..a48e2ea37b7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.LBStickinessResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.network.rules.LoadBalancer; import com.cloud.network.rules.StickinessPolicy; @@ -38,7 +37,6 @@ import com.cloud.user.Account; @APICommand(name = "listLBStickinessPolicies", description = "Lists load balancer stickiness policies.", responseObject = LBStickinessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListLBStickinessPoliciesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListLBStickinessPoliciesCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRuleInstancesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRuleInstancesCmd.java index 723e0efec12..3bfc68a95ba 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRuleInstancesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRuleInstancesCmd.java @@ -23,7 +23,6 @@ import com.cloud.vm.VirtualMachine; import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.LoadBalancerRuleVmMapResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -41,7 +40,6 @@ import com.cloud.utils.Pair; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class ListLoadBalancerRuleInstancesCmd extends BaseListCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListLoadBalancerRuleInstancesCmd.class.getName()); private static final String s_name = "listloadbalancerruleinstancesresponse"; @@ -97,10 +95,10 @@ public class ListLoadBalancerRuleInstancesCmd extends BaseListCmd implements Use public void execute() { Pair, List> vmServiceMap = _lbService.listLoadBalancerInstances(this); List result = vmServiceMap.first(); - s_logger.debug(String.format("A total of [%s] user VMs were obtained when listing the load balancer instances: [%s].", result.size(), result)); + logger.debug(String.format("A total of [%s] user VMs were obtained when listing the load balancer instances: [%s].", result.size(), result)); List serviceStates = vmServiceMap.second(); - s_logger.debug(String.format("A total of [%s] service states were obtained when listing the load balancer instances: [%s].", serviceStates.size(), serviceStates)); + logger.debug(String.format("A total of [%s] service states were obtained when listing the load balancer instances: [%s].", serviceStates.size(), serviceStates)); if (!isListLbVmip()) { ListResponse response = new ListResponse<>(); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRulesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRulesCmd.java index 51a8fa4bfc8..b8b82f0c4a8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRulesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRulesCmd.java @@ -31,7 +31,6 @@ import org.apache.cloudstack.api.response.LoadBalancerResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; import com.cloud.network.rules.LoadBalancer; import com.cloud.utils.Pair; @@ -39,7 +38,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listLoadBalancerRules", description = "Lists load balancer rules.", responseObject = LoadBalancerResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListLoadBalancerRulesCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListLoadBalancerRulesCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListSslCertsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListSslCertsCmd.java index 3f422801780..1bc300fdc69 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListSslCertsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/ListSslCertsCmd.java @@ -20,7 +20,6 @@ import java.util.List; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -39,7 +38,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "listSslCerts", description = "Lists SSL certificates", responseObject = SslCertResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListSslCertsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ListSslCertsCmd.class.getName()); @Inject diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/RemoveCertFromLoadBalancerCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/RemoveCertFromLoadBalancerCmd.java index 38593629f78..dfaafe89923 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/RemoveCertFromLoadBalancerCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/RemoveCertFromLoadBalancerCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.loadbalancer; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RemoveCertFromLoadBalancerCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RemoveCertFromLoadBalancerCmd.class.getName()); @Parameter(name = ApiConstants.LBID, diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java index 01c30c4b3c7..d29f2676ed5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java @@ -24,7 +24,6 @@ import java.util.Iterator; import java.util.ArrayList; import com.cloud.vm.VirtualMachine; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -49,7 +48,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RemoveFromLoadBalancerRuleCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateApplicationLoadBalancerCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateApplicationLoadBalancerCmd.java index 27d49096ed6..d129cd8988f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateApplicationLoadBalancerCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateApplicationLoadBalancerCmd.java @@ -25,7 +25,6 @@ import org.apache.cloudstack.api.response.ApplicationLoadBalancerResponse; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.network.lb.ApplicationLoadBalancerRule; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -34,7 +33,6 @@ import com.cloud.network.rules.FirewallRule; @APICommand(name = "updateLoadBalancer", description = "Updates an internal load balancer", responseObject = ApplicationLoadBalancerResponse.class, since = "4.4.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateApplicationLoadBalancerCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateApplicationLoadBalancerCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBHealthCheckPolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBHealthCheckPolicyCmd.java index b6bb59e60dc..fdd98fc3a0a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBHealthCheckPolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBHealthCheckPolicyCmd.java @@ -19,7 +19,6 @@ import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.LBHealthCheckResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.network.rules.HealthCheckPolicy; @@ -30,7 +29,6 @@ import com.cloud.user.Account; @APICommand(name = "updateLBHealthCheckPolicy", description = "Updates load balancer health check policy", responseObject = LBHealthCheckResponse.class, since = "4.4", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateLBHealthCheckPolicyCmd extends BaseAsyncCustomIdCmd{ - public static final Logger s_logger = Logger.getLogger(UpdateLBHealthCheckPolicyCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBStickinessPolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBStickinessPolicyCmd.java index 2b1f1cc38f6..b2137cf262d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBStickinessPolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBStickinessPolicyCmd.java @@ -19,7 +19,6 @@ import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.LBStickinessResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.network.rules.LoadBalancer; @@ -29,7 +28,6 @@ import com.cloud.user.Account; @APICommand(name = "updateLBStickinessPolicy", description = "Updates load balancer stickiness policy", responseObject = LBStickinessResponse.class, since = "4.4", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateLBStickinessPolicyCmd extends BaseAsyncCustomIdCmd{ - public static final Logger s_logger = Logger.getLogger(UpdateLBStickinessPolicyCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java index b09c01adee6..25254ba9eb7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.cloudstack.api.response.LoadBalancerResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +37,6 @@ import com.cloud.user.Account; @APICommand(name = "updateLoadBalancerRule", description = "Updates load balancer", responseObject = LoadBalancerResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateLoadBalancerRuleCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateLoadBalancerRuleCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UploadSslCertCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UploadSslCertCmd.java index abafde85615..e51b4dee9db 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UploadSslCertCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UploadSslCertCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.loadbalancer; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -41,7 +40,6 @@ import org.apache.cloudstack.network.tls.CertService; @APICommand(name = "uploadSslCert", description = "Upload a certificate to CloudStack", responseObject = SslCertResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UploadSslCertCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UploadSslCertCmd.class.getName()); @Inject diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java index 62c4906b1b7..e883a7a0e4d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.nat; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -45,7 +44,6 @@ import com.cloud.user.Account; @APICommand(name = "createIpForwardingRule", description = "Creates an IP forwarding rule", responseObject = FirewallRuleResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements StaticNatRule { - public static final Logger s_logger = Logger.getLogger(CreateIpForwardingRuleCmd.class.getName()); ///////////////////////////////////////////////////// @@ -150,7 +148,7 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta setEntityId(rule.getId()); setEntityUuid(rule.getUuid()); } catch (NetworkRuleConflictException e) { - s_logger.info("Unable to create static NAT rule due to ", e); + logger.info("Unable to create static NAT rule due to ", e); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java index 5b1335ccf22..e4c16a31751 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.nat; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -37,7 +36,6 @@ import com.cloud.network.rules.FirewallRule; @APICommand(name = "deleteIpForwardingRule", description = "Deletes an IP forwarding rule", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteIpForwardingRuleCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java index 9afdfa3642e..2bee7dfcc89 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.nat; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.network.IpAddress; @APICommand(name = "disableStaticNat", description = "Disables static rule for given IP address", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DisableStaticNatCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DisableStaticNatCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java index ba97356582a..48c6cc20bf1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.nat; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.uservm.UserVm; @APICommand(name = "enableStaticNat", description = "Enables static NAT for given IP address", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class EnableStaticNatCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(EnableStaticNatCmd.class.getName()); ///////////////////////////////////////////////////// @@ -133,8 +131,8 @@ public class EnableStaticNatCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to enable static NAT"); } } catch (NetworkRuleConflictException ex) { - s_logger.info("Network rule conflict: " + ex.getMessage()); - s_logger.trace("Network Rule Conflict: ", ex); + logger.info("Network rule conflict: " + ex.getMessage()); + logger.trace("Network Rule Conflict: ", ex); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/nat/ListIpForwardingRulesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/nat/ListIpForwardingRulesCmd.java index 5e9da328bc8..89981a6453b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/nat/ListIpForwardingRulesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/nat/ListIpForwardingRulesCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.nat; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listIpForwardingRules", description = "List the IP forwarding rules", responseObject = FirewallRuleResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListIpForwardingRulesCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java index 70e67151c1d..8d8e598bcab 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java @@ -32,7 +32,6 @@ import org.apache.cloudstack.api.response.NetworkACLResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -43,7 +42,6 @@ import com.cloud.utils.net.NetUtils; @APICommand(name = "createNetworkACL", description = "Creates a ACL rule in the given network (the network has to belong to VPC)", responseObject = NetworkACLItemResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateNetworkACLCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateNetworkACLCmd.class.getName()); // /////////////////////////////////////////////////// @@ -115,6 +113,10 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd { return p; } + public void setProtocol(String protocol) { + this.protocol = protocol; + } + public List getSourceCidrList() { if (cidrlist != null) { return cidrlist; @@ -138,6 +140,9 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd { throw new InvalidParameterValueException("Invalid traffic type " + trafficType); } + public void setTrafficType(String trafficType) { + this.trafficType = trafficType; + } // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -146,15 +151,23 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd { return action; } + public void setAction(String action) { + this.action = action; + } + public Integer getNumber() { return number; } - public Integer getSourcePortStart() { + public Integer getPublicStartPort() { return publicStartPort; } - public Integer getSourcePortEnd() { + public void setPublicStartPort(Integer publicStartPort) { + this.publicStartPort = publicStartPort; + } + + public Integer getPublicEndPort() { if (publicEndPort == null) { if (publicStartPort != null) { return publicStartPort; @@ -166,10 +179,18 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd { return null; } + public void setPublicEndPort(Integer publicEndPort) { + this.publicEndPort = publicEndPort; + } + public Long getNetworkId() { return networkId; } + public void setNetworkId(Long networkId) { + this.networkId = networkId; + } + @Override public long getEntityOwnerId() { Account caller = CallContext.current().getCallingAccount(); @@ -209,6 +230,10 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd { return aclId; } + public void setAclId(Long aclId) { + this.aclId = aclId; + } + public String getReason() { return reason; } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkACLListCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkACLListCmd.java index e5dbcc7b6d1..cd25a604e77 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkACLListCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkACLListCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.NetworkACLResponse; import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +40,6 @@ import com.cloud.user.Account; responseObject = NetworkACLResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateNetworkACLListCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateNetworkACLListCmd.class.getName()); // /////////////////////////////////////////////////// @@ -130,7 +128,7 @@ public class CreateNetworkACLListCmd extends BaseAsyncCreateCmd { } else { account = CallContext.current().getCallingAccount(); if (!Account.Type.ADMIN.equals(account.getType())) { - s_logger.warn(String.format("Only Root Admin can create global ACLs. Account [%s] cannot create any global ACL.", account)); + logger.warn(String.format("Only Root Admin can create global ACLs. Account [%s] cannot create any global ACL.", account)); throw new PermissionDeniedException("Only Root Admin can create global ACLs."); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java index ca379fb1596..aca3d3ca1b4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.network; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -51,7 +50,6 @@ import com.cloud.utils.net.NetUtils; @APICommand(name = "createNetwork", description = "Creates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateNetworkCmd extends BaseCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(CreateNetworkCmd.class.getName()); private static final String s_name = "createnetworkresponse"; @@ -193,6 +191,14 @@ public class CreateNetworkCmd extends BaseCmd implements UserCmd { since = "4.19") private String sourceNatIP; + @Parameter(name = ApiConstants.CIDR_SIZE, type = CommandType.INTEGER, + description = "the CIDR size of IPv4 network. For regular users, this is required for isolated networks with ROUTED mode.", + since = "4.20.0") + private Integer cidrSize; + + @Parameter(name=ApiConstants.AS_NUMBER, type=CommandType.LONG, since = "4.20.0", description="the AS Number of the network") + private Long asNumber; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -366,6 +372,10 @@ public class CreateNetworkCmd extends BaseCmd implements UserCmd { return NetUtils.standardizeIp6Cidr(ip6Cidr); } + public Integer getCidrSize() { + return cidrSize; + } + public Long getAclId() { return aclId; } @@ -393,6 +403,10 @@ public class CreateNetworkCmd extends BaseCmd implements UserCmd { return ip6Dns2; } + public Long getAsNumber() { + return asNumber; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkPermissionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkPermissionsCmd.java index 4a1f65ba7a2..1df472cbb22 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkPermissionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/CreateNetworkPermissionsCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; @@ -43,7 +42,6 @@ import java.util.List; since = "4.17.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class CreateNetworkPermissionsCmd extends BaseCmd { - public static final Logger LOGGER = Logger.getLogger(CreateNetworkPermissionsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java index f171492b2f6..ca42626eacb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.network; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteNetworkACL", description = "Deletes a network ACL", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteNetworkACLCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteNetworkACLCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLListCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLListCmd.java index 5c24efae6eb..45bc86e8c91 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLListCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLListCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.network; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteNetworkACLList", description = "Deletes a network ACL", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteNetworkACLListCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteNetworkACLListCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java index 5f15c23e23f..8e8e18c6702 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -37,7 +36,6 @@ import com.cloud.network.Network; @APICommand(name = "deleteNetwork", description = "Deletes a network", responseObject = SuccessResponse.class, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteNetworkCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteNetworkCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java index f3a06142d78..c88f956943b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkACLListsCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.NetworkACLResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.VpcResponse; -import org.apache.log4j.Logger; import com.cloud.network.vpc.NetworkACL; import com.cloud.utils.Pair; @@ -36,7 +35,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listNetworkACLLists", description = "Lists all network ACLs", responseObject = NetworkACLResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListNetworkACLListsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListNetworkACLListsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java index 945142f4df0..1ef2b9b7bfb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.NetworkACLItemResponse; import org.apache.cloudstack.api.response.NetworkACLResponse; import org.apache.cloudstack.api.response.NetworkResponse; -import org.apache.log4j.Logger; import com.cloud.network.vpc.NetworkACLItem; import com.cloud.utils.Pair; @@ -36,7 +35,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listNetworkACLs", description = "Lists all network ACL items", responseObject = NetworkACLItemResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListNetworkACLsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java index 70c01fd1d88..bdc89d804cd 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.NetworkOfferingResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; import com.cloud.offering.NetworkOffering; import com.cloud.utils.Pair; @@ -36,7 +35,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listNetworkOfferings", description = "Lists all available network offerings.", responseObject = NetworkOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListNetworkOfferingsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListNetworkOfferingsCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -112,6 +110,12 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { @Parameter(name = ApiConstants.FOR_VPC, type = CommandType.BOOLEAN, description = "the network offering can be used" + " only for network creation inside the VPC") private Boolean forVpc; + @Parameter(name = ApiConstants.ROUTING_MODE, + type = CommandType.STRING, + description = "the routing mode for the network offering. Supported types are: Static or Dynamic.", + since = "4.20.0") + private String routingMode; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -188,6 +192,8 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { return forVpc; } + public String getRoutingMode() { return routingMode; } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkPermissionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkPermissionsCmd.java index 9e6b01d3676..6ea4937e115 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkPermissionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkPermissionsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -42,7 +41,6 @@ import java.util.List; since = "4.17.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class ListNetworkPermissionsCmd extends BaseCmd implements UserCmd { - public static final Logger LOGGER = Logger.getLogger(ListNetworkPermissionsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkProtocolsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkProtocolsCmd.java new file mode 100644 index 00000000000..a7c359d66c2 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworkProtocolsCmd.java @@ -0,0 +1,107 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.network; + +import com.cloud.utils.net.NetworkProtocols; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkProtocolResponse; +import org.apache.cloudstack.context.CallContext; + +import java.util.ArrayList; +import java.util.List; + +@APICommand(name = "listNetworkProtocols", description = "Lists details of network protocols", responseObject = NetworkProtocolResponse.class, + requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, + authorized = { RoleType.Admin, RoleType.DomainAdmin, RoleType.ResourceAdmin, RoleType.User}, since = "4.19.0") +public class ListNetworkProtocolsCmd extends BaseCmd { + + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.OPTION, type = CommandType.STRING, required = true, + description = "The option of network protocols. Supported values are: protocolnumber, icmptype.") + private String option; + + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + + public String getOption() { + return option; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() { + ListResponse response = new ListResponse<>(); + List networkProtocolResponses = new ArrayList<>(); + + NetworkProtocols.Option option = NetworkProtocols.Option.getOption(getOption()); + switch (option) { + case ProtocolNumber: + updateResponseWithProtocolNumbers(networkProtocolResponses); + break; + case IcmpType: + updateResponseWithIcmpTypes(networkProtocolResponses); + break; + default: + break; + } + + response.setResponses(networkProtocolResponses); + response.setResponseName(getCommandName()); + setResponseObject(response); + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + private void updateResponseWithProtocolNumbers(List responses) { + for (NetworkProtocols.ProtocolNumber protocolNumber : NetworkProtocols.ProtocolNumbers) { + NetworkProtocolResponse networkProtocolResponse = new NetworkProtocolResponse(protocolNumber.getNumber(), + protocolNumber.getKeyword(), protocolNumber.getProtocol()); + networkProtocolResponse.setObjectName("networkprotocol"); + responses.add(networkProtocolResponse); + } + } + + private void updateResponseWithIcmpTypes(List responses) { + for (NetworkProtocols.IcmpType icmpType : NetworkProtocols.IcmpTypes) { + NetworkProtocolResponse networkProtocolResponse = new NetworkProtocolResponse(icmpType.getType(), + null, icmpType.getDescription()); + for (NetworkProtocols.IcmpCode code : icmpType.getIcmpCodes()) { + networkProtocolResponse.addDetail(String.valueOf(code.getCode()), code.getDescription()); + } + networkProtocolResponse.setObjectName("networkprotocol"); + responses.add(networkProtocolResponse); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java index c1e85a9b4c3..0e8425b14b4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java @@ -24,7 +24,6 @@ import com.cloud.server.ResourceTag; import org.apache.cloudstack.api.response.NetworkOfferingResponse; import org.apache.cloudstack.api.response.ResourceIconResponse; import org.apache.commons.lang3.BooleanUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -46,7 +45,6 @@ import org.apache.commons.lang3.StringUtils; @APICommand(name = "listNetworks", description = "Lists all available networks.", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListNetworksCmd extends BaseListRetrieveOnlyResourceCountCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListNetworksCmd.class.getName()); private static final String s_name = "listnetworksresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/MoveNetworkAclItemCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/MoveNetworkAclItemCmd.java index da6ac437aa0..5d36dcfd8e9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/MoveNetworkAclItemCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/MoveNetworkAclItemCmd.java @@ -23,7 +23,6 @@ import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.NetworkACLItemResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.network.vpc.NetworkACLItem; @@ -32,7 +31,6 @@ import com.cloud.user.Account; @APICommand(name = "moveNetworkAclItem", description = "Move an ACL rule to a position bettwen two other ACL rules of the same ACL network list", responseObject = NetworkACLItemResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class MoveNetworkAclItemCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(MoveNetworkAclItemCmd.class.getName()); private static final String s_name = "moveNetworkAclItemResponse"; @Parameter(name = ApiConstants.ID, type = CommandType.STRING, required = true, description = "The ID of the network ACL rule that is being moved to a new position.") diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/RemoveNetworkPermissionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/RemoveNetworkPermissionsCmd.java index 05785c81588..c199d872e0c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/RemoveNetworkPermissionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/RemoveNetworkPermissionsCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; @@ -43,7 +42,6 @@ import java.util.List; since = "4.17.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class RemoveNetworkPermissionsCmd extends BaseCmd { - public static final Logger LOGGER = Logger.getLogger(RemoveNetworkPermissionsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ReplaceNetworkACLListCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ReplaceNetworkACLListCmd.java index ea4e74149f4..f6e9557aadb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ReplaceNetworkACLListCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ReplaceNetworkACLListCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.network; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "replaceNetworkACLList", description = "Replaces ACL associated with a network or private gateway", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ReplaceNetworkACLListCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ReplaceNetworkACLListCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ResetNetworkPermissionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ResetNetworkPermissionsCmd.java index f9817f9be5f..a23b98c84a8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ResetNetworkPermissionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ResetNetworkPermissionsCmd.java @@ -25,7 +25,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.log4j.Logger; import com.cloud.network.Network; import com.cloud.user.Account; @@ -38,7 +37,6 @@ import com.cloud.user.Account; since = "4.17.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class ResetNetworkPermissionsCmd extends BaseCmd { - public static final Logger LOGGER = Logger.getLogger(ResetNetworkPermissionsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java index 141dee3c9a0..ffc2e36dee5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -43,7 +42,6 @@ import com.cloud.network.Network; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RestartNetworkCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RestartNetworkCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkACLItemCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkACLItemCmd.java index f675fa23e34..42cb0697edb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkACLItemCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkACLItemCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.NetworkACLItemResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceUnavailableException; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "updateNetworkACLItem", description = "Updates ACL item with specified ID", responseObject = NetworkACLItemResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkACLItemCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateNetworkACLItemCmd.class.getName()); private static final String s_name = "createnetworkaclresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkACLListCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkACLListCmd.java index ddcb202aa8d..adab885542d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkACLListCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkACLListCmd.java @@ -25,7 +25,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.NetworkACLResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceUnavailableException; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "updateNetworkACLList", description = "Updates network ACL list", responseObject = SuccessResponse.class, since = "4.4", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkACLListCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateNetworkACLListCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java index d3cc169b7da..0d92a635e7f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java @@ -31,7 +31,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.NetworkOfferingResponse; import org.apache.cloudstack.api.response.NetworkResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -43,7 +42,6 @@ import com.cloud.offering.NetworkOffering; @APICommand(name = "updateNetwork", description = "Updates a network", responseObject = NetworkResponse.class, responseView = ResponseView.Restricted, entityType = {Network.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateNetworkCmd extends BaseAsyncCustomIdCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); private static final String s_name = "updatenetworkresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/CreateRoutingFirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/CreateRoutingFirewallRuleCmd.java new file mode 100644 index 00000000000..7146d1ae1d1 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/CreateRoutingFirewallRuleCmd.java @@ -0,0 +1,271 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.network.routing; + +import java.util.ArrayList; +import java.util.List; + +import com.cloud.exception.NetworkRuleConflictException; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiCommandResourceType; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.commons.lang3.StringUtils; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.rules.FirewallRule; +import com.cloud.user.Account; +import com.cloud.utils.net.NetUtils; + +@APICommand(name = "createRoutingFirewallRule", + description = "Creates a routing firewall rule in the given network in ROUTED mode", + since = "4.20.0", + responseObject = FirewallRuleResponse.class, + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class CreateRoutingFirewallRuleCmd extends BaseAsyncCreateCmd { + + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, description = "the protocol for the firewall rule. Valid values are TCP/UDP/ICMP/ALL or valid protocol number") + private String protocol; + + @Parameter(name = ApiConstants.START_PORT, type = CommandType.INTEGER, description = "the starting port of firewall rule") + private Integer publicStartPort; + + @Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "the ending port of firewall rule") + private Integer publicEndPort; + + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, + description = "the source CIDR list to allow traffic from. Multiple entries must be separated by a single comma character (,).") + protected List sourceCidrList; + + @Parameter(name = ApiConstants.DEST_CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, + description = "the destination CIDR list to allow traffic to. Multiple entries must be separated by a single comma character (,).") + protected List destinationCidrlist; + + @Parameter(name = ApiConstants.ICMP_TYPE, type = CommandType.INTEGER, description = "type of the ICMP message being sent") + private Integer icmpType; + + @Parameter(name = ApiConstants.ICMP_CODE, type = CommandType.INTEGER, description = "error code for this ICMP message") + private Integer icmpCode; + + @Parameter(name = ApiConstants.NETWORK_ID, type = CommandType.UUID, entityType = NetworkResponse.class, + description = "The network of the VM the firewall rule will be created for", required = true) + private Long networkId; + + @Parameter(name = ApiConstants.TRAFFIC_TYPE, type = CommandType.STRING, + description = "the traffic type for the Routing firewall rule, can be ingress or egress, defaulted to ingress if not specified") + private String trafficType; + + @Parameter(name = ApiConstants.FOR_DISPLAY, type = CommandType.BOOLEAN, + description = "an optional field, whether to the display the rule to the end user or not", authorized = {RoleType.Admin}) + private Boolean display; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + @Override + public boolean isDisplay() { + if (display != null) { + return display; + } else { + return true; + } + } + + public String getProtocol() { + String p = protocol == null ? "" : protocol.trim(); + if (StringUtils.isNumeric(p)) { + int protoNumber = Integer.parseInt(p); + switch (protoNumber) { + case 1: + p = NetUtils.ICMP_PROTO; + break; + case 6: + p = NetUtils.TCP_PROTO; + break; + case 17: + p = NetUtils.UDP_PROTO; + break; + default: + throw new InvalidParameterValueException(String.format("Protocol %d not supported", protoNumber)); + + } + } + return p; + } + + public List getSourceCidrList() { + if (sourceCidrList != null) { + return sourceCidrList; + } else { + List oneCidrList = new ArrayList(); + oneCidrList.add(NetUtils.ALL_IP4_CIDRS); + return oneCidrList; + } + } + + public List getDestinationCidrList() { + if (destinationCidrlist != null) { + return destinationCidrlist; + } else { + List oneCidrList = new ArrayList(); + oneCidrList.add(NetUtils.ALL_IP4_CIDRS); + return oneCidrList; + } + } + + public FirewallRule.TrafficType getTrafficType() { + if (trafficType == null) { + return FirewallRule.TrafficType.Ingress; + } + for (FirewallRule.TrafficType type : FirewallRule.TrafficType.values()) { + if (type.toString().equalsIgnoreCase(trafficType)) { + return type; + } + } + throw new InvalidParameterValueException("Invalid traffic type " + trafficType); + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + public Integer getSourcePortStart() { + return publicStartPort; + } + + public Integer getSourcePortEnd() { + if (publicEndPort == null) { + if (publicStartPort != null) { + return publicStartPort; + } + } else { + return publicEndPort; + } + + return null; + } + + public Long getNetworkId() { + return networkId; + } + + @Override + public long getEntityOwnerId() { + Network network = _networkService.getNetwork(networkId); + if (network != null) { + return network.getAccountId(); + } + Account owner = CallContext.current().getCallingAccount(); + return owner.getAccountId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_ROUTING_IPV4_FIREWALL_RULE_CREATE; + } + + @Override + public String getEventDescription() { + return "Creating ipv4 firewall rule for routed network"; + } + + public Integer getIcmpCode() { + if (icmpCode != null) { + return icmpCode; + } else if (getProtocol().equalsIgnoreCase(NetUtils.ICMP_PROTO)) { + return -1; + } + return null; + } + + public Integer getIcmpType() { + if (icmpType != null) { + return icmpType; + } else if (getProtocol().equalsIgnoreCase(NetUtils.ICMP_PROTO)) { + return -1; + + } + return null; + } + + @Override + public void create() { + try { + FirewallRule result = routedIpv4Manager.createRoutingFirewallRule(this); + setEntityId(result.getId()); + setEntityUuid(result.getUuid()); + } catch (NetworkRuleConflictException e) { + logger.trace("Network Rule Conflict: ", e); + throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage(), e); + } + } + + @Override + public void execute() throws ResourceUnavailableException { + boolean success = false; + FirewallRule rule = _firewallService.getFirewallRule(getEntityId()); + try { + CallContext.current().setEventDetails("Rule ID: " + getEntityId()); + success = routedIpv4Manager.applyRoutingFirewallRule(rule.getId()); + + // State is different after the rule is applied, so get new object here + rule = _firewallService.getFirewallRule(getEntityId()); + FirewallResponse ruleResponse = new FirewallResponse(); + if (rule != null) { + ruleResponse = _responseGenerator.createFirewallResponse(rule); + setResponseObject(ruleResponse); + } + ruleResponse.setResponseName(getCommandName()); + } catch (Exception ex) { + logger.error("Got exception when create Routing firewall rules: " + ex); + } finally { + if (!success || rule == null) { + routedIpv4Manager.revokeRoutingFirewallRule(getEntityId()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create Routing firewall rule"); + } + } + } + + @Override + public Long getApiResourceId() { + return getNetworkId(); + } + + @Override + public ApiCommandResourceType getApiResourceType() { + return ApiCommandResourceType.Network; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/DeleteRoutingFirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/DeleteRoutingFirewallRuleCmd.java new file mode 100644 index 00000000000..16696f5f71b --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/DeleteRoutingFirewallRuleCmd.java @@ -0,0 +1,109 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.network.routing; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiCommandResourceType; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.context.CallContext; + +import com.cloud.event.EventTypes; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.rules.FirewallRule; +import com.cloud.user.Account; + +@APICommand(name = "deleteRoutingFirewallRule", + description = "Deletes a routing firewall rule", + since = "4.20.0", + responseObject = SuccessResponse.class, + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class DeleteRoutingFirewallRuleCmd extends BaseAsyncCmd { + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, required = true, description = "the ID of the Routing firewall rule") + private Long id; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + @Override + public String getEventType() { + return EventTypes.EVENT_ROUTING_IPV4_FIREWALL_RULE_DELETE; + } + + @Override + public String getEventDescription() { + return String.format("Deleting ipv4 routing firewall rule ID=%s", id); + } + + @Override + public long getEntityOwnerId() { + FirewallRule rule = _firewallService.getFirewallRule(id); + if (rule != null) { + return rule.getAccountId(); + } + Account caller = CallContext.current().getCallingAccount(); + return caller.getAccountId(); + } + + @Override + public void execute() throws ResourceUnavailableException { + CallContext.current().setEventDetails("Routing firewall rule ID: " + id); + boolean result = routedIpv4Manager.revokeRoutingFirewallRule(id); + + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Routing firewall rule"); + } + } + + @Override + public Long getApiResourceId() { + FirewallRule rule = _firewallService.getFirewallRule(id); + if (rule != null) { + return rule.getNetworkId(); + } + return null; + } + + @Override + public ApiCommandResourceType getApiResourceType() { + return ApiCommandResourceType.Network; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/ListRoutingFirewallRulesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/ListRoutingFirewallRulesCmd.java new file mode 100644 index 00000000000..3fdf3b0f5b4 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/ListRoutingFirewallRulesCmd.java @@ -0,0 +1,115 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.network.routing; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.command.user.firewall.IListFirewallRulesCmd; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; + +import com.cloud.network.rules.FirewallRule; +import com.cloud.utils.Pair; + +@APICommand(name = "listRoutingFirewallRules", + description = "Lists all Routing firewall rules", + since = "4.20.0", + responseObject = FirewallRuleResponse.class, + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class ListRoutingFirewallRulesCmd extends BaseListTaggedResourcesCmd implements IListFirewallRulesCmd { + + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + description = "Lists Routing firewall rule with the specified ID") + private Long id; + + @Parameter(name = ApiConstants.NETWORK_ID, type = CommandType.UUID, entityType = NetworkResponse.class, description = "list Routing firewall rules by network ID") + private Long networkId; + + @Parameter(name = ApiConstants.TRAFFIC_TYPE, type = CommandType.STRING, description = "list Routing firewall rules by traffic type - ingress or egress") + private String trafficType; + + @Parameter(name = ApiConstants.FOR_DISPLAY, type = CommandType.BOOLEAN, description = "list resources by display flag; only ROOT admin is eligible to pass this parameter", authorized = {RoleType.Admin}) + private Boolean display; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + @Override + public Long getNetworkId() { + return networkId; + } + + @Override + public Long getId() { + return id; + } + + @Override + public FirewallRule.TrafficType getTrafficType() { + if (trafficType != null) { + return FirewallRule.TrafficType.valueOf(trafficType); + } + return null; + } + + @Override + public Long getIpAddressId() { + return null; + } + + @Override + public Boolean getDisplay() { + if (display != null) { + return display; + } + return super.getDisplay(); + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() { + Pair, Integer> result = routedIpv4Manager.listRoutingFirewallRules(this); + ListResponse response = new ListResponse<>(); + List ruleResponses = new ArrayList<>(); + + for (FirewallRule rule : result.first()) { + FirewallResponse ruleData = _responseGenerator.createFirewallResponse(rule); + ruleResponses.add(ruleData); + } + response.setResponses(ruleResponses, result.second()); + response.setResponseName(getCommandName()); + setResponseObject(response); + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/UpdateRoutingFirewallRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/UpdateRoutingFirewallRuleCmd.java new file mode 100644 index 00000000000..c6f6034b1ba --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/routing/UpdateRoutingFirewallRuleCmd.java @@ -0,0 +1,125 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.network.routing; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiCommandResourceType; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.context.CallContext; + +import com.cloud.event.EventTypes; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.rules.FirewallRule; +import com.cloud.user.Account; + +@APICommand(name = "updateRoutingFirewallRule", + description = "Updates Routing firewall rule with specified ID", + since = "4.20.0", + responseObject = FirewallRuleResponse.class, + requestHasSensitiveInfo = false, + responseHasSensitiveInfo = false, + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class UpdateRoutingFirewallRuleCmd extends BaseAsyncCustomIdCmd { + + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, required = true, description = "the ID of the Routing firewall rule") + private Long id; + + @Parameter(name = ApiConstants.FOR_DISPLAY, type = CommandType.BOOLEAN, description = "an optional field, whether to the display the Routing firewall rule to the end user or not", + authorized = {RoleType.Admin}) + private Boolean display; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + @Override + public boolean isDisplay() { + if (display != null) { + return display; + } else { + return true; + } + } + + public Long getId() { + return id; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public long getEntityOwnerId() { + FirewallRule rule = _firewallService.getFirewallRule(id); + if (rule != null) { + return rule.getAccountId(); + } + Account caller = CallContext.current().getCallingAccount(); + return caller.getAccountId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_ROUTING_IPV4_FIREWALL_RULE_UPDATE; + } + + @Override + public String getEventDescription() { + return "Updating ipv4 routing firewall rule"; + } + + @Override + public void execute() throws ResourceUnavailableException { + CallContext.current().setEventDetails("Rule Id: " + getId()); + FirewallRule rule = routedIpv4Manager.updateRoutingFirewallRule(this); + FirewallResponse ruleResponse = _responseGenerator.createFirewallResponse(rule); + setResponseObject(ruleResponse); + ruleResponse.setResponseName(getCommandName()); + } + + @Override + public void checkUuid() { + if (this.getCustomId() != null) { + _uuidMgr.checkUuid(this.getCustomId(), FirewallRule.class); + } + } + + @Override + public Long getApiResourceId() { + FirewallRule rule = _firewallService.getFirewallRule(id); + if (rule != null) { + return rule.getNetworkId(); + } + return null; + } + + @Override + public ApiCommandResourceType getApiResourceType() { + return ApiCommandResourceType.Network; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java index 6f32b58b733..f9b9ec59a40 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java @@ -16,28 +16,26 @@ // under the License. package org.apache.cloudstack.api.command.user.offering; -import com.cloud.offering.DiskOffering.State; +import static com.cloud.offering.DiskOffering.State.Active; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.BaseCmd.CommandType; -import org.apache.cloudstack.api.response.DiskOfferingResponse; -import org.apache.cloudstack.api.response.ListResponse; - -import static com.cloud.offering.DiskOffering.State.Active; +import com.cloud.offering.DiskOffering.State; @APICommand(name = "listDiskOfferings", description = "Lists all available disk offerings.", responseObject = DiskOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListDiskOfferingsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListDiskOfferingsCmd.class.getName()); ///////////////////////////////////////////////////// @@ -77,6 +75,13 @@ public class ListDiskOfferingsCmd extends BaseListProjectAndAccountResourcesCmd since = "4.19") private String diskOfferingState; + @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, + type = CommandType.UUID, + entityType = UserVmResponse.class, + description = "The ID of a virtual machine. Pass this in if you want to see the suitable disk offering that can be used to create and add a disk to the virtual machine. Suitability is returned with suitableforvirtualmachine flag in the response", + since = "4.20.0") + private Long virtualMachineId; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -116,13 +121,16 @@ public class ListDiskOfferingsCmd extends BaseListProjectAndAccountResourcesCmd return state; } + public Long getVirtualMachineId() { + return virtualMachineId; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { - ListResponse response = _queryService.searchForDiskOfferings(this); response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java index 246984aaada..1b3f531e370 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java @@ -16,26 +16,25 @@ // under the License. package org.apache.cloudstack.api.command.user.offering; -import com.cloud.offering.ServiceOffering.State; -import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; -import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.commons.lang3.EnumUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import static com.cloud.offering.ServiceOffering.State.Active; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.commons.lang3.EnumUtils; +import org.apache.commons.lang3.StringUtils; -import static com.cloud.offering.ServiceOffering.State.Active; +import com.cloud.offering.ServiceOffering.State; @APICommand(name = "listServiceOfferings", description = "Lists all available service offerings.", responseObject = ServiceOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListServiceOfferingsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName()); ///////////////////////////////////////////////////// @@ -104,6 +103,13 @@ public class ListServiceOfferingsCmd extends BaseListProjectAndAccountResourcesC since = "4.19") private String serviceOfferingState; + @Parameter(name = ApiConstants.TEMPLATE_ID, + type = CommandType.UUID, + entityType = TemplateResponse.class, + description = "The ID of the template that listed offerings must support", + since = "4.20.0") + private Long templateId; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -161,6 +167,10 @@ public class ListServiceOfferingsCmd extends BaseListProjectAndAccountResourcesC return state; } + public Long getTemplateId() { + return templateId; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java index 58cc93ff95d..42e045d4389 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.project; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -36,7 +35,6 @@ import com.cloud.projects.Project; @APICommand(name = "activateProject", description = "Activates a project", responseObject = ProjectResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ActivateProjectCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ActivateProjectCmd.class.getName()); private static final String s_name = "activaterojectresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java index a5742e8d0de..cb93729381a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "createProject", description = "Creates a project", responseObject = ProjectResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateProjectCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateProjectCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java index 85b411b075d..1fd205fdae4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.project; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.projects.Project; @APICommand(name = "deleteProject", description = "Deletes a project", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteProjectCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteProjectCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java index 600fac350de..d1b17eda76b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.project; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteProjectInvitation", description = "Deletes project invitation", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteProjectInvitationCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteProjectInvitationCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/project/ListProjectInvitationsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/project/ListProjectInvitationsCmd.java index b8d2f9b5f1a..210394ec2dd 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/project/ListProjectInvitationsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/project/ListProjectInvitationsCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.project; import org.apache.cloudstack.api.response.UserResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import org.apache.cloudstack.api.response.ProjectResponse; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListProjectInvitationsCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/project/ListProjectsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/project/ListProjectsCmd.java index 39d1c0dfeda..d4679dbe057 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/project/ListProjectsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/project/ListProjectsCmd.java @@ -24,7 +24,6 @@ import java.util.Map; import com.cloud.server.ResourceIcon; import com.cloud.server.ResourceTag; import org.apache.cloudstack.api.response.ResourceIconResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -44,7 +43,6 @@ import com.cloud.exception.InvalidParameterValueException; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListProjectsCmd extends BaseListAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListProjectsCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java index 4937b164aab..a3eee8c80bb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.project; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.projects.Project; @APICommand(name = "suspendProject", description = "Suspends a project", responseObject = ProjectResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class SuspendProjectCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(SuspendProjectCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java index 6520aa63a64..4fabf7da788 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -40,7 +39,6 @@ import com.cloud.projects.ProjectAccount; @APICommand(name = "updateProject", description = "Updates a project", responseObject = ProjectResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateProjectCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateProjectCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java index e783aa64467..0cbd9f702c2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.user.Account; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "updateProjectInvitation", description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateProjectInvitationCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateProjectInvitationCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java index d3eb8bf8b0f..777f437851c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ListRegionsCmd.java @@ -21,7 +21,6 @@ import java.util.List; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import org.apache.cloudstack.region.RegionService; @APICommand(name = "listRegions", description = "Lists Regions", responseObject = RegionResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListRegionsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListRegionsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/AssignToGlobalLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/AssignToGlobalLoadBalancerRuleCmd.java index aedc363e5cc..649b2a7bd9b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/AssignToGlobalLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/AssignToGlobalLoadBalancerRuleCmd.java @@ -25,7 +25,6 @@ import java.util.Map; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -53,7 +52,6 @@ import com.cloud.user.Account; responseHasSensitiveInfo = false) public class AssignToGlobalLoadBalancerRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(AssignToGlobalLoadBalancerRuleCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/CreateGlobalLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/CreateGlobalLoadBalancerRuleCmd.java index 3aaf0607392..ddaadde7852 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/CreateGlobalLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/CreateGlobalLoadBalancerRuleCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.GlobalLoadBalancerResponse; import org.apache.cloudstack.api.response.RegionResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -42,7 +41,6 @@ import com.cloud.region.ha.GlobalLoadBalancingRulesService; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateGlobalLoadBalancerRuleCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateGlobalLoadBalancerRuleCmd.class.getName()); ///////////////////////////////////////////////////// @@ -157,7 +155,7 @@ public class CreateGlobalLoadBalancerRuleCmd extends BaseAsyncCreateCmd { this.setEntityUuid(gslbRule.getUuid()); CallContext.current().setEventDetails("Rule Id: " + getEntityId()); } catch (Exception ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage()); } finally { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/DeleteGlobalLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/DeleteGlobalLoadBalancerRuleCmd.java index 87c4e60a90b..7f3308614cc 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/DeleteGlobalLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/DeleteGlobalLoadBalancerRuleCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.region.ha.gslb; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -41,7 +40,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteGlobalLoadBalancerRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteGlobalLoadBalancerRuleCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/ListGlobalLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/ListGlobalLoadBalancerRuleCmd.java index 7a1bcfc37a7..bf0cf22a2ec 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/ListGlobalLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/ListGlobalLoadBalancerRuleCmd.java @@ -22,7 +22,6 @@ import java.util.List; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.region.ha.GlobalLoadBalancingRulesService; @APICommand(name = "listGlobalLoadBalancerRules", description = "Lists load balancer rules.", responseObject = GlobalLoadBalancerResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListGlobalLoadBalancerRuleCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListGlobalLoadBalancerRuleCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/RemoveFromGlobalLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/RemoveFromGlobalLoadBalancerRuleCmd.java index b9bbfec847f..d4b02139892 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/RemoveFromGlobalLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/RemoveFromGlobalLoadBalancerRuleCmd.java @@ -21,7 +21,6 @@ import java.util.List; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -47,7 +46,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RemoveFromGlobalLoadBalancerRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RemoveFromGlobalLoadBalancerRuleCmd.class.getName()); private static final String s_name = "removefromloadbalancerruleresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/UpdateGlobalLoadBalancerRuleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/UpdateGlobalLoadBalancerRuleCmd.java index c8d307e4084..7996998e5d9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/UpdateGlobalLoadBalancerRuleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/region/ha/gslb/UpdateGlobalLoadBalancerRuleCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.region.ha.gslb; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "updateGlobalLoadBalancerRule", description = "update global load balancer rules.", responseObject = GlobalLoadBalancerResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateGlobalLoadBalancerRuleCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateGlobalLoadBalancerRuleCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java index b513b811e46..b9e43336217 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "getCloudIdentifier", description = "Retrieves a cloud identifier.", responseObject = CloudIdentifierResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class GetCloudIdentifierCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(GetCloudIdentifierCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/resource/ListHypervisorsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/resource/ListHypervisorsCmd.java index a0e750eb19f..556f3b081f0 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/resource/ListHypervisorsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/resource/ListHypervisorsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "listHypervisors", description = "List hypervisors", responseObject = HypervisorResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListHypervisorsCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ListHypervisorsCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmd.java index adf1c93e4d0..71b886ed12b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmd.java @@ -19,22 +19,20 @@ package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; import java.util.List; -import com.cloud.configuration.Resource; -import com.cloud.exception.InvalidParameterValueException; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ResourceLimitResponse; -import org.apache.log4j.Logger; +import com.cloud.configuration.Resource; import com.cloud.configuration.ResourceLimit; +import com.cloud.exception.InvalidParameterValueException; @APICommand(name = "listResourceLimits", description = "Lists resource limits.", responseObject = ResourceLimitResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListResourceLimitsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListResourceLimitsCmd.class.getName()); ///////////////////////////////////////////////////// @@ -74,6 +72,10 @@ public class ListResourceLimitsCmd extends BaseListProjectAndAccountResourcesCmd + "secondary_storage - SecondaryStorage. Total secondary storage space (in GiB) a user can use. ") private String resourceTypeName; + @Parameter(name = ApiConstants.TAG, type = CommandType.STRING, description = "Tag for the resource type", since = "4.20.0") + private String tag; + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -90,6 +92,10 @@ public class ListResourceLimitsCmd extends BaseListProjectAndAccountResourcesCmd return resourceTypeName; } + public String getTag() { + return tag; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -98,7 +104,7 @@ public class ListResourceLimitsCmd extends BaseListProjectAndAccountResourcesCmd public void execute() { List result = _resourceLimitService.searchForLimits(id, _accountService.finalyzeAccountId(this.getAccountName(), this.getDomainId(), this.getProjectId(), false), this.getDomainId(), - getResourceTypeEnum(), this.getStartIndex(), this.getPageSizeVal()); + getResourceTypeEnum(), getTag(), this.getStartIndex(), this.getPageSizeVal()); ListResponse response = new ListResponse(); List limitResponses = new ArrayList(); for (ResourceLimit limit : result) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java index 424087bc71e..49c6ee605c8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java @@ -30,15 +30,16 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ResourceCountResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.configuration.ResourceCount; import com.cloud.user.Account; -@APICommand(name = "updateResourceCount", description = "Recalculate and update resource count for an account or domain.", responseObject = ResourceCountResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) +@APICommand(name = "updateResourceCount", + description = "Recalculate and update resource count for an account or domain. " + + "This also executes some cleanup tasks before calculating resource counts.", + responseObject = ResourceCountResponse.class, + requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateResourceCountCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateResourceCountCmd.class.getName()); ///////////////////////////////////////////////////// @@ -77,6 +78,9 @@ public class UpdateResourceCountCmd extends BaseCmd { @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "Update resource limits for project") private Long projectId; + @Parameter(name = ApiConstants.TAG, type = CommandType.STRING, description = "Tag for the resource type", since = "4.20.0") + private String tag; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -93,6 +97,10 @@ public class UpdateResourceCountCmd extends BaseCmd { return resourceType; } + public String getTag() { + return tag; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -119,7 +127,7 @@ public class UpdateResourceCountCmd extends BaseCmd { @Override public void execute() { List result = - _resourceLimitService.recalculateResourceCount(_accountService.finalyzeAccountId(accountName, domainId, projectId, true), getDomainId(), getResourceType()); + _resourceLimitService.recalculateResourceCount(_accountService.finalyzeAccountId(accountName, domainId, projectId, true), getDomainId(), getResourceType(), getTag()); if ((result != null) && (result.size() > 0)) { ListResponse response = new ListResponse(); @@ -127,7 +135,6 @@ public class UpdateResourceCountCmd extends BaseCmd { for (ResourceCount count : result) { ResourceCountResponse resourceCountResponse = _responseGenerator.createResourceCountResponse(count); - resourceCountResponse.setObjectName("resourcecount"); countResponses.add(resourceCountResponse); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java index 41676ed23ca..3538a389a6e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java @@ -26,14 +26,12 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ResourceLimitResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.configuration.ResourceLimit; @APICommand(name = "updateResourceLimit", description = "Updates resource limits for an account or domain.", responseObject = ResourceLimitResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateResourceLimitCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateResourceLimitCmd.class.getName()); ///////////////////////////////////////////////////// @@ -64,6 +62,7 @@ public class UpdateResourceLimitCmd extends BaseCmd { + "2 - Volume. Number of disk volumes a user can create. " + "3 - Snapshot. Number of snapshots a user can create. " + "4 - Template. Number of templates that a user can register/create. " + + "5 - Project. Number of projects a user can create. " + "6 - Network. Number of guest network a user can create. " + "7 - VPC. Number of VPC a user can create. " + "8 - CPU. Total number of CPU cores a user can use. " @@ -72,6 +71,9 @@ public class UpdateResourceLimitCmd extends BaseCmd { + "11 - SecondaryStorage. Total secondary storage space (in GiB) a user can use. ") private Integer resourceType; + @Parameter(name = ApiConstants.TAG, type = CommandType.STRING, description = "Tag for the resource type", since = "4.20.0") + private String tag; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -84,6 +86,10 @@ public class UpdateResourceLimitCmd extends BaseCmd { return domainId; } + public String getTag() { + return tag; + } + public Integer getResourceType() { return resourceType; } @@ -104,7 +110,7 @@ public class UpdateResourceLimitCmd extends BaseCmd { @Override public void execute() { - ResourceLimit result = _resourceLimitService.updateResourceLimit(_accountService.finalyzeAccountId(accountName, domainId, projectId, true), getDomainId(), resourceType, max); + ResourceLimit result = _resourceLimitService.updateResourceLimit(_accountService.finalyzeAccountId(accountName, domainId, projectId, true), getDomainId(), resourceType, max, getTag()); if (result != null || (result == null && max != null && max.longValue() == -1L)) { ResourceLimitResponse response = _responseGenerator.createResourceLimitResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java index 737bdc8773b..13faafe348c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java @@ -22,7 +22,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -50,7 +49,6 @@ import com.cloud.network.security.SecurityRule; responseHasSensitiveInfo = false) @SuppressWarnings("rawtypes") public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(AuthorizeSecurityGroupEgressCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java index b6918905f29..640870fc3de 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java @@ -22,7 +22,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -50,7 +49,6 @@ import com.cloud.network.security.SecurityRule; responseHasSensitiveInfo = false) @SuppressWarnings("rawtypes") public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(AuthorizeSecurityGroupIngressCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java index 4978aa174fc..673eaaef33d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.securitygroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "createSecurityGroup", responseObject = SecurityGroupResponse.class, description = "Creates a security group", entityType = {SecurityGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateSecurityGroupCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateSecurityGroupCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java index 57d365d5ce1..b2ea90792b8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.securitygroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -39,7 +38,6 @@ import com.cloud.network.security.SecurityGroup; @APICommand(name = "deleteSecurityGroup", description = "Deletes security group", responseObject = SuccessResponse.class, entityType = {SecurityGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteSecurityGroupCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteSecurityGroupCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -124,7 +122,7 @@ public class DeleteSecurityGroupCmd extends BaseCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete security group"); } } catch (ResourceInUseException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/ListSecurityGroupsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/ListSecurityGroupsCmd.java index c4c103cf98e..f93e7b39586 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/ListSecurityGroupsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/ListSecurityGroupsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.securitygroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -32,7 +31,6 @@ import com.cloud.network.security.SecurityGroup; @APICommand(name = "listSecurityGroups", description = "Lists security groups", responseObject = SecurityGroupResponse.class, entityType = {SecurityGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListSecurityGroupsCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListSecurityGroupsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java index f4a0362fce9..bf435406174 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.securitygroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -38,7 +37,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RevokeSecurityGroupEgressCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupEgressCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java index c5f88c9673f..c426647fe36 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.securitygroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -38,7 +37,6 @@ import com.cloud.user.Account; @APICommand(name = "revokeSecurityGroupIngress", responseObject = SuccessResponse.class, description = "Deletes a particular ingress rule from this security group", entityType = {SecurityGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupIngressCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/UpdateSecurityGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/UpdateSecurityGroupCmd.java index 9b3000b1bf7..801fb6ac5e5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/UpdateSecurityGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/securitygroup/UpdateSecurityGroupCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.securitygroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -37,7 +36,6 @@ import com.cloud.user.Account; since = "4.14.0.0", authorized = {RoleType.Admin}) public class UpdateSecurityGroupCmd extends BaseCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateSecurityGroupCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ArchiveSnapshotCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ArchiveSnapshotCmd.java index 78aa208ac1f..f72de2278cc 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ArchiveSnapshotCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ArchiveSnapshotCmd.java @@ -35,13 +35,11 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SnapshotResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; @APICommand(name = "archiveSnapshot", description = "Archives (moves) a snapshot on primary storage to secondary storage", responseObject = SnapshotResponse.class, entityType = {Snapshot.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ArchiveSnapshotCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ArchiveSnapshotCmd.class.getName()); private static final String s_name = "createsnapshotresponse"; @ACL(accessType = SecurityChecker.AccessType.OperateEntry) diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CopySnapshotCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CopySnapshotCmd.java index f6d16c3eb49..07973fcbfca 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CopySnapshotCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CopySnapshotCmd.java @@ -34,7 +34,6 @@ import org.apache.cloudstack.api.response.SnapshotResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.event.EventTypes; @@ -43,13 +42,15 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.StorageUnavailableException; import com.cloud.storage.Snapshot; import com.cloud.user.Account; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; @APICommand(name = "copySnapshot", description = "Copies a snapshot from one zone to another.", responseObject = SnapshotResponse.class, responseView = ResponseObject.ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.19.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class CopySnapshotCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(CopySnapshotCmd.class.getName()); + public static final Logger logger = LogManager.getLogger(CopySnapshotCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -170,10 +171,10 @@ public class CopySnapshotCmd extends BaseAsyncCmd implements UserCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to copy snapshot"); } } catch (StorageUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ResourceAllocationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage()); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java index eed3aa49fa5..3289ac2fe10 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java @@ -35,7 +35,6 @@ import org.apache.cloudstack.api.response.SnapshotResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.commons.collections.MapUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -50,7 +49,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @APICommand(name = "createSnapshot", description = "Creates an instant snapshot of a volume.", responseObject = SnapshotResponse.class, entityType = {Snapshot.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateSnapshotCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateSnapshotCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// @@ -240,7 +238,7 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { } String errorMessage = "Failed to create snapshot due to an internal error creating snapshot for volume " + getVolumeUuid(); - s_logger.error(errorMessage, e); + logger.error(errorMessage, e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMessage); } } @@ -257,7 +255,7 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { } catch (IllegalArgumentException e) { String errMesg = "Invalid locationType " + locationType + "Specified for volume " + getVolumeId() + " Valid values are: primary,secondary "; - s_logger.warn(errMesg); + logger.warn(errMesg); throw new CloudRuntimeException(errMesg); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotFromVMSnapshotCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotFromVMSnapshotCmd.java index d33a3ba224c..0203558c916 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotFromVMSnapshotCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotFromVMSnapshotCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.response.SnapshotResponse; import org.apache.cloudstack.api.response.VMSnapshotResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -43,7 +42,6 @@ import com.cloud.vm.snapshot.VMSnapshot; @APICommand(name = "createSnapshotFromVMSnapshot", description = "Creates an instant snapshot of a volume from existing vm snapshot.", responseObject = SnapshotResponse.class, entityType = {Snapshot.class}, since = "4.10.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateSnapshotFromVMSnapshotCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateSnapshotFromVMSnapshotCmd.class.getName()); // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// @@ -126,10 +124,10 @@ public class CreateSnapshotFromVMSnapshotCmd extends BaseAsyncCreateCmd { if (account.getType() == Account.Type.PROJECT) { Project project = _projectService.findByProjectAccountId(vmsnapshot.getAccountId()); if (project == null) { - throw new InvalidParameterValueException("Unable to find project by account id=" + account.getUuid()); + throw new InvalidParameterValueException(String.format("Unable to find project by account %s", account)); } if (project.getState() != Project.State.Active) { - throw new PermissionDeniedException("Can't add resources to the project id=" + project.getUuid() + " in state=" + project.getState() + " as it's no longer active"); + throw new PermissionDeniedException(String.format("Can't add resources to the project %s in state=%s as it's no longer active", project, project.getState())); } } else if (account.getState() == Account.State.DISABLED) { throw new PermissionDeniedException("The owner of template is disabled: " + account); @@ -166,8 +164,9 @@ public class CreateSnapshotFromVMSnapshotCmd extends BaseAsyncCreateCmd { @Override public void execute() { - s_logger.info("CreateSnapshotFromVMSnapshotCmd with vm snapshot id:" + getVMSnapshotId() + " and snapshot id:" + getEntityId() + " starts:" + System.currentTimeMillis()); - CallContext.current().setEventDetails("Vm Snapshot Id: "+ this._uuidMgr.getUuid(VMSnapshot.class, getVMSnapshotId())); + VMSnapshot vmSnapshot = _vmSnapshotService.getVMSnapshotById(getVMSnapshotId()); + logger.info("CreateSnapshotFromVMSnapshotCmd with vm snapshot {} with id {} and snapshot [id: {}, uuid: {}]", vmSnapshot, getVMSnapshotId(), getEntityId(), getEntityUuid()); + CallContext.current().setEventDetails("Vm Snapshot Id: " + vmSnapshot.getUuid()); Snapshot snapshot = null; try { snapshot = _snapshotService.backupSnapshotFromVmSnapshot(getEntityId(), getVmId(), getVolumeId(), getVMSnapshotId()); @@ -176,19 +175,19 @@ public class CreateSnapshotFromVMSnapshotCmd extends BaseAsyncCreateCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create snapshot due to an internal error creating snapshot from vm snapshot " + getVMSnapshotId()); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to create snapshot due to an internal error creating snapshot from vm snapshot %s", vmSnapshot)); } } catch (InvalidParameterValueException ex) { throw ex; } catch (Exception e) { - s_logger.debug("Failed to create snapshot", e); - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create snapshot due to an internal error creating snapshot from vm snapshot " + getVMSnapshotId()); + logger.debug("Failed to create snapshot", e); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to create snapshot due to an internal error creating snapshot from vm snapshot %s", vmSnapshot)); } finally { if (snapshot == null) { try { _snapshotService.deleteSnapshot(getEntityId(), null); } catch (Exception e) { - s_logger.debug("Failed to clean failed snapshot" + getEntityId()); + logger.debug("Failed to clean failed snapshot {} with id {}", () -> _entityMgr.findById(Snapshot.class, getEntityId()), this::getEntityId); } } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java index 00bfb9e7e2c..e30b897db2e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java @@ -33,7 +33,6 @@ import org.apache.cloudstack.api.response.SnapshotPolicyResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.commons.collections.MapUtils; -import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; @@ -45,7 +44,6 @@ import com.cloud.user.Account; @APICommand(name = "createSnapshotPolicy", description = "Creates a snapshot policy for the account.", responseObject = SnapshotPolicyResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateSnapshotPolicyCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateSnapshotPolicyCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java index 6d71b1363b4..a0a8cfac9bd 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.snapshot; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteSnapshot", description = "Deletes a snapshot of a disk volume.", responseObject = SuccessResponse.class, entityType = {Snapshot.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteSnapshotCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteSnapshotCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java index 1a72b22f06c..6f4b60dc8b2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.snapshot; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteSnapshotPolicies", description = "Deletes snapshot policies for the account.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteSnapshotPoliciesCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteSnapshotPoliciesCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ExtractSnapshotCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ExtractSnapshotCmd.java new file mode 100644 index 00000000000..3f0f82ea4e3 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ExtractSnapshotCmd.java @@ -0,0 +1,115 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.snapshot; + +import com.cloud.event.EventTypes; +import com.cloud.storage.Snapshot; +import com.cloud.user.Account; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.api.ACL; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiCommandResourceType; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ExtractResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.context.CallContext; + +@APICommand(name = "extractSnapshot", description = "Returns a download URL for extracting a snapshot. It must be in the Backed Up state.", since = "4.20.0", + responseObject = ExtractResponse.class, entityType = {Snapshot.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) +public class ExtractSnapshotCmd extends BaseAsyncCmd { + + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @ACL(accessType = AccessType.OperateEntry) + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SnapshotResponse.class, required=true, since="4.20.0", description="the ID of the snapshot") + private Long id; + + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = true, since="4.20.0", + description = "the ID of the zone where the snapshot is located") + private Long zoneId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getZoneId() { + return zoneId; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public ApiCommandResourceType getApiResourceType() { + return ApiCommandResourceType.Snapshot; + } + + @Override + public Long getApiResourceId() { + return getId(); + } + + /** + * @return ID of the snapshot to extract, if any. Otherwise returns the ACCOUNT_ID_SYSTEM, so ERROR events will be traceable. + */ + @Override + public long getEntityOwnerId() { + Snapshot snapshot = _entityMgr.findById(Snapshot.class, getId()); + if (snapshot != null) { + return snapshot.getAccountId(); + } + + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_SNAPSHOT_EXTRACT; + } + + @Override + public String getEventDescription() { + return "Snapshot extraction job"; + } + + @Override + public void execute() { + CallContext.current().setEventDetails("Snapshot ID: " + this._uuidMgr.getUuid(Snapshot.class, getId())); + String uploadUrl = _snapshotService.extractSnapshot(this); + logger.info("Extract URL [{}] of snapshot [{}].", uploadUrl, id); + if (uploadUrl != null) { + ExtractResponse response = _responseGenerator.createSnapshotExtractResponse(id, zoneId, getEntityOwnerId(), uploadUrl); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract snapshot"); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java index e30ee75dee7..126a4080e6d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.List; import org.apache.cloudstack.acl.RoleType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -36,7 +35,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listSnapshotPolicies", description = "Lists snapshot policies.", responseObject = SnapshotPolicyResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListSnapshotPoliciesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListSnapshotPoliciesCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotsCmd.java index cf665127a17..826c54c2e05 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotsCmd.java @@ -28,14 +28,12 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.SnapshotResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; import com.cloud.storage.Snapshot; @APICommand(name = "listSnapshots", description = "Lists all available snapshots for the account.", responseObject = SnapshotResponse.class, entityType = { Snapshot.class }, responseView = ResponseObject.ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListSnapshotsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/RevertSnapshotCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/RevertSnapshotCmd.java index e65a03812d6..fe3b4da0160 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/RevertSnapshotCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/RevertSnapshotCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SnapshotResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.storage.Snapshot; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "revertSnapshot", description = "This is supposed to revert a volume snapshot. This command is only supported with KVM so far", responseObject = SnapshotResponse.class, entityType = {Snapshot.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RevertSnapshotCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RevertSnapshotCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/UpdateSnapshotPolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/UpdateSnapshotPolicyCmd.java index 0bedbe66199..e7feb11f4af 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/UpdateSnapshotPolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/UpdateSnapshotPolicyCmd.java @@ -33,13 +33,11 @@ import org.apache.cloudstack.api.ResponseObject; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SnapshotPolicyResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; @APICommand(name = "updateSnapshotPolicy", description = "Updates the snapshot policy.", responseObject = SnapshotPolicyResponse.class, responseView = ResponseObject.ResponseView.Restricted, entityType = {Volume.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateSnapshotPolicyCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateSnapshotPolicyCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/CreateSSHKeyPairCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/CreateSSHKeyPairCmd.java index 521148b596d..5212779e965 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/CreateSSHKeyPairCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/CreateSSHKeyPairCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.ssh; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,7 +31,6 @@ import com.cloud.user.SSHKeyPair; @APICommand(name = "createSSHKeyPair", description = "Create a new keypair and returns the private key", responseObject = CreateSSHKeyPairResponse.class, entityType = {SSHKeyPair.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class CreateSSHKeyPairCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateSSHKeyPairCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/DeleteSSHKeyPairCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/DeleteSSHKeyPairCmd.java index 39c65c181c5..364ca77ae1f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/DeleteSSHKeyPairCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/DeleteSSHKeyPairCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.ssh; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.SSHKeyPair; @APICommand(name = "deleteSSHKeyPair", description = "Deletes a keypair by name", responseObject = SuccessResponse.class, entityType = {SSHKeyPair.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteSSHKeyPairCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteSSHKeyPairCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/ListSSHKeyPairsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/ListSSHKeyPairsCmd.java index 71fbb66a337..6bf8dca864b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/ListSSHKeyPairsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/ListSSHKeyPairsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.ssh; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listSSHKeyPairs", description = "List registered keypairs", responseObject = SSHKeyPairResponse.class, entityType = {SSHKeyPair.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListSSHKeyPairsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListSSHKeyPairsCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/RegisterSSHKeyPairCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/RegisterSSHKeyPairCmd.java index 8bacfde7f73..6a0c0541bb4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/RegisterSSHKeyPairCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/ssh/RegisterSSHKeyPairCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.ssh; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -32,7 +31,6 @@ import com.cloud.user.SSHKeyPair; @APICommand(name = "registerSSHKeyPair", description = "Register a public key in a keypair under a certain name", responseObject = SSHKeyPairResponse.class, entityType = {SSHKeyPair.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RegisterSSHKeyPairCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(RegisterSSHKeyPairCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ChangeSharedFSDiskOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ChangeSharedFSDiskOfferingCmd.java new file mode 100644 index 00000000000..b078ce4aae9 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ChangeSharedFSDiskOfferingCmd.java @@ -0,0 +1,145 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +import com.cloud.event.EventTypes; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.user.Account; + +@APICommand(name = "changeSharedFileSystemDiskOffering", + responseObject= SharedFSResponse.class, + description = "Change Disk offering of a Shared FileSystem", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class ChangeSharedFSDiskOfferingCmd extends BaseAsyncCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + required = true, + entityType = SharedFSResponse.class, + description = "the ID of the shared filesystem") + private Long id; + + @Parameter(name = ApiConstants.DISK_OFFERING_ID, + type = CommandType.UUID, + entityType = DiskOfferingResponse.class, + description = "the disk offering to use for the underlying storage") + private Long diskOfferingId; + + @Parameter(name = ApiConstants.SIZE, + type = CommandType.LONG, + description = "the size of the shared filesystem in GiB") + private Long size; + + @Parameter(name = ApiConstants.MIN_IOPS, + type = CommandType.LONG, + description = "min iops") + private Long minIops; + + @Parameter(name = ApiConstants.MAX_IOPS, + type = CommandType.LONG, + description = "max iops") + private Long maxIops; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getSize() { + return size; + } + + public Long getDiskOfferingId() { + return diskOfferingId; + } + + public Long getMinIops() { + return minIops; + } + + public Long getMaxIops() { + return maxIops; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getEventType() { + return EventTypes.EVENT_SHAREDFS_CHANGE_DISK_OFFERING; + } + + @Override + public String getEventDescription() { + return "Changing disk offering for the Shared FileSystem " + id; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + @Override + public void execute() throws ResourceAllocationException { + SharedFS sharedFS = sharedFSService.changeSharedFSDiskOffering(this); + if (sharedFS != null) { + ResponseObject.ResponseView respView = getResponseView(); + Account caller = CallContext.current().getCallingAccount(); + if (_accountService.isRootAdmin(caller.getId())) { + respView = ResponseObject.ResponseView.Full; + } + SharedFSResponse response = _responseGenerator.createSharedFSResponse(respView, sharedFS); + response.setObjectName(SharedFS.class.getSimpleName().toLowerCase()); + response.setResponseName(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to change disk offering for the Shared FileSystem"); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ChangeSharedFSServiceOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ChangeSharedFSServiceOfferingCmd.java new file mode 100644 index 00000000000..70fb543d64c --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ChangeSharedFSServiceOfferingCmd.java @@ -0,0 +1,147 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ManagementServerException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.exception.VirtualMachineMigrationException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "changeSharedFileSystemServiceOffering", + responseObject= SharedFSResponse.class, + description = "Change Service offering of a Shared FileSystem", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class ChangeSharedFSServiceOfferingCmd extends BaseAsyncCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + required = true, + entityType = SharedFSResponse.class, + description = "the ID of the shared filesystem") + private Long id; + + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, + type = CommandType.UUID, + entityType = ServiceOfferingResponse.class, + required = true, + description = "the offering to use for the shared filesystem instance") + private Long serviceOfferingId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getServiceOfferingId() { + return serviceOfferingId; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getEventType() { + return EventTypes.EVENT_SHAREDFS_CHANGE_SERVICE_OFFERING; + } + + @Override + public String getEventDescription() { + return "Changing service offering for the Shared FileSystem " + id; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + private String getExceptionMsg(Exception ex) { + return "Shared FileSystem restart failed with exception" + ex.getMessage(); + } + + @Override + public void execute() { + SharedFS sharedFS; + try { + sharedFS = sharedFSService.changeSharedFSServiceOffering(this); + } catch (ResourceUnavailableException ex) { + logger.warn("Shared FileSystem change service offering exception: ", ex); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, getExceptionMsg(ex)); + } catch (InsufficientCapacityException ex) { + logger.warn("Shared FileSystem change service offering exception: ", ex); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, getExceptionMsg(ex)); + } catch (OperationTimedoutException ex) { + logger.warn("Shared FileSystem change service offering exception: ", ex); + throw new CloudRuntimeException("Shared FileSystem change service offering timed out due to " + ex.getMessage()); + } catch (ManagementServerException ex) { + logger.warn("Shared FileSystem change service offering exception: ", ex); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } catch (VirtualMachineMigrationException ex) { + logger.warn("Shared FileSystem change service offering exception: ", ex); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); + } + + if (sharedFS != null) { + ResponseObject.ResponseView respView = getResponseView(); + Account caller = CallContext.current().getCallingAccount(); + if (_accountService.isRootAdmin(caller.getId())) { + respView = ResponseObject.ResponseView.Full; + } + SharedFSResponse response = _responseGenerator.createSharedFSResponse(respView, sharedFS); + response.setObjectName(SharedFS.class.getSimpleName().toLowerCase()); + response.setResponseName(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to change the service offering for the Shared FileSystem"); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/CreateSharedFSCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/CreateSharedFSCmd.java new file mode 100644 index 00000000000..ddaa31612a8 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/CreateSharedFSCmd.java @@ -0,0 +1,304 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import javax.inject.Inject; + +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiCommandResourceType; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSProvider; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +@APICommand(name = "createSharedFileSystem", + responseObject= SharedFSResponse.class, + description = "Create a new Shared File System of specified size and disk offering, attached to the given network", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class CreateSharedFSCmd extends BaseAsyncCreateCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.NAME, + type = CommandType.STRING, + required = true, + description = "the name of the shared filesystem.") + private String name; + + @Parameter(name = ApiConstants.ACCOUNT, + type = BaseCmd.CommandType.STRING, + description = "the account associated with the shared filesystem. Must be used with the domainId parameter.") + private String accountName; + + @Parameter(name = ApiConstants.DOMAIN_ID, + type = CommandType.UUID, + entityType = DomainResponse.class, + description = "the domain ID associated with the shared filesystem. If used with the account parameter" + + " returns the shared filesystem associated with the account for the specified domain." + + "If account is NOT provided then the shared filesystem will be assigned to the caller account and domain.") + private Long domainId; + + @Parameter(name = ApiConstants.PROJECT_ID, + type = CommandType.UUID, + entityType = ProjectResponse.class, + description = "the project associated with the shared filesystem. Mutually exclusive with account parameter") + private Long projectId; + + @Parameter(name = ApiConstants.DESCRIPTION, + type = CommandType.STRING, + description = "the description for the shared filesystem.") + private String description; + + @Parameter(name = ApiConstants.SIZE, + type = CommandType.LONG, + description = "the size of the shared filesystem in GiB") + private Long size; + + @Parameter(name = ApiConstants.ZONE_ID, + type = CommandType.UUID, + required = true, + entityType = ZoneResponse.class, + description = "the zone id.") + private Long zoneId; + + @Parameter(name = ApiConstants.DISK_OFFERING_ID, + type = CommandType.UUID, + required = true, + entityType = DiskOfferingResponse.class, + description = "the disk offering to use for the underlying storage. This will define the size and other specifications like encryption and qos for the shared filesystem.") + private Long diskOfferingId; + + @Parameter(name = ApiConstants.MIN_IOPS, + type = CommandType.LONG, + description = "min iops") + private Long minIops; + + @Parameter(name = ApiConstants.MAX_IOPS, + type = CommandType.LONG, + description = "max iops") + private Long maxIops; + + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, + type = CommandType.UUID, + required = true, + entityType = ServiceOfferingResponse.class, + description = "the service offering to use for the shared filesystem instance hosting the data. The offering should be HA enabled and the cpu count and memory size should be greater than equal to sharedfsvm.min.cpu.count and sharedfsvm.min.ram.size respectively") + private Long serviceOfferingId; + + @Parameter(name = ApiConstants.FILESYSTEM, + type = CommandType.STRING, + required = true, + description = "the filesystem format (XFS / EXT4) which will be installed on the shared filesystem.") + private String fsFormat; + + @Parameter(name = ApiConstants.PROVIDER, + type = CommandType.STRING, + description = "the provider to be used for the shared filesystem. The list of providers can be fetched by using the listSharedFileSystemProviders API.") + private String sharedFSProviderName; + + @Parameter(name = ApiConstants.NETWORK_ID, + type = CommandType.UUID, + required = true, + entityType = NetworkResponse.class, + description = "network to attach the shared filesystem to") + private Long networkId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public String getName() { + return name; + } + + + public Long getProjectId() { + return projectId; + } + + public Long getDomainId() { + return domainId; + } + + public String getAccountName() { + return accountName; + } + public String getDescription() { + return description; + } + + public Long getSize() { + return size; + } + + public Long getZoneId() { + return zoneId; + } + + public Long getDiskOfferingId() { + return diskOfferingId; + } + + public Long getServiceOfferingId() { + return serviceOfferingId; + } + + public Long getMaxIops() { + return maxIops; + } + + public Long getMinIops() { + return minIops; + } + + public String getFsFormat() { + return fsFormat; + } + + public Long getNetworkId() { + return networkId; + } + + public String getSharedFSProviderName() { + if (sharedFSProviderName != null) { + return sharedFSProviderName; + } else { + return SharedFSProvider.SharedFSProviderType.SHAREDFSVM.toString(); + } + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public ApiCommandResourceType getApiResourceType() { + return ApiCommandResourceType.SharedFS; + } + + @Override + public Long getApiResourceId() { + return this.getEntityId(); + } + @Override + public long getEntityOwnerId() { + Long accountId = _accountService.finalyzeAccountId(accountName, domainId, projectId, true); + if (accountId == null) { + return CallContext.current().getCallingAccount().getId(); + } + return accountId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_SHAREDFS_CREATE; + } + + @Override + public String getEventDescription() { + return "Creating shared filesystem " + name; + } + + private String getCreateExceptionMsg(Exception ex) { + return "Shared FileSystem create failed with exception" + ex.getMessage(); + } + + private String getStartExceptionMsg(Exception ex) { + return "Shared FileSystem start failed with exception: " + ex.getMessage(); + } + + public void create() { + SharedFS sharedFS; + sharedFS = sharedFSService.allocSharedFS(this); + if (sharedFS != null) { + setEntityId(sharedFS.getId()); + setEntityUuid(sharedFS.getUuid()); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create Shared FileSystem"); + } + } + + @Override + public void execute() { + SharedFS sharedFS; + try { + sharedFS = sharedFSService.deploySharedFS(this); + } catch (ResourceUnavailableException ex) { + logger.warn("Shared FileSystem start exception: ", ex); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, getStartExceptionMsg(ex)); + } catch (ConcurrentOperationException ex) { + logger.warn("Shared FileSystem start exception: ", ex); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, getStartExceptionMsg(ex)); + } catch (InsufficientCapacityException ex) { + logger.warn("Shared FileSystem start exception: ", ex); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, getStartExceptionMsg(ex)); + } catch (ResourceAllocationException ex) { + logger.warn("Shared FileSystem start exception: ", ex); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + } catch (OperationTimedoutException ex) { + throw new CloudRuntimeException("Shared FileSystem start timed out due to " + ex.getMessage()); + } + + if (sharedFS != null) { + ResponseObject.ResponseView respView = getResponseView(); + Account caller = CallContext.current().getCallingAccount(); + if (_accountService.isRootAdmin(caller.getId())) { + respView = ResponseObject.ResponseView.Full; + } + SharedFSResponse response = _responseGenerator.createSharedFSResponse(respView, sharedFS); + response.setObjectName(SharedFS.class.getSimpleName().toLowerCase()); + response.setResponseName(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to start Shared FileSystem"); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/DestroySharedFSCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/DestroySharedFSCmd.java new file mode 100644 index 00000000000..09fae53f128 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/DestroySharedFSCmd.java @@ -0,0 +1,116 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +import javax.inject.Inject; + +import com.cloud.event.EventTypes; + +@APICommand(name = "destroySharedFileSystem", + responseObject= SuccessResponse.class, + description = "Destroy a Shared FileSystem by id", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class DestroySharedFSCmd extends BaseAsyncCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + entityType = SharedFSResponse.class, + description = "the ID of the shared filesystem to delete") + private Long id; + + @Parameter(name = ApiConstants.EXPUNGE, + type = CommandType.BOOLEAN, + description = "If true is passed, the shared filesystem is expunged immediately. False by default.") + private Boolean expunge; + + @Parameter(name = ApiConstants.FORCED, + type = CommandType.BOOLEAN, + description = "If true is passed, the shared filesystem can be destroyed without stopping it first.") + private Boolean forced; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public boolean isExpunge() { + return (expunge != null) ? expunge : false; + } + + public boolean isForced() { + return (forced != null) ? forced : false; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getEventType() { + return EventTypes.EVENT_SHAREDFS_DESTROY; + } + + @Override + public String getEventDescription() { + return "Destroying Shared FileSystem " + id; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + @Override + public void execute() { + Boolean result = sharedFSService.destroySharedFS(this); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to destroy Shared FileSystem"); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ExpungeSharedFSCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ExpungeSharedFSCmd.java new file mode 100644 index 00000000000..39b99218b66 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ExpungeSharedFSCmd.java @@ -0,0 +1,96 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +import com.cloud.event.EventTypes; + +@APICommand(name = "expungeSharedFileSystem", + responseObject= SuccessResponse.class, + description = "Expunge a Shared FileSystem by id", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class ExpungeSharedFSCmd extends BaseAsyncCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = SharedFSResponse.class, description = "the ID of the shared filesystem to expunge") + private Long id; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getEventType() { + return EventTypes.EVENT_SHAREDFS_EXPUNGE; + } + + @Override + public String getEventDescription() { + return "Expunging Shared FileSystem " + id; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + @Override + public void execute() { + try { + sharedFSService.deleteSharedFS(id); + } catch (Exception ex) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to expunge Shared FileSystem"); + } finally { + SuccessResponse response = new SuccessResponse(getCommandName()); + setResponseObject(response); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ListSharedFSCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ListSharedFSCmd.java new file mode 100644 index 00000000000..c52c691ac0b --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ListSharedFSCmd.java @@ -0,0 +1,114 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListRetrieveOnlyResourceCountCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +import javax.inject.Inject; + +@APICommand(name = "listSharedFileSystems", + responseObject= SharedFSResponse.class, + description = "List Shared FileSystems", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class ListSharedFSCmd extends BaseListRetrieveOnlyResourceCountCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = SharedFSResponse.class, description = "the ID of the shared filesystem") + private Long id; + + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the name of the shared filesystem") + private String name; + + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, description = "the ID of the availability zone") + private Long zoneId; + + @Parameter(name = ApiConstants.NETWORK_ID, type = CommandType.UUID, entityType = NetworkResponse.class, description = "the ID of the network") + private Long networkId; + + @Parameter(name = ApiConstants.DISK_OFFERING_ID, type = CommandType.UUID, entityType = DiskOfferingResponse.class, description = "the disk offering of the shared filesystem") + private Long diskOfferingId; + + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, description = "the service offering of the shared filesystem") + private Long serviceOfferingId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public Long getZoneId() { + return zoneId; + } + + public Long getNetworkId() { + return networkId; + } + + public Long getDiskOfferingId() { + return diskOfferingId; + } + + public Long getServiceOfferingId() { + return serviceOfferingId; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + public long getEntityOwnerId() { + return 0; + } + + @Override + public void execute() { + ListResponse response = sharedFSService.searchForSharedFS(getResponseView(), this); + response.setResponseName(getCommandName()); + setResponseObject(response); + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ListSharedFSProvidersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ListSharedFSProvidersCmd.java new file mode 100644 index 00000000000..940e07225cf --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/ListSharedFSProvidersCmd.java @@ -0,0 +1,60 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.response.SharedFSProviderResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.storage.sharedfs.SharedFSProvider; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +@APICommand(name = "listSharedFileSystemProviders", + responseObject = SharedFSProviderResponse.class, + description = "Lists all available shared filesystem providers.", + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class ListSharedFSProvidersCmd extends BaseListCmd { + + @Inject + public SharedFSService sharedFSService; + + @Override + public void execute() { + List sharedFSProviders = sharedFSService.getSharedFSProviders(); + final ListResponse response = new ListResponse<>(); + final List responses = new ArrayList<>(); + + for (SharedFSProvider sharedFSProvider : sharedFSProviders) { + SharedFSProviderResponse sharedFSProviderResponse = new SharedFSProviderResponse(); + sharedFSProviderResponse.setName(sharedFSProvider.getName()); + sharedFSProviderResponse.setObjectName("sharedfilesystemprovider"); + responses.add(sharedFSProviderResponse); + } + response.setResponses(responses, responses.size()); + response.setResponseName(this.getCommandName()); + setResponseObject(response); + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/RecoverSharedFSCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/RecoverSharedFSCmd.java new file mode 100644 index 00000000000..6e5bbaa4d8a --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/RecoverSharedFSCmd.java @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +@APICommand(name = "recoverSharedFileSystem", + responseObject= SuccessResponse.class, + description = "Recover a Shared FileSystem by id", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class RecoverSharedFSCmd extends BaseCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = SharedFSResponse.class, description = "the ID of the shared filesystem to recover") + private Long id; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + @Override + public void execute() { + SharedFS sharedFS = sharedFSService.recoverSharedFS(id); + if (sharedFS != null) { + SuccessResponse response = new SuccessResponse(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to recover Shared FileSystem"); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/RestartSharedFSCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/RestartSharedFSCmd.java new file mode 100644 index 00000000000..576c472b6eb --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/RestartSharedFSCmd.java @@ -0,0 +1,145 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "restartSharedFileSystem", + responseObject= SuccessResponse.class, + description = "Restart a Shared FileSystem", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class RestartSharedFSCmd extends BaseAsyncCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + required = true, + entityType = SharedFSResponse.class, + description = "the ID of the shared filesystem") + private Long id; + + @Parameter(name = ApiConstants.CLEANUP, + type = CommandType.BOOLEAN, + description = "is cleanup required") + private boolean cleanup; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Boolean getCleanup() { + return cleanup; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getEventType() { + return EventTypes.EVENT_SHAREDFS_RESTART; + } + + @Override + public String getEventDescription() { + return "Restarting Shared FileSystem " + id; + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + private String getRestartExceptionMsg(Exception ex) { + return "Shared FileSystem restart failed with exception" + ex.getMessage(); + } + + @Override + public void execute() { + SharedFS sharedFS; + try { + sharedFS = sharedFSService.restartSharedFS(this.getId(), this.getCleanup()); + } catch (ResourceUnavailableException ex) { + logger.warn("Shared FileSystem restart exception: ", ex); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, getRestartExceptionMsg(ex)); + } catch (ConcurrentOperationException ex) { + logger.warn("Shared FileSystem restart exception: ", ex); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, getRestartExceptionMsg(ex)); + } catch (InsufficientCapacityException ex) { + logger.warn("Shared FileSystem restart exception: ", ex); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, getRestartExceptionMsg(ex)); + } catch (ResourceAllocationException ex) { + logger.warn("Shared FileSystem restart exception: ", ex); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + } catch (OperationTimedoutException ex) { + logger.warn("Shared FileSystem restart exception: ", ex); + throw new CloudRuntimeException("Shared FileSystem start timed out due to " + ex.getMessage()); + } + + if (sharedFS != null) { + ResponseObject.ResponseView respView = getResponseView(); + Account caller = CallContext.current().getCallingAccount(); + if (_accountService.isRootAdmin(caller.getId())) { + respView = ResponseObject.ResponseView.Full; + } + SharedFSResponse response = _responseGenerator.createSharedFSResponse(respView, sharedFS); + response.setObjectName(SharedFS.class.getSimpleName().toLowerCase()); + response.setResponseName(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to restart Shared FileSystem"); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/StartSharedFSCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/StartSharedFSCmd.java new file mode 100644 index 00000000000..bd384aceef7 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/StartSharedFSCmd.java @@ -0,0 +1,135 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "startSharedFileSystem", + responseObject= SharedFSResponse.class, + description = "Start a Shared FileSystem", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class StartSharedFSCmd extends BaseAsyncCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + required = true, + entityType = SharedFSResponse.class, + description = "the ID of the shared filesystem") + private Long id; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + @Override + public String getEventDescription() { + return "Starting Shared FileSystem " + id; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_SHAREDFS_START; + } + + private String getStartExceptionMsg(Exception ex) { + return "Shared FileSystem start failed with exception: " + ex.getMessage(); + } + + @Override + public void execute() { + SharedFS sharedFS; + try { + sharedFS = sharedFSService.startSharedFS(this.getId()); + } catch (ResourceUnavailableException ex) { + logger.warn("Shared FileSystem start exception: ", ex); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, getStartExceptionMsg(ex)); + } catch (ConcurrentOperationException ex) { + logger.warn("Shared FileSystem start exception: ", ex); + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, getStartExceptionMsg(ex)); + } catch (InsufficientCapacityException ex) { + logger.warn("Shared FileSystem start exception: ", ex); + throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, getStartExceptionMsg(ex)); + } catch (ResourceAllocationException ex) { + logger.warn("Shared FileSystem start exception: ", ex); + throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); + } catch (OperationTimedoutException ex) { + logger.warn("Shared FileSystem start exception: ", ex); + throw new CloudRuntimeException("Shared FileSystem start timed out due to " + ex.getMessage()); + } + + if (sharedFS != null) { + ResponseObject.ResponseView respView = getResponseView(); + Account caller = CallContext.current().getCallingAccount(); + if (_accountService.isRootAdmin(caller.getId())) { + respView = ResponseObject.ResponseView.Full; + } + SharedFSResponse response = _responseGenerator.createSharedFSResponse(respView, sharedFS); + response.setObjectName(SharedFS.class.getSimpleName().toLowerCase()); + response.setResponseName(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to start Shared FileSystem"); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/StopSharedFSCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/StopSharedFSCmd.java new file mode 100644 index 00000000000..d6e0737144a --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/StopSharedFSCmd.java @@ -0,0 +1,115 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import javax.inject.Inject; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +import com.cloud.event.EventTypes; +import com.cloud.user.Account; + +@APICommand(name = "stopSharedFileSystem", + responseObject= SharedFSResponse.class, + description = "Stop a Shared FileSystem", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class StopSharedFSCmd extends BaseAsyncCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + required = true, + entityType = SharedFSResponse.class, + description = "the ID of the shared filesystem") + private Long id; + + @Parameter(name = ApiConstants.FORCED, + type = CommandType.BOOLEAN, + description = "Force stop the shared filesystem.") + private Boolean forced; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public boolean isForced() { + return (forced != null) ? forced : false; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_SHAREDFS_STOP; + } + + @Override + public String getEventDescription() { + return "Stopping Shared FileSystem " + id; + } + + @Override + public void execute() { + SharedFS sharedFS = sharedFSService.stopSharedFS(this.getId(), this.isForced()); + if (sharedFS != null) { + ResponseObject.ResponseView respView = getResponseView(); + Account caller = CallContext.current().getCallingAccount(); + if (_accountService.isRootAdmin(caller.getId())) { + respView = ResponseObject.ResponseView.Full; + } + SharedFSResponse response = _responseGenerator.createSharedFSResponse(respView, sharedFS); + response.setObjectName(SharedFS.class.getSimpleName().toLowerCase()); + response.setResponseName(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to stop Shared FileSystem"); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/UpdateSharedFSCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/UpdateSharedFSCmd.java new file mode 100644 index 00000000000..daad6cc78c5 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/storage/sharedfs/UpdateSharedFSCmd.java @@ -0,0 +1,113 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.storage.sharedfs; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSService; + +import javax.inject.Inject; + +import com.cloud.user.Account; + +@APICommand(name = "updateSharedFileSystem", + responseObject= SharedFSResponse.class, + description = "Update a Shared FileSystem", + responseView = ResponseObject.ResponseView.Restricted, + entityType = SharedFS.class, + requestHasSensitiveInfo = false, + since = "4.20.0", + authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) +public class UpdateSharedFSCmd extends BaseCmd implements UserCmd { + + @Inject + SharedFSService sharedFSService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + required = true, + entityType = SharedFSResponse.class, + description = "the ID of the shared filesystem") + private Long id; + + @Parameter(name = ApiConstants.NAME, + type = CommandType.STRING, + description = "the name of the shared filesystem.") + private String name; + + @Parameter(name = ApiConstants.DESCRIPTION, + type = CommandType.STRING, + description = "the description for the shared filesystem.") + private String description; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } + + @Override + public void execute() { + SharedFS sharedFS = sharedFSService.updateSharedFS(this); + if (sharedFS != null) { + ResponseObject.ResponseView respView = getResponseView(); + Account caller = CallContext.current().getCallingAccount(); + if (_accountService.isRootAdmin(caller.getId())) { + respView = ResponseObject.ResponseView.Full; + } + SharedFSResponse response = _responseGenerator.createSharedFSResponse(respView, sharedFS); + response.setObjectName(SharedFS.class.getSimpleName().toLowerCase()); + response.setResponseName(getCommandName()); + setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update Shared FileSystem"); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java index 67705859419..30904db46c4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java @@ -20,7 +20,6 @@ package org.apache.cloudstack.api.command.user.tag; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.server.ResourceTag.ResourceObjectType; @APICommand(name = "createTags", description = "Creates resource tag(s)", responseObject = SuccessResponse.class, since = "4.0.0", entityType = {ResourceTag.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateTagsCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CreateTagsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java index 55dec6e9645..f8f319eba23 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java @@ -23,7 +23,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +39,6 @@ import com.cloud.server.ResourceTag.ResourceObjectType; @APICommand(name = "deleteTags", description = "Deleting resource tag(s)", responseObject = SuccessResponse.class, since = "4.0.0", entityType = {ResourceTag.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteTagsCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteTagsCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java index f672d4c8890..f094bc43507 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java @@ -31,7 +31,6 @@ import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.event.EventTypes; @@ -43,7 +42,6 @@ import com.cloud.user.Account; @APICommand(name = "copyTemplate", description = "Copies a template from one zone to another.", responseObject = TemplateResponse.class, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CopyTemplateCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(CopyTemplateCmd.class.getName()); private static final String s_name = "copytemplateresponse"; ///////////////////////////////////////////////////// @@ -191,7 +189,7 @@ public class CopyTemplateCmd extends BaseAsyncCmd implements UserCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to copy template"); } } catch (StorageUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java index 6c39ab6d3c7..5f09ac6698d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java @@ -20,6 +20,7 @@ import java.util.Collection; import java.util.List; import java.util.Map; +import com.cloud.cpu.CPU; import org.apache.cloudstack.acl.SecurityChecker; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -40,7 +41,6 @@ import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -55,7 +55,6 @@ import com.cloud.user.Account; + "A template created from this command is automatically designated as a private template visible to the account that created it.", responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateTemplateCmd extends BaseAsyncCreateCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(CreateTemplateCmd.class.getName()); private static final String s_name = "createtemplateresponse"; // /////////////////////////////////////////////////// @@ -150,6 +149,11 @@ public class CreateTemplateCmd extends BaseAsyncCreateCmd implements UserCmd { since = "4.19.0") private String accountName; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "the CPU arch of the template. Valid options are: x86_64, aarch64. Defaults to x86_64", + since = "4.20.2") + private String arch; + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// @@ -236,6 +240,10 @@ public class CreateTemplateCmd extends BaseAsyncCreateCmd implements UserCmd { return accountName; } + public CPU.CPUArch getArch() { + return CPU.CPUArch.fromType(arch); + } + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -348,11 +356,11 @@ public class CreateTemplateCmd extends BaseAsyncCreateCmd implements UserCmd { try { accountIdToUse = _accountService.finalyzeAccountId(accountName, domainId, projectId, true); } catch (InvalidParameterValueException | PermissionDeniedException ex) { - if (s_logger.isDebugEnabled()) { - s_logger.debug(String.format("An exception occurred while finalizing account id with accountName, domainId and projectId" + + if (logger.isDebugEnabled()) { + logger.debug(String.format("An exception occurred while finalizing account id with accountName, domainId and projectId" + "using callingAccountId=%s", callingAccount.getUuid()), ex); } - s_logger.warn("Unable to find accountId associated with accountName=" + accountName + " and domainId=" + logger.warn("Unable to find accountId associated with accountName=" + accountName + " and domainId=" + domainId + " or projectId=" + projectId + ", using callingAccountId=" + callingAccount.getUuid()); } return accountIdToUse != null ? accountIdToUse : callingAccount.getAccountId(); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java index 3d7aaaec31c..5e9bf317fe1 100755 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java @@ -17,8 +17,8 @@ package org.apache.cloudstack.api.command.user.template; import org.apache.commons.lang3.BooleanUtils; -import org.apache.log4j.Logger; +import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; @@ -40,7 +40,6 @@ import com.cloud.user.Account; description = "Deletes a template from the system. All virtual machines using the deleted template will not be affected.", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteTemplateCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteTemplateCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -55,6 +54,9 @@ public class DeleteTemplateCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, required = false, description = "Force delete a template.", since = "4.9+") private Boolean forced; + @Parameter(name = ApiConstants.IS_SYSTEM, type = CommandType.BOOLEAN, required = false, description = "Necessary if the template's type is system.", since = "4.20.0", authorized = {RoleType.Admin}) + private Boolean isSystem; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -71,6 +73,10 @@ public class DeleteTemplateCmd extends BaseAsyncCmd { return BooleanUtils.toBooleanDefaultIfNull(forced, false); } + public boolean getIsSystem() { + return BooleanUtils.toBooleanDefaultIfNull(isSystem, false); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java index 91e8d168ecb..22f59351e9a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.response.ExtractResponse; import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.event.EventTypes; @@ -38,7 +37,6 @@ import com.cloud.user.Account; @APICommand(name = "extractTemplate", description = "Extracts a template", responseObject = ExtractResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractTemplateCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); ///////////////////////////////////////////////////// @@ -103,7 +101,15 @@ public class ExtractTemplateCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "extracting template: " + this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()) + ((getZoneId() != null) ? " from zone: " + this._uuidMgr.getUuid(DataCenter.class, getZoneId()) : ""); + String templateId = this._uuidMgr.getUuid(VirtualMachineTemplate.class, getId()); + String baseDescription = String.format("Extracting template: %s", templateId); + + Long zoneId = getZoneId(); + if (zoneId == null) { + return baseDescription; + } + + return String.format("%s from zone: %s", baseDescription, this._uuidMgr.getUuid(DataCenter.class, zoneId)); } @Override @@ -122,14 +128,15 @@ public class ExtractTemplateCmd extends BaseAsyncCmd { CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _templateService.extract(this); if (uploadUrl != null) { - ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); + ExtractResponse response = _responseGenerator.createImageExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); + response.setObjectName("template"); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template"); } } catch (InternalErrorException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/GetUploadParamsForTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/GetUploadParamsForTemplateCmd.java index ab872b84edb..8fa1a5d53eb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/GetUploadParamsForTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/GetUploadParamsForTemplateCmd.java @@ -22,6 +22,7 @@ import java.net.MalformedURLException; import java.util.Collection; import java.util.Map; +import com.cloud.cpu.CPU; import com.cloud.hypervisor.Hypervisor; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -34,7 +35,6 @@ import org.apache.cloudstack.api.response.GetUploadParamsResponse; import org.apache.cloudstack.api.response.GuestOSResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.exception.ResourceAllocationException; @@ -43,7 +43,6 @@ import com.cloud.exception.ResourceAllocationException; authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class GetUploadParamsForTemplateCmd extends AbstractGetUploadParamsCmd { - public static final Logger s_logger = Logger.getLogger(GetUploadParamsForTemplateCmd.class.getName()); private static final String s_name = "postuploadtemplateresponse"; @@ -57,6 +56,11 @@ public class GetUploadParamsForTemplateCmd extends AbstractGetUploadParamsCmd { description = "the ID of the OS Type that best represents the OS of this template. Not required for VMware as the guest OS is obtained from the OVF file.") private Long osTypeId; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "the CPU arch of the template. Valid options are: x86_64, aarch64", + since = "4.20") + private String arch; + @Parameter(name = ApiConstants.BITS, type = CommandType.INTEGER, description = "32 or 64 bits support. 64 by default") private Integer bits; @@ -164,6 +168,10 @@ public class GetUploadParamsForTemplateCmd extends AbstractGetUploadParamsCmd { Boolean.TRUE.equals(deployAsIs); } + public CPU.CPUArch getArch() { + return CPU.CPUArch.fromType(arch); + } + @Override public void execute() throws ServerApiException { validateRequest(); @@ -172,7 +180,7 @@ public class GetUploadParamsForTemplateCmd extends AbstractGetUploadParamsCmd { response.setResponseName(getCommandName()); setResponseObject(response); } catch (ResourceAllocationException | MalformedURLException e) { - s_logger.error("exception while registering template", e); + logger.error("exception while registering template", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "exception while registering template: " + e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/ListTemplatePermissionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/ListTemplatePermissionsCmd.java index 970c6b34743..6d544df4187 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/ListTemplatePermissionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/ListTemplatePermissionsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.template; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; @@ -40,11 +39,6 @@ public class ListTemplatePermissionsCmd extends BaseListTemplateOrIsoPermissions return "template"; } - @Override - protected Logger getLogger() { - return Logger.getLogger(ListTemplatePermissionsCmd.class.getName()); - } - @Override protected boolean templateIsCorrectType(VirtualMachineTemplate template) { return !template.getFormat().equals(ImageFormat.ISO); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java index dae7cc97a4c..bff65ef70a9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java @@ -16,12 +16,12 @@ // under the License. package org.apache.cloudstack.api.command.user.template; +import com.cloud.cpu.CPU; import com.cloud.exception.InvalidParameterValueException; import com.cloud.server.ResourceIcon; import com.cloud.server.ResourceTag; import org.apache.cloudstack.api.response.ResourceIconResponse; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.Collections; @@ -42,11 +42,11 @@ import org.apache.cloudstack.context.CallContext; import com.cloud.template.VirtualMachineTemplate; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; +import org.apache.commons.lang3.StringUtils; @APICommand(name = "listTemplates", description = "List all public, private, and privileged templates.", responseObject = TemplateResponse.class, entityType = {VirtualMachineTemplate.class}, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListTemplatesCmd extends BaseListTaggedResourcesCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListTemplatesCmd.class.getName()); private static final String s_name = "listtemplatesresponse"; @@ -106,6 +106,11 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd implements User since = "4.19.0") private Boolean isVnf; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "the CPU arch of the template. Valid options are: x86_64, aarch64", + since = "4.20") + private String arch; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -193,6 +198,13 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd implements User return isVnf; } + public CPU.CPUArch getArch() { + if (StringUtils.isBlank(arch)) { + return null; + } + return CPU.CPUArch.fromType(arch); + } + @Override public String getCommandName() { return s_name; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java index 0a087888d52..1f968b869b9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java @@ -16,6 +16,7 @@ // under the License. package org.apache.cloudstack.api.command.user.template; +import com.cloud.cpu.CPU; import com.cloud.hypervisor.Hypervisor; import java.net.URISyntaxException; import java.util.ArrayList; @@ -41,7 +42,6 @@ import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.exception.ResourceAllocationException; import com.cloud.template.VirtualMachineTemplate; @@ -49,7 +49,6 @@ import com.cloud.template.VirtualMachineTemplate; @APICommand(name = "registerTemplate", description = "Registers an existing template into the CloudStack cloud. ", responseObject = TemplateResponse.class, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RegisterTemplateCmd extends BaseCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(RegisterTemplateCmd.class.getName()); private static final String s_name = "registertemplateresponse"; @@ -174,6 +173,11 @@ public class RegisterTemplateCmd extends BaseCmd implements UserCmd { since = "4.19.0") private String templateType; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "the CPU arch of the template. Valid options are: x86_64, aarch64", + since = "4.20") + private String arch; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -295,6 +299,10 @@ public class RegisterTemplateCmd extends BaseCmd implements UserCmd { return templateType; } + public CPU.CPUArch getArch() { + return CPU.CPUArch.fromType(arch); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -335,7 +343,7 @@ public class RegisterTemplateCmd extends BaseCmd implements UserCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to register template"); } } catch (URISyntaxException ex1) { - s_logger.info(ex1); + logger.info(ex1); throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex1.getMessage()); } } @@ -354,7 +362,9 @@ public class RegisterTemplateCmd extends BaseCmd implements UserCmd { "Parameter zoneids cannot combine all zones (-1) option with other zones"); String customHypervisor = HypervisorGuru.HypervisorCustomDisplayName.value(); - if (isDirectDownload() && !(getHypervisor().equalsIgnoreCase(Hypervisor.HypervisorType.KVM.toString()) + if (isDirectDownload() && + !(Hypervisor.HypervisorType.getType(getHypervisor()) + .isFunctionalitySupported(Hypervisor.HypervisorType.Functionality.DirectDownloadTemplate) || getHypervisor().equalsIgnoreCase(customHypervisor))) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, String.format("Parameter directdownload " + "is only allowed for KVM or %s templates", customHypervisor)); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java index 2afa6a98b13..dbbd771293a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java @@ -16,8 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.template; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "updateTemplate", description = "Updates attributes of a template.", responseObject = TemplateResponse.class, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateTemplateCmd extends BaseUpdateTemplateOrIsoCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(UpdateTemplateCmd.class.getName()); private static final String s_name = "updatetemplateresponse"; ///////////////////////////////////////////////////// @@ -46,6 +43,9 @@ public class UpdateTemplateCmd extends BaseUpdateTemplateOrIsoCmd implements Use description = "the type of the template. Valid options are: USER/VNF (for all users) and SYSTEM/ROUTING/BUILTIN (for admins only).") private String templateType; + @Parameter(name = ApiConstants.TEMPLATE_TAG, type = CommandType.STRING, description = "the tag for this template.", since = "4.20.0") + private String templateTag; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -59,6 +59,10 @@ public class UpdateTemplateCmd extends BaseUpdateTemplateOrIsoCmd implements Use return templateType; } + public String getTemplateTag() { + return templateTag; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/UpdateTemplatePermissionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/UpdateTemplatePermissionsCmd.java index 7cf5e0bc3f5..de8f09a6400 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/UpdateTemplatePermissionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/UpdateTemplatePermissionsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.template; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; @@ -35,10 +34,6 @@ public class UpdateTemplatePermissionsCmd extends BaseUpdateTemplateOrIsoPermiss return "updatetemplatepermissionsresponse"; } - @Override - protected Logger getLogger() { - return Logger.getLogger(UpdateTemplatePermissionsCmd.class.getName()); - } @Override public long getEntityOwnerId() { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/DeleteUserDataCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/DeleteUserDataCmd.java index d27b90f07a1..a1d1afc7b05 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/DeleteUserDataCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/DeleteUserDataCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.UserDataResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.user.Account; import com.cloud.user.UserData; @@ -39,7 +38,6 @@ import com.cloud.user.UserData; authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class DeleteUserDataCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteUserDataCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/LinkUserDataToTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/LinkUserDataToTemplateCmd.java index be1a95c3694..e322de00bb1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/LinkUserDataToTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/LinkUserDataToTemplateCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.command.admin.AdminCmd; import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.UserDataResponse; -import org.apache.log4j.Logger; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; @@ -39,7 +38,6 @@ import com.cloud.utils.exception.CloudRuntimeException; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.18.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class LinkUserDataToTemplateCmd extends BaseCmd implements AdminCmd { - public static final Logger s_logger = Logger.getLogger(LinkUserDataToTemplateCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/ListUserDataCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/ListUserDataCmd.java index 87d8883e2e3..64ab3ec3d70 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/ListUserDataCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/ListUserDataCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.UserDataResponse; -import org.apache.log4j.Logger; import com.cloud.user.UserData; import com.cloud.utils.Pair; @@ -35,7 +34,6 @@ import com.cloud.utils.Pair; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.18", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class ListUserDataCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListUserDataCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/RegisterUserDataCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/RegisterUserDataCmd.java index 3d44230cac1..4588d734847 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/RegisterUserDataCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/userdata/RegisterUserDataCmd.java @@ -32,7 +32,6 @@ import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.UserDataResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -44,7 +43,7 @@ import com.cloud.network.NetworkModel; import com.cloud.user.UserData; @APICommand(name = "registerUserData", - description = "Register a new userdata.", + description = "Register a new User Data.", since = "4.18", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, @@ -52,39 +51,38 @@ import com.cloud.user.UserData; authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class RegisterUserDataCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(RegisterUserDataCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "Name of the userdata") + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "Name of the User Data") private String name; //Owner information - @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the userdata. Must be used with domainId.") + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the User Data. Must be used with domainId.") private String accountName; @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, - description = "an optional domainId for the userdata. If the account parameter is used, domainId must also be used.") + description = "an optional domainId for the User Data. If the account parameter is used, domainId must also be used.") private Long domainId; - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "an optional project for the userdata") + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "an optional project for the User Data") private Long projectId; @Parameter(name = ApiConstants.USER_DATA, type = CommandType.STRING, required = true, - description = "Base64 encoded userdata content. " + + description = "Base64 encoded User Data content. " + "Using HTTP GET (via querystring), you can send up to 4KB of data after base64 encoding. " + - "Using HTTP POST (via POST body), you can send up to 1MB of data after base64 encoding. " + - "You also need to change vm.userdata.max.length value", + "Using HTTP POST (via POST body), you can send up to 32KB of data after base64 encoding, " + + "which can be increased upto 1MB using the vm.userdata.max.length setting", length = 1048576) private String userData; - @Parameter(name = ApiConstants.PARAMS, type = CommandType.STRING, description = "comma separated list of variables declared in userdata content") + @Parameter(name = ApiConstants.PARAMS, type = CommandType.STRING, description = "comma separated list of variables declared in the User Data content") private String params; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java index fc009c7e5db..e76a75ae398 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/AddIpToVmNicCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.NicResponse; import org.apache.cloudstack.api.response.NicSecondaryIpResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.event.EventTypes; @@ -46,7 +45,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "addIpToNic", description = "Assigns secondary IP to NIC", responseObject = NicSecondaryIpResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddIpToVmNicCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(AddIpToVmNicCmd.class.getName()); private static final String s_name = "addiptovmnicresponse"; ///////////////////////////////////////////////////// @@ -81,7 +79,7 @@ public class AddIpToVmNicCmd extends BaseAsyncCreateCmd { private boolean isZoneSGEnabled() { Network ntwk = _entityMgr.findById(Network.class, getNetworkId()); DataCenter dc = _entityMgr.findById(DataCenter.class, ntwk.getDataCenterId()); - return dc.isSecurityGroupEnabled(); + return dc.isSecurityGroupEnabled() || _ntwkModel.isSecurityGroupSupportedForZone(dc.getId()); } @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/AddNicToVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/AddNicToVMCmd.java index 1e395831a6f..ecd066d98cd 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/AddNicToVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/AddNicToVMCmd.java @@ -37,7 +37,6 @@ import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -51,7 +50,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "addNicToVirtualMachine", description = "Adds VM to specified network by creating a NIC", responseObject = UserVmResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class AddNicToVMCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(AddNicToVMCmd.class); private static final String s_name = "addnictovirtualmachineresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/CreateVMScheduleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/CreateVMScheduleCmd.java index 935f39bf4dd..5811eb1abfc 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/CreateVMScheduleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/CreateVMScheduleCmd.java @@ -68,7 +68,7 @@ public class CreateVMScheduleCmd extends BaseCmd { @Parameter(name = ApiConstants.ACTION, type = CommandType.STRING, required = true, - description = "Action to take on the VM (start/stop/restart/force_stop/force_reboot).") + description = "Action to take on the VM (start/stop/reboot/force_stop/force_reboot).") private String action; @Parameter(name = ApiConstants.START_DATE, diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java index e02111af59f..52d42a95d98 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java @@ -31,6 +31,7 @@ import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.affinity.AffinityGroupResponse; import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiArgValidator; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiConstants.IoDriverPolicy; @@ -56,7 +57,6 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.agent.api.LogLevel; import com.cloud.event.EventTypes; @@ -80,7 +80,6 @@ import com.cloud.vm.VmDetailConstants; @APICommand(name = "deployVirtualMachine", description = "Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject = UserVmResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd implements SecurityGroupAction, UserCmd { - public static final Logger s_logger = Logger.getLogger(DeployVMCmd.class.getName()); private static final String s_name = "deployvirtualmachineresponse"; @@ -99,7 +98,7 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd implements SecurityG @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.UUID, entityType = TemplateResponse.class, required = true, description = "the ID of the template for the virtual machine") private Long templateId; - @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "host name for the virtual machine") + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "host name for the virtual machine", validations = {ApiArgValidator.RFCComplianceDomainName}) private String name; @Parameter(name = ApiConstants.DISPLAY_NAME, type = CommandType.STRING, description = "an optional user generated name for the virtual machine") @@ -317,7 +316,7 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd implements SecurityG } catch (IllegalArgumentException e) { String errMesg = "Invalid bootType " + bootType + "Specified for vm " + getName() + " Valid values are: " + Arrays.toString(ApiConstants.BootType.values()); - s_logger.warn(errMesg); + logger.warn(errMesg); throw new InvalidParameterValueException(errMesg); } } @@ -364,14 +363,14 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd implements SecurityG } catch (IllegalArgumentException e) { String msg = String.format("Invalid %s: %s specified for VM: %s. Valid values are: %s", ApiConstants.BOOT_MODE, bootMode, getName(), Arrays.toString(ApiConstants.BootMode.values())); - s_logger.error(msg); + logger.error(msg); throw new InvalidParameterValueException(msg); } } if (ApiConstants.BootType.UEFI.equals(getBootType())) { String msg = String.format("%s must be specified for the VM with boot type: %s. Valid values are: %s", ApiConstants.BOOT_MODE, getBootType(), Arrays.toString(ApiConstants.BootMode.values())); - s_logger.error(msg); + logger.error(msg); throw new InvalidParameterValueException(msg); } return null; @@ -404,8 +403,8 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd implements SecurityG nic = null; } String networkUuid = entry.get(VmDetailConstants.NETWORK); - if (s_logger.isTraceEnabled()) { - s_logger.trace(String.format("nic, '%s', goes on net, '%s'", nic, networkUuid)); + if (logger.isTraceEnabled()) { + logger.trace(String.format("nic, '%s', goes on net, '%s'", nic, networkUuid)); } if (nic == null || StringUtils.isEmpty(networkUuid) || _entityMgr.findByUuid(Network.class, networkUuid) == null) { throw new InvalidParameterValueException(String.format("Network ID: %s for NIC ID: %s is invalid", networkUuid, nic)); @@ -715,7 +714,7 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd implements SecurityG return ApiConstants.IoDriverPolicy.valueOf(policyType); } catch (IllegalArgumentException e) { String errMesg = String.format("Invalid io policy %s specified for vm %s. Valid values are: %s", ioDriverPolicy, getName(), Arrays.toString(ApiConstants.IoDriverPolicy.values())); - s_logger.warn(errMesg); + logger.warn(errMesg); throw new InvalidParameterValueException(errMesg); } } @@ -781,13 +780,13 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd implements SecurityG try { result = _userVmService.startVirtualMachine(this); } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ResourceAllocationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { StringBuilder message = new StringBuilder(ex.getMessage()); @@ -796,12 +795,12 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd implements SecurityG message.append(", Please check the affinity groups provided, there may not be sufficient capacity to follow them"); } } - s_logger.info(String.format("%s: %s", message.toString(), ex.getLocalizedMessage())); - s_logger.debug(message.toString(), ex); + logger.info(String.format("%s: %s", message.toString(), ex.getLocalizedMessage())); + logger.debug(message.toString(), ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, message.toString()); } } else { - s_logger.info("VM " + getEntityUuid() + " already created, load UserVm from DB"); + logger.info("VM " + getEntityUuid() + " already created, load UserVm from DB"); result = _userVmService.finalizeCreateVirtualMachine(getEntityId()); } @@ -827,17 +826,17 @@ public class DeployVMCmd extends BaseAsyncCreateCustomIdCmd implements SecurityG throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to deploy vm"); } } catch (InsufficientCapacityException ex) { - s_logger.info(ex); - s_logger.trace(ex.getMessage(), ex); + logger.info(ex); + logger.trace(ex.getMessage(), ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (ResourceAllocationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java index 07fd55276f8..18a9d2058a6 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.vm; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -46,7 +45,6 @@ import com.cloud.vm.VirtualMachine; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class DestroyVMCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(DestroyVMCmd.class.getName()); private static final String s_name = "destroyvirtualmachineresponse"; @@ -142,7 +140,8 @@ public class DestroyVMCmd extends BaseAsyncCmd implements UserCmd { if (responses != null && !responses.isEmpty()) { response = responses.get(0); } - response.setResponseName("virtualmachine"); + response.setResponseName(getCommandName()); + response.setObjectName("virtualmachine"); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to destroy vm"); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/GetVMPasswordCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/GetVMPasswordCmd.java index d3cbf82f755..11534fd4375 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/GetVMPasswordCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/GetVMPasswordCmd.java @@ -16,10 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vm; -import java.security.InvalidParameterException; - -import org.apache.log4j.Logger; - import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; @@ -29,6 +25,7 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.GetVMPasswordResponse; import org.apache.cloudstack.api.response.UserVmResponse; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.user.Account; import com.cloud.uservm.UserVm; import com.cloud.vm.VirtualMachine; @@ -36,7 +33,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "getVMPassword", responseObject = GetVMPasswordResponse.class, description = "Returns an encrypted password for the VM", entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class GetVMPasswordCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(GetVMPasswordCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -63,7 +59,7 @@ public class GetVMPasswordCmd extends BaseCmd { public void execute() { String passwd = _mgr.getVMPassword(this); if (passwd == null || passwd.equals("")) - throw new InvalidParameterException("No password for VM with id '" + getId() + "' found."); + throw new InvalidParameterValueException("No password for VM with id '" + getId() + "' found."); setResponseObject(new GetVMPasswordResponse(getCommandName(), passwd)); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java index 44710d018d3..0e659fc02a1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java @@ -33,7 +33,6 @@ import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.cloudstack.api.response.NicResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -45,7 +44,6 @@ import com.cloud.vm.Nic; @APICommand(name = "listNics", description = "list the vm nics IP to NIC", responseObject = NicResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListNicsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListNicsCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -157,7 +155,7 @@ public class ListNicsCmd extends BaseListCmd { this.setResponseObject(response); } } catch (Exception e) { - s_logger.warn("Failed to list secondary ip address per nic "); + logger.warn("Failed to list secondary ip address per nic "); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java index a6c5bafbd51..c205b357732 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java @@ -46,10 +46,11 @@ import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +import com.cloud.cpu.CPU; import com.cloud.exception.InvalidParameterValueException; import com.cloud.server.ResourceIcon; import com.cloud.server.ResourceTag; @@ -59,7 +60,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "listVirtualMachines", description = "List the virtual machines owned by the account.", responseObject = UserVmResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class ListVMsCmd extends BaseListRetrieveOnlyResourceCountCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListVMsCmd.class.getName()); ///////////////////////////////////////////////////// @@ -155,6 +155,11 @@ public class ListVMsCmd extends BaseListRetrieveOnlyResourceCountCmd implements @Parameter(name = ApiConstants.USER_DATA_ID, type = CommandType.UUID, entityType = UserDataResponse.class, required = false, description = "the instances by userdata", since = "4.20.1") private Long userdataId; + @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, + description = "CPU arch of the VM", + since = "4.20.1") + private String arch; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -294,6 +299,10 @@ public class ListVMsCmd extends BaseListRetrieveOnlyResourceCountCmd implements return isVnf; } + public CPU.CPUArch getArch() { + return StringUtils.isBlank(arch) ? null : CPU.CPUArch.fromType(arch); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java index 9bdcc1aed56..153f5ea6563 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java @@ -16,8 +16,8 @@ // under the License. package org.apache.cloudstack.api.command.user.vm; -import org.apache.log4j.Logger; +import com.cloud.exception.ResourceAllocationException; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; @@ -42,7 +42,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "rebootVirtualMachine", description = "Reboots a virtual machine.", responseObject = UserVmResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class RebootVMCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(RebootVMCmd.class.getName()); private static final String s_name = "rebootvirtualmachineresponse"; ///////////////////////////////////////////////////// @@ -115,7 +114,7 @@ public class RebootVMCmd extends BaseAsyncCmd implements UserCmd { } @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException { + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { CallContext.current().setEventDetails("Vm Id: " + this._uuidMgr.getUuid(VirtualMachine.class, getId())); UserVm result; result = _userVmService.rebootVirtualMachine(this); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java index e964cc69231..2f53c3d4e4c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveIpFromVmNicCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vm; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -41,7 +40,6 @@ import com.cloud.vm.NicSecondaryIp; @APICommand(name = "removeIpFromNic", description = "Removes secondary IP from the NIC.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RemoveIpFromVmNicCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RemoveIpFromVmNicCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -129,7 +127,7 @@ public class RemoveIpFromVmNicCmd extends BaseAsyncCmd { private boolean isZoneSGEnabled() { Network ntwk = _entityMgr.findById(Network.class, getNetworkId()); DataCenter dc = _entityMgr.findById(DataCenter.class, ntwk.getDataCenterId()); - return dc.isSecurityGroupEnabled(); + return dc.isSecurityGroupEnabled() || _ntwkModel.isSecurityGroupSupportedForZone(dc.getId()); } @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveNicFromVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveNicFromVMCmd.java index 5fd016c38ed..d9024f34022 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveNicFromVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RemoveNicFromVMCmd.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.EnumSet; import com.cloud.vm.Nic; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -45,7 +44,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "removeNicFromVirtualMachine", description = "Removes VM from specified network by deleting a NIC", responseObject = UserVmResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class RemoveNicFromVMCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(RemoveNicFromVMCmd.class); private static final String s_name = "removenicfromvirtualmachineresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java index 1cf4c929b32..7270004aeed 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.vm; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -45,7 +44,6 @@ import com.cloud.vm.VirtualMachine; "support this feature for this command to take effect. [async]", responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class ResetVMPasswordCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ResetVMPasswordCmd.class.getName()); private static final String s_name = "resetpasswordforvirtualmachineresponse"; @@ -122,9 +120,9 @@ public class ResetVMPasswordCmd extends BaseAsyncCmd implements UserCmd { UserVm vm = _responseGenerator.findUserVmById(getId()); if (StringUtils.isBlank(password)) { password = _mgr.generateRandomPassword(); - s_logger.debug(String.format("Resetting VM [%s] password to a randomly generated password.", vm.getUuid())); + logger.debug(String.format("Resetting VM [%s] password to a randomly generated password.", vm.getUuid())); } else { - s_logger.debug(String.format("Resetting VM [%s] password to password defined by user.", vm.getUuid())); + logger.debug(String.format("Resetting VM [%s] password to password defined by user.", vm.getUuid())); } CallContext.current().setEventDetails("Vm Id: " + getId()); UserVm result = _userVmService.resetVMPassword(this, password); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMSSHKeyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMSSHKeyCmd.java index 259cfebbad5..a4019411e1d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMSSHKeyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMSSHKeyCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.vm; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -50,7 +49,6 @@ import java.util.List; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class ResetVMSSHKeyCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ResetVMSSHKeyCmd.class.getName()); private static final String s_name = "resetSSHKeyforvirtualmachineresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMUserDataCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMUserDataCmd.java index 7e0aab98760..0ecf4ff1384 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMUserDataCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ResetVMUserDataCmd.java @@ -37,7 +37,6 @@ import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.UserDataResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import java.util.Map; @@ -46,7 +45,6 @@ import java.util.Map; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true, since = "4.18.0") public class ResetVMUserDataCmd extends BaseCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ResetVMUserDataCmd.class.getName()); private static final String s_name = "resetuserdataforvirtualmachineresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java index 17c4e97eb3b..3839049eee5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java @@ -17,11 +17,8 @@ package org.apache.cloudstack.api.command.user.vm; import com.cloud.vm.VmDetailConstants; -import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.cloudstack.api.response.DiskOfferingResponse; -import org.apache.log4j.Logger; - import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -31,6 +28,7 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ResponseObject.ResponseView; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.command.user.UserCmd; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.context.CallContext; @@ -50,7 +48,6 @@ import java.util.Map; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class RestoreVMCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(RestoreVMCmd.class); private static final String s_name = "restorevmresponse"; @ACL(accessType = AccessType.OperateEntry) diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java index 5af45762ece..3af6d5245f0 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java @@ -33,7 +33,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.UserVmResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -49,7 +48,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "scaleVirtualMachine", description = "Scales the virtual machine to a new service offering. This command also considers the volume size in the service offering or disk offering linked to the new service offering and apply all characteristics to the root volume.", responseObject = UserVmResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ScaleVMCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ScaleVMCmd.class.getName()); private static final String s_name = "scalevirtualmachineresponse"; ///////////////////////////////////////////////////// @@ -169,16 +167,16 @@ public class ScaleVMCmd extends BaseAsyncCmd implements UserCmd { try { result = _userVmService.upgradeVirtualMachine(this); } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (ManagementServerException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (VirtualMachineMigrationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } if (result != null){ diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java index 10c50dc380b..c0311d59997 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.vm; import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.PodResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -51,7 +50,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "startVirtualMachine", responseObject = UserVmResponse.class, description = "Starts a virtual machine.", responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class StartVMCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(StartVMCmd.class.getName()); private static final String s_name = "startvirtualmachineresponse"; @@ -104,6 +102,10 @@ public class StartVMCmd extends BaseAsyncCmd implements UserCmd { return id; } + public void setId(Long id) { + this.id = id; + } + public Long getHostId() { return hostId; } @@ -188,19 +190,19 @@ public class StartVMCmd extends BaseAsyncCmd implements UserCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to start a vm"); } } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (StorageUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ExecutionException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ResourceAllocationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { StringBuilder message = new StringBuilder(ex.getMessage()); @@ -209,8 +211,8 @@ public class StartVMCmd extends BaseAsyncCmd implements UserCmd { message.append(", Please check the affinity groups provided, there may not be sufficient capacity to follow them"); } } - s_logger.info(ex); - s_logger.info(message.toString(), ex); + logger.info(ex); + logger.info(message.toString(), ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, message.toString()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java index 113ba9ed25d..bfd5d8d07f6 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vm; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -41,7 +40,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "stopVirtualMachine", responseObject = UserVmResponse.class, description = "Stops a virtual machine.", responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class StopVMCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(StopVMCmd.class.getName()); private static final String s_name = "stopvirtualmachineresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateDefaultNicForVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateDefaultNicForVMCmd.java index ff533f82095..837bde06a6c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateDefaultNicForVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateDefaultNicForVMCmd.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.EnumSet; import com.cloud.vm.Nic; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -45,7 +44,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "updateDefaultNicForVirtualMachine", description = "Changes the default NIC on a VM", responseObject = UserVmResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class UpdateDefaultNicForVMCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(UpdateDefaultNicForVMCmd.class); private static final String s_name = "updatedefaultnicforvirtualmachineresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java index 1660255979a..0f5dade96d2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java @@ -22,8 +22,9 @@ import java.util.List; import java.util.Map; import com.cloud.utils.exception.CloudRuntimeException; + +import org.apache.cloudstack.api.ApiArgValidator; import org.apache.cloudstack.api.response.UserDataResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -54,7 +55,6 @@ import com.cloud.vm.VirtualMachine; "Therefore, stop the VM manually before issuing this call.", responseObject = UserVmResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class UpdateVMCmd extends BaseCustomIdCmd implements SecurityGroupAction, UserCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVMCmd.class.getName()); private static final String s_name = "updatevirtualmachineresponse"; ///////////////////////////////////////////////////// @@ -106,7 +106,7 @@ public class UpdateVMCmd extends BaseCustomIdCmd implements SecurityGroupAction, description = "true if VM contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory. This can be updated only when dynamic scaling is enabled on template, service offering and the corresponding global setting") protected Boolean isDynamicallyScalable; - @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "new host name of the vm. The VM has to be stopped/started for this update to take affect", since = "4.4") + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "new host name of the vm. The VM has to be stopped/started for this update to take affect", validations = {ApiArgValidator.RFCComplianceDomainName}, since = "4.4") private String name; @Parameter(name = ApiConstants.INSTANCE_NAME, type = CommandType.STRING, description = "instance name of the user vm", since = "4.4", authorized = {RoleType.Admin}) @@ -146,6 +146,14 @@ public class UpdateVMCmd extends BaseCustomIdCmd implements SecurityGroupAction, @Parameter(name = ApiConstants.EXTRA_CONFIG, type = CommandType.STRING, since = "4.12", description = "an optional URL encoded string that can be passed to the virtual machine upon successful deployment", length = 5120) private String extraConfig; + @Parameter(name = ApiConstants.DELETE_PROTECTION, + type = CommandType.BOOLEAN, since = "4.20.0", + description = "Set delete protection for the virtual machine. If " + + "true, the instance will be protected from deletion. " + + "Note: If the instance is managed by another service like" + + " autoscaling groups or CKS, delete protection will be ignored.") + private Boolean deleteProtection; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -215,6 +223,10 @@ public class UpdateVMCmd extends BaseCustomIdCmd implements SecurityGroupAction, return cleanupDetails == null ? false : cleanupDetails.booleanValue(); } + public Boolean getDeleteProtection() { + return deleteProtection; + } + public Map> getDhcpOptionsMap() { Map> dhcpOptionsMap = new HashMap<>(); if (dhcpOptionsNetworkList != null && !dhcpOptionsNetworkList.isEmpty()) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateVmNicIpCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateVmNicIpCmd.java index 40658f9b58d..5c654701de9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateVmNicIpCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpdateVmNicIpCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.vm; import java.util.ArrayList; import java.util.EnumSet; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -49,7 +48,6 @@ import com.cloud.vm.Nic; @APICommand(name = "updateVmNicIp", description = "Update the default Ip of a VM Nic", responseObject = UserVmResponse.class) public class UpdateVmNicIpCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVmNicIpCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java index 4b31c12ec0a..6a7422e70bb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.vm; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -47,7 +46,6 @@ import com.cloud.vm.VirtualMachine; "this command to take effect.", responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class UpgradeVMCmd extends BaseCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName()); private static final String s_name = "changeserviceforvirtualmachineresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java index 154ec45873a..e2952b5bd81 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vmgroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.vm.InstanceGroup; @APICommand(name = "createInstanceGroup", description = "Creates a vm group", responseObject = InstanceGroupResponse.class, entityType = {InstanceGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateVMGroupCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateVMGroupCmd.class.getName()); // /////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java index 0bdda0bb9e7..b74bc43eeb7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vmgroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -35,7 +34,6 @@ import com.cloud.vm.InstanceGroup; @APICommand(name = "deleteInstanceGroup", description = "Deletes a vm group", responseObject = SuccessResponse.class, entityType = {InstanceGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteVMGroupCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVMGroupCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/ListVMGroupsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/ListVMGroupsCmd.java index 2e61c898ae0..31845a956e9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/ListVMGroupsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/ListVMGroupsCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vmgroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -30,7 +29,6 @@ import com.cloud.vm.InstanceGroup; @APICommand(name = "listInstanceGroups", description = "Lists vm groups", responseObject = InstanceGroupResponse.class, entityType = {InstanceGroup.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListVMGroupsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListVMGroupsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java index 8873c852460..5c553f06404 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vmgroup; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -35,7 +34,6 @@ import com.cloud.vm.InstanceGroup; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateVMGroupCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVMGroupCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java index e83c6b4009d..18a478e9dae 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/CreateVMSnapshotCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VMSnapshotResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -42,7 +41,6 @@ import com.cloud.vm.snapshot.VMSnapshot; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateVMSnapshotCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateVMSnapshotCmd.class.getName()); @ACL(accessType = AccessType.OperateEntry) @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, required = true, entityType = UserVmResponse.class, description = "The ID of the vm") diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/DeleteVMSnapshotCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/DeleteVMSnapshotCmd.java index bcddc75a8e7..94b8824f868 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/DeleteVMSnapshotCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/DeleteVMSnapshotCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.vmsnapshot; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -39,7 +38,6 @@ import com.cloud.vm.snapshot.VMSnapshot; @APICommand(name = "deleteVMSnapshot", description = "Deletes a vmsnapshot.", responseObject = SuccessResponse.class, since = "4.2.0", entityType = {VMSnapshot.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteVMSnapshotCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVMSnapshotCmd.class.getName()); @ACL(accessType = AccessType.OperateEntry) @Parameter(name = ApiConstants.VM_SNAPSHOT_ID, diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/RevertToVMSnapshotCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/RevertToVMSnapshotCmd.java index 42cd18bfa2f..310b45687d4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/RevertToVMSnapshotCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vmsnapshot/RevertToVMSnapshotCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.vmsnapshot; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -45,7 +44,6 @@ import com.cloud.vm.snapshot.VMSnapshot; @APICommand(name = "revertToVMSnapshot", description = "Revert VM from a vmsnapshot.", responseObject = UserVmResponse.class, since = "4.2.0", responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class RevertToVMSnapshotCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(RevertToVMSnapshotCmd.class.getName()); private static final String s_name = "reverttovmsnapshotresponse"; @ACL(accessType = AccessType.OperateEntry, pointerToEntity = "getVmId()") diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java index 8d472d96eef..287991fa984 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AddResourceDetailCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.volume; import java.util.Map; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -33,7 +32,6 @@ import com.cloud.server.ResourceTag; @APICommand(name = "addResourceDetail", description = "Adds detail for the Resource.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddResourceDetailCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(AddResourceDetailCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AssignVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AssignVolumeCmd.java index 03413682c4f..1a51aa03c22 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AssignVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AssignVolumeCmd.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.VolumeResponse; -import org.apache.log4j.Logger; import com.cloud.storage.Volume; @@ -38,7 +37,6 @@ import java.util.Map; @APICommand(name = AssignVolumeCmd.CMD_NAME, responseObject = VolumeResponse.class, description = "Changes ownership of a Volume from one account to another.", entityType = { Volume.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.18.0.0") public class AssignVolumeCmd extends BaseCmd implements UserCmd { - public static final Logger LOGGER = Logger.getLogger(AssignVolumeCmd.class.getName()); public static final String CMD_NAME = "assignVolume"; ///////////////////////////////////////////////////// @@ -96,7 +94,7 @@ public class AssignVolumeCmd extends BaseCmd implements UserCmd { } catch (CloudRuntimeException | ResourceAllocationException e) { String msg = String.format("Assign volume command for volume [%s] failed due to [%s].", getFullUrlParams().get("volumeid"), e.getMessage()); - LOGGER.error(msg, e); + logger.error(msg, e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, msg); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java index 687d683309c..1a3b9220877 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.volume; import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -41,7 +40,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "attachVolume", description = "Attaches a disk volume to a virtual machine.", responseObject = VolumeResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AttachVolumeCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(AttachVolumeCmd.class.getName()); private static final String s_name = "attachvolumeresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/CheckAndRepairVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/CheckAndRepairVolumeCmd.java index e28efd10852..56fdf6bc126 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/CheckAndRepairVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/CheckAndRepairVolumeCmd.java @@ -16,8 +16,8 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; -import com.cloud.event.EventTypes; -import com.cloud.exception.InvalidParameterValueException; +import java.util.Arrays; + import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -30,21 +30,19 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.context.CallContext; import org.apache.commons.lang3.EnumUtils; -import org.apache.log4j.Logger; +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.storage.Volume; import com.cloud.user.Account; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; -import java.util.Arrays; - @APICommand(name = "checkVolume", description = "Check the volume for any errors or leaks and also repairs when repair parameter is passed, this is currently supported for KVM only", responseObject = VolumeResponse.class, entityType = {Volume.class}, since = "4.19.1", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class CheckAndRepairVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CheckAndRepairVolumeCmd.class.getName()); private static final String s_name = "checkandrepairvolumeresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java index 566e8a46bd9..7ffcea50b21 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -48,7 +47,6 @@ import com.cloud.vm.VirtualMachine; Volume.class, VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateVolumeCmd extends BaseAsyncCreateCustomIdCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(CreateVolumeCmd.class.getName()); private static final String s_name = "createvolumeresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java index 4bcc8a88545..6111488a802 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteVolume", description = "Deletes a detached disk volume.", responseObject = SuccessResponse.class, entityType = {Volume.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteVolumeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVolumeCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DestroyVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DestroyVolumeCmd.java index f4007ce9f40..2eafb76e591 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DestroyVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DestroyVolumeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -42,7 +41,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class DestroyVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DestroyVolumeCmd.class.getName()); private static final String s_name = "destroyvolumeresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java index e92f6a3cb0d..2fddcace84d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.volume; import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -42,7 +41,6 @@ import com.cloud.vm.VirtualMachine; @APICommand(name = "detachVolume", description = "Detaches a disk volume from a virtual machine.", responseObject = VolumeResponse.class, responseView = ResponseView.Restricted, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DetachVolumeCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(DetachVolumeCmd.class.getName()); private static final String s_name = "detachvolumeresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java index 8f6e3a6c120..6ddb5f1e567 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java @@ -16,8 +16,8 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; -import org.apache.log4j.Logger; +import com.cloud.dc.DataCenter; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; @@ -32,16 +32,13 @@ import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; -import com.cloud.dc.DataCenter; import com.cloud.event.EventTypes; -import com.cloud.storage.Upload; import com.cloud.storage.Volume; import com.cloud.user.Account; @APICommand(name = "extractVolume", description = "Extracts volume", responseObject = ExtractResponse.class, entityType = {Volume.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ExtractVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ExtractVolumeCmd.class.getName()); ///////////////////////////////////////////////////// @@ -118,28 +115,19 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "Extraction job"; + String volumeId = this._uuidMgr.getUuid(Volume.class, getId()); + String zoneId = this._uuidMgr.getUuid(DataCenter.class, getZoneId()); + + return String.format("Extracting volume: %s from zone: %s", volumeId, zoneId); } @Override public void execute() { - CallContext.current().setEventDetails("Volume Id: " + this._uuidMgr.getUuid(Volume.class, getId())); + CallContext.current().setEventDetails(getEventDescription()); String uploadUrl = _volumeService.extractVolume(this); if (uploadUrl != null) { - ExtractResponse response = new ExtractResponse(); + ExtractResponse response = _responseGenerator.createVolumeExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl); response.setResponseName(getCommandName()); - response.setObjectName("volume"); - Volume vol = _entityMgr.findById(Volume.class, id); - response.setId(vol.getUuid()); - response.setName(vol.getName()); - DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId); - response.setZoneId(zone.getUuid()); - response.setZoneName(zone.getName()); - response.setMode(mode); - response.setState(Upload.Status.DOWNLOAD_URL_CREATED.toString()); - Account account = _entityMgr.findById(Account.class, getEntityOwnerId()); - response.setAccountId(account.getUuid()); - response.setUrl(uploadUrl); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract volume"); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/GetUploadParamsForVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/GetUploadParamsForVolumeCmd.java index 1342ffc4748..4ccd5f97993 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/GetUploadParamsForVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/GetUploadParamsForVolumeCmd.java @@ -30,12 +30,10 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.cloudstack.api.response.GetUploadParamsResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; @APICommand(name = "getUploadParamsForVolume", description = "Upload a data disk to the cloudstack cloud.", responseObject = GetUploadParamsResponse.class, since = "4.6.0", requestHasSensitiveInfo= false, responseHasSensitiveInfo = false) public class GetUploadParamsForVolumeCmd extends AbstractGetUploadParamsCmd { - public static final Logger s_logger = Logger.getLogger(GetUploadParamsForVolumeCmd.class.getName()); private static final String s_name = "postuploadvolumeresponse"; @@ -62,7 +60,7 @@ public class GetUploadParamsForVolumeCmd extends AbstractGetUploadParamsCmd { response.setResponseName(getCommandName()); setResponseObject(response); } catch (MalformedURLException | ResourceAllocationException e) { - s_logger.error("exception while uploading volume", e); + logger.error("exception while uploading volume", e); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "exception while uploading a volume: " + e.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java index 6510106557b..a1024a98898 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java @@ -37,14 +37,12 @@ import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.commons.lang3.BooleanUtils; -import org.apache.log4j.Logger; import com.cloud.storage.Volume; @APICommand(name = "listVolumes", description = "Lists all volumes.", responseObject = VolumeResponse.class, responseView = ResponseView.Restricted, entityType = { Volume.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListVolumesCmd extends BaseListRetrieveOnlyResourceCountCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListVolumesCmd.class.getName()); private static final String s_name = "listvolumesresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/RecoverVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/RecoverVolumeCmd.java index 2589f816bc6..cd5a7735e38 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/RecoverVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/RecoverVolumeCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.volume; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -39,7 +38,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = true) public class RecoverVolumeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(RecoverVolumeCmd.class.getName()); private static final String s_name = "recovervolumeresponse"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/RemoveResourceDetailCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/RemoveResourceDetailCmd.java index 98fe6a7e821..bad839f8ac7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/RemoveResourceDetailCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/RemoveResourceDetailCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -31,7 +30,6 @@ import com.cloud.server.ResourceTag; @APICommand(name = "removeResourceDetail", description = "Removes detail for the Resource.", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RemoveResourceDetailCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RemoveResourceDetailCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java index 0daf141ba4a..eb89115cf46 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -44,7 +43,6 @@ import com.cloud.user.Account; @APICommand(name = "resizeVolume", description = "Resizes a volume", responseObject = VolumeResponse.class, responseView = ResponseView.Restricted, entityType = {Volume.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ResizeVolumeCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ResizeVolumeCmd.class.getName()); private static final String s_name = "resizevolumeresponse"; @@ -75,6 +73,10 @@ public class ResizeVolumeCmd extends BaseAsyncCmd implements UserCmd { description = "new disk offering id") private Long newDiskOfferingId; + @Parameter(name = ApiConstants.AUTO_MIGRATE, type = CommandType.BOOLEAN, required = false, + description = "Flag to allow automatic migration of the volume to another suitable storage pool that accommodates the new size", since = "4.20.1") + private Boolean autoMigrate; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -103,6 +105,10 @@ public class ResizeVolumeCmd extends BaseAsyncCmd implements UserCmd { return getEntityId(); } + public void setId(Long id) { + this.id = id; + } + public Long getMinIops() { return minIops; } @@ -115,6 +121,10 @@ public class ResizeVolumeCmd extends BaseAsyncCmd implements UserCmd { return size; } + public void setSize(Long size) { + this.size = size; + } + public boolean isShrinkOk() { return shrinkOk; } @@ -123,6 +133,10 @@ public class ResizeVolumeCmd extends BaseAsyncCmd implements UserCmd { return newDiskOfferingId; } + public boolean getAutoMigrate() { + return autoMigrate == null ? false : autoMigrate; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -195,10 +209,10 @@ public class ResizeVolumeCmd extends BaseAsyncCmd implements UserCmd { volume = _volumeService.resizeVolume(this); } catch (ResourceAllocationException ex) { - s_logger.error(ex.getMessage()); + logger.error(ex.getMessage()); throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage()); } catch (InvalidParameterValueException ex) { - s_logger.info(ex.getMessage()); + logger.info(ex.getMessage()); throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, ex.getMessage()); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java index e7782674828..22b819c8cba 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.volume; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -41,7 +40,6 @@ import com.cloud.storage.Volume; @APICommand(name = "updateVolume", description = "Updates the volume.", responseObject = VolumeResponse.class, responseView = ResponseView.Restricted, entityType = {Volume.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateVolumeCmd extends BaseAsyncCustomIdCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVolumeCmd.class.getName()); private static final String s_name = "updatevolumeresponse"; ///////////////////////////////////////////////////// @@ -79,6 +77,14 @@ public class UpdateVolumeCmd extends BaseAsyncCustomIdCmd implements UserCmd { @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "new name of the volume", since = "4.16") private String name; + @Parameter(name = ApiConstants.DELETE_PROTECTION, + type = CommandType.BOOLEAN, since = "4.20.0", + description = "Set delete protection for the volume. If true, The volume " + + "will be protected from deletion. Note: If the volume is managed by " + + "another service like autoscaling groups or CKS, delete protection will be " + + "ignored.") + private Boolean deleteProtection; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -111,6 +117,10 @@ public class UpdateVolumeCmd extends BaseAsyncCustomIdCmd implements UserCmd { return name; } + public Boolean getDeleteProtection() { + return deleteProtection; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -170,7 +180,7 @@ public class UpdateVolumeCmd extends BaseAsyncCustomIdCmd implements UserCmd { public void execute() { CallContext.current().setEventDetails("Volume Id: " + this._uuidMgr.getUuid(Volume.class, getId())); Volume result = _volumeService.updateVolume(getId(), getPath(), getState(), getStorageId(), getDisplayVolume(), - getCustomId(), getEntityOwnerId(), getChainInfo(), getName()); + getDeleteProtection(), getCustomId(), getEntityOwnerId(), getChainInfo(), getName()); if (result != null) { VolumeResponse response = _responseGenerator.createVolumeResponse(getResponseView(), result); response.setResponseName(getCommandName()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java index c622081079d..339c276d59e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java @@ -31,7 +31,6 @@ import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter; import com.cloud.event.EventTypes; @@ -45,7 +44,6 @@ import com.cloud.storage.Volume; @APICommand(name = "uploadVolume", description = "Uploads a data disk.", responseObject = VolumeResponse.class, responseView = ResponseView.Restricted, entityType = {Volume.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UploadVolumeCmd extends BaseAsyncCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(UploadVolumeCmd.class.getName()); private static final String s_name = "uploadvolumeresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreatePrivateGatewayCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreatePrivateGatewayCmd.java index cf1315c9d55..dceaabf648d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreatePrivateGatewayCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreatePrivateGatewayCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vpc; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -52,7 +51,6 @@ import com.cloud.network.vpc.VpcGateway; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(CreatePrivateGatewayCmd.class.getName()); private static final String s_name = "createprivategatewayresponse"; @@ -149,11 +147,11 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd implements UserC try { result = _vpcService.createVpcPrivateGateway(this); } catch (InsufficientCapacityException ex) { - s_logger.info(ex); - s_logger.trace(ex); + logger.info(ex); + logger.trace(ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java index 68d7a77d946..b28c02cb800 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vpc; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -42,7 +41,6 @@ import com.cloud.network.vpc.VpcGateway; @APICommand(name = "createStaticRoute", description = "Creates a static route", responseObject = StaticRouteResponse.class, entityType = {StaticRoute.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateStaticRouteCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateStaticRouteCmd.class.getName()); @Parameter(name = ApiConstants.GATEWAY_ID, type = CommandType.UUID, @@ -75,8 +73,8 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd { setEntityId(result.getId()); setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException ex) { - s_logger.info("Network rule conflict: " + ex.getMessage()); - s_logger.trace("Network rule conflict: ", ex); + logger.info("Network rule conflict: " + ex.getMessage()); + logger.trace("Network rule conflict: ", ex); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java index 39f2b32751d..2f62d0d7210 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.vpc; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -46,7 +45,6 @@ import com.cloud.network.vpc.Vpc; @APICommand(name = "createVPC", description = "Creates a VPC", responseObject = VpcResponse.class, responseView = ResponseView.Restricted, entityType = {Vpc.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateVPCCmd extends BaseAsyncCreateCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(CreateVPCCmd.class.getName()); private static final String s_name = "createvpcresponse"; // /////////////////////////////////////////////////// @@ -77,10 +75,15 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd implements UserCmd { private String displayText; - @Parameter(name = ApiConstants.CIDR, type = CommandType.STRING, required = true, description = "the cidr of the VPC. All VPC " + - "guest networks' cidrs should be within this CIDR") + @Parameter(name = ApiConstants.CIDR, type = CommandType.STRING, + description = "the cidr of the VPC. All VPC guest networks' cidrs should be within this CIDR") private String cidr; + @Parameter(name = ApiConstants.CIDR_SIZE, type = CommandType.INTEGER, + description = "the CIDR size of VPC. For regular users, this is required for VPC with ROUTED mode.", + since = "4.20.0") + private Integer cidrSize; + @Parameter(name = ApiConstants.VPC_OFF_ID, type = CommandType.UUID, entityType = VpcOfferingResponse.class, required = true, description = "the ID of the VPC offering") private Long vpcOffering; @@ -119,6 +122,9 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd implements UserCmd { since = "4.19") private String sourceNatIP; + @Parameter(name=ApiConstants.AS_NUMBER, type=CommandType.LONG, since = "4.20.0", description="the AS Number of the VPC tiers") + private Long asNumber; + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// @@ -143,6 +149,10 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd implements UserCmd { return cidr; } + public Integer getCidrSize() { + return cidrSize; + } + public String getDisplayText() { return StringUtils.isEmpty(displayText) ? vpcName : displayText; } @@ -191,6 +201,10 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd implements UserCmd { return sourceNatIP; } + public Long getAsNumber() { + return asNumber; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -213,14 +227,14 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd implements UserCmd { _vpcService.startVpc(this); vpc = _entityMgr.findById(Vpc.class, getEntityId()); } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { - s_logger.info(ex); - s_logger.trace(ex); + logger.info(ex); + logger.trace(ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java index 6210d80586f..01b6aae425b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vpc; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -40,7 +39,6 @@ import com.cloud.network.vpc.StaticRoute; @APICommand(name = "deleteStaticRoute", description = "Deletes a static route", responseObject = SuccessResponse.class, entityType = {StaticRoute.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteStaticRouteCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteStaticRouteCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java index f408e32f62d..c35d9084bcc 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.vpc; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteVPC", description = "Deletes a VPC", responseObject = SuccessResponse.class, entityType = {Vpc.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteVPCCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVPCCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -81,10 +79,10 @@ public class DeleteVPCCmd extends BaseAsyncCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete VPC"); } } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListPrivateGatewaysCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListPrivateGatewaysCmd.java index 8813cccc779..2304cef3c6d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListPrivateGatewaysCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListPrivateGatewaysCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.vpc; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -39,7 +38,6 @@ import com.cloud.utils.Pair; responseView = ResponseObject.ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListPrivateGatewaysCmd extends BaseListProjectAndAccountResourcesCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListPrivateGatewaysCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java index c0f95fcd361..f48e113286a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; import com.cloud.network.vpc.VpcOffering; import com.cloud.utils.Pair; @@ -35,7 +34,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listVPCOfferings", description = "Lists VPC offerings", responseObject = VpcOfferingResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListVPCOfferingsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListVPCOfferingsCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java index 76cbcca61bb..d128be1414d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java @@ -33,7 +33,6 @@ import org.apache.cloudstack.api.response.ResourceIconResponse; import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; import com.cloud.network.vpc.Vpc; import com.cloud.utils.Pair; @@ -42,7 +41,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listVPCs", description = "Lists VPCs", responseObject = VpcResponse.class, responseView = ResponseView.Restricted, entityType = {Vpc.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListVPCsCmd extends BaseListTaggedResourcesCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListVPCsCmd.class.getName()); private static final String s_name = "listvpcsresponse"; ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java index 04946619c0a..5ccd496eeb4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.VpcResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,7 +38,6 @@ import com.cloud.user.Account; @APICommand(name = "restartVPC", description = "Restarts a VPC", responseObject = SuccessResponse.class, entityType = {Vpc.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RestartVPCCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RestartVPCCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -101,14 +99,14 @@ public class RestartVPCCmd extends BaseAsyncCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to restart VPC"); } } catch (final ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (final ConcurrentOperationException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (final InsufficientCapacityException ex) { - s_logger.info(ex); - s_logger.trace(ex); + logger.info(ex); + logger.trace(ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java index d4c7d0d5c59..6fcfb5311f6 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.vpc; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.acl.SecurityChecker.AccessType; @@ -42,7 +41,6 @@ import com.cloud.user.Account; @APICommand(name = "updateVPC", description = "Updates a VPC", responseObject = VpcResponse.class, responseView = ResponseView.Restricted, entityType = {Vpc.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateVPCCmd extends BaseAsyncCustomIdCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVPCCmd.class.getName()); private static final String s_name = "updatevpcresponse"; ///////////////////////////////////////////////////// @@ -129,11 +127,11 @@ public class UpdateVPCCmd extends BaseAsyncCustomIdCmd implements UserCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update VPC"); } } catch (final ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (final InsufficientCapacityException ex) { - s_logger.info(ex); - s_logger.trace(ex); + logger.info(ex); + logger.trace(ex); throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java index 8f0fb7bc096..59ba7e94b04 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vpn; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "addVpnUser", description = "Adds vpn users", responseObject = VpnUsersResponse.class, entityType = {VpnUser.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AddVpnUserCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(AddVpnUserCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java index 8ecf4b051ce..417ba2773c4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.vpn; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -41,7 +40,6 @@ import com.cloud.network.RemoteAccessVpn; @APICommand(name = "createRemoteAccessVpn", description = "Creates a l2tp/ipsec remote access vpn", responseObject = RemoteAccessVpnResponse.class, entityType = {RemoteAccessVpn.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateRemoteAccessVpnCmd.class.getName()); ///////////////////////////////////////////////////// @@ -148,8 +146,8 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create remote access vpn"); } } catch (NetworkRuleConflictException e) { - s_logger.info("Network rule conflict: " + e.getMessage()); - s_logger.trace("Network Rule Conflict: ", e); + logger.info("Network rule conflict: " + e.getMessage()); + logger.trace("Network Rule Conflict: ", e); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } } @@ -166,7 +164,7 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create remote access vpn"); } } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java index 84aaafc60ed..0b5c46d36eb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vpn; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -41,7 +40,6 @@ import com.cloud.network.vpc.Vpc; @APICommand(name = "createVpnConnection", description = "Create site to site vpn connection", responseObject = Site2SiteVpnConnectionResponse.class, entityType = {Site2SiteVpnConnection.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateVpnConnectionCmd.class.getName()); ///////////////////////////////////////////////////// @@ -135,8 +133,8 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create site to site vpn connection"); } } catch (NetworkRuleConflictException e) { - s_logger.info("Network rule conflict: " + e.getMessage()); - s_logger.trace("Network Rule Conflict: ", e); + logger.info("Network rule conflict: " + e.getMessage()); + logger.trace("Network Rule Conflict: ", e); throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } } @@ -153,7 +151,7 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create site to site vpn connection"); } } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java index 88c6c12fac7..a2fa0d9829c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -37,7 +36,6 @@ import com.cloud.network.Site2SiteCustomerGateway; @APICommand(name = "createVpnCustomerGateway", description = "Creates site to site vpn customer gateway", responseObject = Site2SiteCustomerGatewayResponse.class, entityType = {Site2SiteCustomerGateway.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateVpnCustomerGatewayCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateVpnCustomerGatewayCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java index c354e972737..6f31176c4ff 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java @@ -31,12 +31,10 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; @APICommand(name = "createVpnGateway", description = "Creates site to site vpn local gateway", responseObject = Site2SiteVpnGatewayResponse.class, entityType = {Site2SiteVpnGateway.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class CreateVpnGatewayCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateVpnGatewayCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java index dfc80b2fabc..bf8d0157923 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.vpn; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import com.cloud.network.RemoteAccessVpn; @APICommand(name = "deleteRemoteAccessVpn", description = "Destroys a l2tp/ipsec remote access vpn", responseObject = SuccessResponse.class, entityType = {RemoteAccessVpn.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteRemoteAccessVpnCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java index 8a57dfc8edd..2528d93a042 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vpn; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteVpnConnection", description = "Delete site to site vpn connection", responseObject = SuccessResponse.class, entityType = {Site2SiteVpnConnection.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteVpnConnectionCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVpnConnectionCmd.class.getName()); ///////////////////////////////////////////////////// @@ -86,7 +84,7 @@ public class DeleteVpnConnectionCmd extends BaseAsyncCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete site to site VPN connection"); } } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java index e2f0aee90ec..2b657fd3c08 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.api.command.user.vpn; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteVpnCustomerGateway", description = "Delete site to site vpn customer gateway", responseObject = SuccessResponse.class, entityType = {Site2SiteCustomerGateway.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVpnCustomerGatewayCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java index b7acc5c4506..27ded12dc58 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vpn; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteVpnGateway", description = "Delete site to site vpn gateway", responseObject = SuccessResponse.class, entityType = {Site2SiteVpnGateway.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeleteVpnGatewayCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVpnGatewayCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListRemoteAccessVpnsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListRemoteAccessVpnsCmd.java index 1f2f95188e7..4efc70c8419 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListRemoteAccessVpnsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListRemoteAccessVpnsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -37,7 +36,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listRemoteAccessVpns", description = "Lists remote access vpns", responseObject = RemoteAccessVpnResponse.class, entityType = {RemoteAccessVpn.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListRemoteAccessVpnsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListRemoteAccessVpnsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnConnectionsCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnConnectionsCmd.java index 763a374645b..aeeae44d004 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnConnectionsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnConnectionsCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -36,7 +35,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listVpnConnections", description = "Lists site to site vpn connection gateways", responseObject = Site2SiteVpnConnectionResponse.class, entityType = {Site2SiteVpnConnection.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListVpnConnectionsCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListVpnConnectionsCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnCustomerGatewaysCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnCustomerGatewaysCmd.java index b66c47899f7..258a8a753eb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnCustomerGatewaysCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnCustomerGatewaysCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listVpnCustomerGateways", description = "Lists site to site vpn customer gateways", responseObject = Site2SiteCustomerGatewayResponse.class, entityType = {Site2SiteCustomerGateway.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListVpnCustomerGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListVpnCustomerGatewaysCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnGatewaysCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnGatewaysCmd.java index fb9c8262003..d30fbf8d32b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnGatewaysCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnGatewaysCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -36,7 +35,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listVpnGateways", description = "Lists site 2 site vpn gateways", responseObject = Site2SiteVpnGatewayResponse.class, entityType = {Site2SiteVpnGateway.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListVpnGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListVpnGatewaysCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnUsersCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnUsersCmd.java index 9f8581eb014..48591765ec3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnUsersCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ListVpnUsersCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -34,7 +33,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listVpnUsers", description = "Lists vpn users", responseObject = VpnUsersResponse.class, entityType = {VpnUser.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListVpnUsersCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListVpnUsersCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java index 4adf385b127..0697987b04d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vpn; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -37,7 +36,6 @@ import com.cloud.user.Account; @APICommand(name = "removeVpnUser", description = "Removes vpn user", responseObject = SuccessResponse.class, entityType = {VpnUser.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class RemoveVpnUserCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RemoveVpnUserCmd.class.getName()); ///////////////////////////////////////////////////// @@ -106,10 +104,10 @@ public class RemoveVpnUserCmd extends BaseAsyncCmd { public void execute() { Account owner = _accountService.getAccount(getEntityOwnerId()); long ownerId = owner.getId(); - boolean result = _ravService.removeVpnUser(ownerId, userName, CallContext.current().getCallingAccount()); + boolean result = _ravService.removeVpnUser(owner, userName, CallContext.current().getCallingAccount()); if (!result) { String errorMessage = String.format("Failed to remove VPN user=[%s]. VPN owner id=[%s].", userName, ownerId); - s_logger.error(errorMessage); + logger.error(errorMessage); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMessage); } @@ -118,13 +116,13 @@ public class RemoveVpnUserCmd extends BaseAsyncCmd { appliedVpnUsers = _ravService.applyVpnUsers(ownerId, userName, true); } catch (ResourceUnavailableException ex) { String errorMessage = String.format("Failed to refresh VPN user=[%s] due to resource unavailable. VPN owner id=[%s].", userName, ownerId); - s_logger.error(errorMessage, ex); + logger.error(errorMessage, ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMessage, ex); } if (!appliedVpnUsers) { String errorMessage = String.format("Failed to refresh VPN user=[%s]. VPN owner id=[%s].", userName, ownerId); - s_logger.debug(errorMessage); + logger.debug(errorMessage); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMessage); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java index c63126578f2..736295b4119 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java @@ -16,7 +16,6 @@ // under the License. package org.apache.cloudstack.api.command.user.vpn; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "resetVpnConnection", description = "Reset site to site vpn connection", responseObject = Site2SiteVpnConnectionResponse.class, entityType = {Site2SiteVpnConnection.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ResetVpnConnectionCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ResetVpnConnectionCmd.class.getName()); ///////////////////////////////////////////////////// @@ -105,7 +103,7 @@ public class ResetVpnConnectionCmd extends BaseAsyncCmd { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to reset site to site VPN connection"); } } catch (ResourceUnavailableException ex) { - s_logger.warn("Exception: ", ex); + logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateRemoteAccessVpnCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateRemoteAccessVpnCmd.java index d5b36f662f9..defde70b63a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateRemoteAccessVpnCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateRemoteAccessVpnCmd.java @@ -23,7 +23,6 @@ import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -32,7 +31,6 @@ import com.cloud.network.RemoteAccessVpn; @APICommand(name = "updateRemoteAccessVpn", description = "Updates remote access vpn", responseObject = RemoteAccessVpnResponse.class, since = "4.4", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateRemoteAccessVpnCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateRemoteAccessVpnCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnConnectionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnConnectionCmd.java index 67cb65bdb93..62dd6167b75 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnConnectionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnConnectionCmd.java @@ -22,7 +22,6 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteVpnConnection; @@ -31,7 +30,6 @@ import com.cloud.user.Account; @APICommand(name = "updateVpnConnection", description = "Updates site to site vpn connection", responseObject = Site2SiteVpnConnectionResponse.class, since = "4.4", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateVpnConnectionCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVpnConnectionCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java index 179bc0407b4..9f3ac2ec436 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java @@ -18,7 +18,6 @@ package org.apache.cloudstack.api.command.user.vpn; import org.apache.cloudstack.api.ApiArgValidator; import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -36,7 +35,6 @@ import com.cloud.network.Site2SiteCustomerGateway; @APICommand(name = "updateVpnCustomerGateway", description = "Update site to site vpn customer gateway", responseObject = Site2SiteCustomerGatewayResponse.class, entityType = {Site2SiteCustomerGateway.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVpnCustomerGatewayCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnGatewayCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnGatewayCmd.java index c69bbb5689f..9fe5ae0480f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnGatewayCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnGatewayCmd.java @@ -22,7 +22,6 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseAsyncCustomIdCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; -import org.apache.log4j.Logger; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteVpnGateway; @@ -31,7 +30,6 @@ import com.cloud.user.Account; @APICommand(name = "updateVpnGateway", description = "Updates site to site vpn local gateway", responseObject = Site2SiteVpnGatewayResponse.class, since = "4.4", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UpdateVpnGatewayCmd extends BaseAsyncCustomIdCmd { - public static final Logger s_logger = Logger.getLogger(UpdateVpnGatewayCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/zone/ListZonesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/zone/ListZonesCmd.java index c29f3a85106..8d371bb6761 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/zone/ListZonesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/zone/ListZonesCmd.java @@ -29,14 +29,10 @@ import org.apache.cloudstack.api.command.user.UserCmd; import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.log4j.Logger; @APICommand(name = "listZones", description = "Lists zones", responseObject = ZoneResponse.class, responseView = ResponseView.Restricted, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListZonesCmd extends BaseListCmd implements UserCmd { - public static final Logger s_logger = Logger.getLogger(ListZonesCmd.class.getName()); - - private static final String s_name = "listzonesresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -115,11 +111,6 @@ public class ListZonesCmd extends BaseListCmd implements UserCmd { /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override - public String getCommandName() { - return s_name; - } - @Override public void execute() { ListResponse response = _queryService.listDataCenters(this); diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ASNRangeResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ASNRangeResponse.java new file mode 100644 index 00000000000..86dab54ca6b --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/ASNRangeResponse.java @@ -0,0 +1,93 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.response; + +import com.cloud.bgp.ASNumberRange; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + +import java.util.Date; + +@EntityReference(value = ASNumberRange.class) +public class ASNRangeResponse extends BaseResponse { + + @SerializedName(ApiConstants.ID) + @Param(description = "ID of the AS Number Range") + private String id; + + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "Zone ID") + private String zoneId; + + @SerializedName(ApiConstants.START_ASN) + @Param(description = "Start AS Number") + private Long startASNumber; + + @SerializedName(ApiConstants.END_ASN) + @Param(description = "End AS Number") + private Long endASNumber; + + @SerializedName(ApiConstants.CREATED) + @Param(description = "Created date") + private Date created; + + public ASNRangeResponse() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getZoneId() { + return zoneId; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; + } + + public Long getStartASNumber() { + return startASNumber; + } + + public void setStartASNumber(Long startASNumber) { + this.startASNumber = startASNumber; + } + + public Long getEndASNumber() { + return endASNumber; + } + + public void setEndASNumber(Long endASNumber) { + this.endASNumber = endASNumber; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ASNumberResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ASNumberResponse.java new file mode 100644 index 00000000000..45884250984 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/ASNumberResponse.java @@ -0,0 +1,237 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.response; + +import com.cloud.bgp.ASNumber; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + +import java.util.Date; + +@EntityReference(value = ASNumber.class) +public class ASNumberResponse extends BaseResponse { + + @SerializedName(ApiConstants.ID) + @Param(description = "ID of the AS Number") + private String id; + + @SerializedName(ApiConstants.ACCOUNT_ID) + @Param(description = "Account ID") + private String accountId; + + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the account name") + private String accountName; + + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "Domain ID") + private String domainId; + + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "the domain name") + private String domainName; + + @SerializedName(ApiConstants.AS_NUMBER) + @Param(description = "AS Number") + private Long asNumber; + + @SerializedName(ApiConstants.ASN_RANGE_ID) + @Param(description = "AS Number ID") + private String asNumberRangeId; + + @SerializedName(ApiConstants.ASN_RANGE) + @Param(description = "AS Number Range") + private String asNumberRange; + + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "Zone ID") + private String zoneId; + + @SerializedName(ApiConstants.ZONE_NAME) + @Param(description = "the zone name of the AS Number range") + private String zoneName; + + @SerializedName("allocated") + @Param(description = "Allocated Date") + private Date allocated; + + @SerializedName(ApiConstants.ALLOCATION_STATE) + @Param(description = "Allocation state") + private String allocationState; + + @SerializedName(ApiConstants.ASSOCIATED_NETWORK_ID) + @Param(description = "Network ID") + private String associatedNetworkId; + + @SerializedName(ApiConstants.ASSOCIATED_NETWORK_NAME) + @Param(description = "Network Name") + private String associatedNetworkName; + + @SerializedName((ApiConstants.VPC_ID)) + @Param(description = "VPC ID") + private String vpcId; + + @SerializedName(ApiConstants.VPC_NAME) + @Param(description = "VPC Name") + private String vpcName; + + @SerializedName(ApiConstants.CREATED) + @Param(description = "Created Date") + private Date created; + + public ASNumberResponse() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public String getDomainId() { + return domainId; + } + + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public Long getAsNumber() { + return asNumber; + } + + public void setAsNumber(Long asNumber) { + this.asNumber = asNumber; + } + + public String getAsNumberRangeId() { + return asNumberRangeId; + } + + public void setAsNumberRangeId(String asNumberRangeId) { + this.asNumberRangeId = asNumberRangeId; + } + + public String getAsNumberRange() { + return asNumberRange; + } + + public void setAsNumberRange(String asNumberRange) { + this.asNumberRange = asNumberRange; + } + + public String getZoneId() { + return zoneId; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; + } + + public String getZoneName() { + return zoneName; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public Date getAllocated() { + return allocated; + } + + public void setAllocated(Date allocatedDate) { + this.allocated = allocatedDate; + } + + public String getAllocationState() { + return allocationState; + } + + public void setAllocationState(String allocated) { + allocationState = allocated; + } + + public String getAssociatedNetworkId() { + return associatedNetworkId; + } + + public void setAssociatedNetworkId(String associatedNetworkId) { + this.associatedNetworkId = associatedNetworkId; + } + + public String getAssociatedNetworkName() { + return associatedNetworkName; + } + + public void setAssociatedNetworkName(String associatedNetworkName) { + this.associatedNetworkName = associatedNetworkName; + } + + public String getVpcId() { + return vpcId; + } + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; + } + + public String getVpcName() { + return vpcName; + } + + public void setVpcName(String vpcName) { + this.vpcName = vpcName; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/AccountResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/AccountResponse.java index 7ffe7d095e4..d761d7c0394 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/AccountResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/AccountResponse.java @@ -267,6 +267,14 @@ public class AccountResponse extends BaseResponse implements ResourceLimitAndCou @Param(description = "Base64 string representation of the resource icon", since = "4.16.0.0") ResourceIconResponse icon; + @SerializedName(ApiConstants.TAGGED_RESOURCES) + @Param(description = "The tagged resource limit and count for the account", since = "4.20.0") + List taggedResources; + + @SerializedName(ApiConstants.API_KEY_ACCESS) + @Param(description = "whether api key access is Enabled, Disabled or set to Inherit (it inherits the value from the parent)", since = "4.20.1.0") + ApiConstants.ApiKeyAccess apiKeyAccess; + @Override public String getObjectId() { return id; @@ -456,7 +464,7 @@ public class AccountResponse extends BaseResponse implements ResourceLimitAndCou @Override public void setVpcLimit(String vpcLimit) { - this.vpcLimit = networkLimit; + this.vpcLimit = vpcLimit; } @Override @@ -545,4 +553,13 @@ public class AccountResponse extends BaseResponse implements ResourceLimitAndCou public void setResourceIconResponse(ResourceIconResponse icon) { this.icon = icon; } + + @Override + public void setTaggedResourceLimitsAndCounts(List taggedResourceLimitsAndCounts) { + this.taggedResources = taggedResourceLimitsAndCounts; + } + + public void setApiKeyAccess(Boolean apiKeyAccess) { + this.apiKeyAccess = ApiConstants.ApiKeyAccess.fromBoolean(apiKeyAccess); + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/AcquirePodIpCmdResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/AcquirePodIpCmdResponse.java index 77c4d0d3ffc..2226efd063d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/AcquirePodIpCmdResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/AcquirePodIpCmdResponse.java @@ -44,7 +44,7 @@ public class AcquirePodIpCmdResponse extends BaseResponse { @SerializedName(ApiConstants.NIC_ID) @Param(description = "the ID of the nic") - private Long instanceId; + private Long nicId; @SerializedName(ApiConstants.HOST_MAC) @Param(description = "MAC address of the pod the IP") @@ -58,8 +58,8 @@ public class AcquirePodIpCmdResponse extends BaseResponse { this.ipAddress = ipAddress; } - public void setInstanceId(Long instanceId) { - this.instanceId = instanceId; + public void setNicId(Long nicId) { + this.nicId = nicId; } public void setPodId(long podId) { @@ -82,8 +82,8 @@ public class AcquirePodIpCmdResponse extends BaseResponse { return id; } - public Long getInstanceId() { - return instanceId; + public Long getNicId() { + return nicId; } public long getPodId() { diff --git a/api/src/main/java/org/apache/cloudstack/api/response/BackupRepositoryResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/BackupRepositoryResponse.java new file mode 100644 index 00000000000..0db51f04034 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/BackupRepositoryResponse.java @@ -0,0 +1,142 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.response; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.backup.BackupRepository; + +import java.util.Date; + +@EntityReference(value = BackupRepository.class) +public class BackupRepositoryResponse extends BaseResponse { + + @SerializedName(ApiConstants.ID) + @Param(description = "the ID of the backup repository") + private String id; + + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "the Zone ID of the backup repository") + private String zoneId; + + @SerializedName(ApiConstants.ZONE_NAME) + @Param(description = "the Zone name of the backup repository") + private String zoneName; + + @SerializedName(ApiConstants.NAME) + @Param(description = "the name of the backup repository") + private String name; + + @SerializedName(ApiConstants.ADDRESS) + @Param(description = "the address / url of the backup repository") + private String address; + + @SerializedName(ApiConstants.PROVIDER) + @Param(description = "name of the provider") + private String providerName; + + @SerializedName(ApiConstants.TYPE) + @Param(description = "backup type") + private String type; + + @SerializedName(ApiConstants.CAPACITY_BYTES) + @Param(description = "capacity of the backup repository") + private Long capacityBytes; + + @SerializedName("created") + @Param(description = "the date and time the backup repository was added") + private Date created; + + public BackupRepositoryResponse() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getZoneId() { + return zoneId; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; + } + + public String getZoneName() { + return zoneName; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getProviderName() { + return providerName; + } + + public void setProviderName(String providerName) { + this.providerName = providerName; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Long getCapacityBytes() { + return capacityBytes; + } + + public void setCapacityBytes(Long capacityBytes) { + this.capacityBytes = capacityBytes; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/BgpPeerResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/BgpPeerResponse.java new file mode 100644 index 00000000000..344e65c6bad --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/BgpPeerResponse.java @@ -0,0 +1,200 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.response; + +import java.util.Date; +import java.util.Map; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.network.BgpPeer; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +@EntityReference(value = BgpPeer.class) +public class BgpPeerResponse extends BaseResponse { + @SerializedName(ApiConstants.ID) + @Param(description = "id of the bgp peer") + private String id; + + @SerializedName(ApiConstants.IP_ADDRESS) + @Param(description = "IPv4 address of bgp peer") + private String ip4Address; + + @SerializedName(ApiConstants.IP6_ADDRESS) + @Param(description = "IPv6 address of bgp peer") + private String ip6Address; + + @SerializedName(ApiConstants.AS_NUMBER) + @Param(description = "AS number of bgp peer") + private Long asNumber; + + @SerializedName(ApiConstants.PASSWORD) + @Param(description = "password of bgp peer") + private String password; + + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "id of zone to which the bgp peer belongs to." ) + private String zoneId; + + @SerializedName(ApiConstants.ZONE_NAME) + @Param(description = "name of zone to which the bgp peer belongs to." ) + private String zoneName; + + @SerializedName(ApiConstants.CREATED) + @Param(description = "date when this bgp peer was created." ) + private Date created; + + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the account of the bgp peer") + private String accountName; + + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "the domain ID of the bgp peer") + private String domainId; + + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "the domain name of the bgp peer") + private String domainName; + + @SerializedName(ApiConstants.PROJECT_ID) + @Param(description = "the project id of the bgp peer") + private String projectId; + + @SerializedName(ApiConstants.PROJECT) + @Param(description = "the project name of the bgp peer") + private String projectName; + + @SerializedName(ApiConstants.DETAILS) + @Param(description = "additional key/value details of the bgp peer") + private Map details; + + public void setId(String id) { + this.id = id; + } + + public void setIp4Address(String ip4Address) { + this.ip4Address = ip4Address; + } + + public void setIp6Address(String ip6Address) { + this.ip6Address = ip6Address; + } + + public void setAsNumber(Long asNumber) { + this.asNumber = asNumber; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public void setCreated(Date created) { + this.created = created; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public void setDetails(Map details) { + this.details = details; + } + + public String getId() { + return id; + } + + public String getIp4Address() { + return ip4Address; + } + + public String getIp6Address() { + return ip6Address; + } + + public Long getAsNumber() { + return asNumber; + } + + public String getPassword() { + return password; + } + + public String getZoneId() { + return zoneId; + } + + public String getZoneName() { + return zoneName; + } + + public Date getCreated() { + return created; + } + + public String getAccountName() { + return accountName; + } + + public String getDomainId() { + return domainId; + } + + public String getDomainName() { + return domainName; + } + + public String getProjectId() { + return projectId; + } + + public String getProjectName() { + return projectName; + } + + public Map getDetails() { + return details; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/BucketResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/BucketResponse.java index c66629c8e13..f2dd365452c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/BucketResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/BucketResponse.java @@ -102,7 +102,7 @@ public class BucketResponse extends BaseResponseWithTagInformation implements Co @Param(description = "Bucket Access Key") private String accessKey; - @SerializedName(ApiConstants.SECRET_KEY) + @SerializedName(ApiConstants.USER_SECRET_KEY) @Param(description = "Bucket Secret Key") private String secretKey; diff --git a/api/src/main/java/org/apache/cloudstack/api/response/CapabilitiesResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/CapabilitiesResponse.java index 83fb4f4b372..affa130d4b0 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/CapabilitiesResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/CapabilitiesResponse.java @@ -92,6 +92,10 @@ public class CapabilitiesResponse extends BaseResponse { @Param(description = "true if users can see all accounts within the same domain, false otherwise") private boolean allowUserViewAllDomainAccounts; + @SerializedName(ApiConstants.ALLOW_USER_FORCE_STOP_VM) + @Param(description = "true if users are allowed to force stop a vm, false otherwise", since = "4.20.0") + private boolean allowUserForceStopVM; + @SerializedName("kubernetesserviceenabled") @Param(description = "true if Kubernetes Service plugin is enabled, false otherwise") private boolean kubernetesServiceEnabled; @@ -124,10 +128,22 @@ public class CapabilitiesResponse extends BaseResponse { @Param(description = "the retention time for Instances disks stats", since = "4.18.0") private Integer instancesDisksStatsRetentionTime; + @SerializedName(ApiConstants.SHAREDFSVM_MIN_CPU_COUNT) + @Param(description = "the min CPU count for the service offering used by the shared filesystem instance", since = "4.20.0") + private Integer sharedFsVmMinCpuCount; + + @SerializedName(ApiConstants.SHAREDFSVM_MIN_RAM_SIZE) + @Param(description = "the min Ram size for the service offering used by the shared filesystem instance", since = "4.20.0") + private Integer sharedFsVmMinRamSize; + @SerializedName(ApiConstants.DYNAMIC_SCALING_ENABLED) @Param(description = "true if dynamically scaling for instances is enabled", since = "4.21.0") private Boolean dynamicScalingEnabled; + @SerializedName(ApiConstants.ADDITONAL_CONFIG_ENABLED) + @Param(description = "true if additional configurations or extraconfig can be passed to Instances", since = "4.20.2") + private Boolean additionalConfigEnabled; + public void setSecurityGroupsEnabled(boolean securityGroupsEnabled) { this.securityGroupsEnabled = securityGroupsEnabled; } @@ -196,6 +212,10 @@ public class CapabilitiesResponse extends BaseResponse { this.allowUserViewAllDomainAccounts = allowUserViewAllDomainAccounts; } + public void setAllowUserForceStopVM(boolean allowUserForceStopVM) { + this.allowUserForceStopVM = allowUserForceStopVM; + } + public void setKubernetesServiceEnabled(boolean kubernetesServiceEnabled) { this.kubernetesServiceEnabled = kubernetesServiceEnabled; } @@ -228,7 +248,19 @@ public class CapabilitiesResponse extends BaseResponse { this.customHypervisorDisplayName = customHypervisorDisplayName; } + public void setSharedFsVmMinCpuCount(Integer sharedFsVmMinCpuCount) { + this.sharedFsVmMinCpuCount = sharedFsVmMinCpuCount; + } + + public void setSharedFsVmMinRamSize(Integer sharedFsVmMinRamSize) { + this.sharedFsVmMinRamSize = sharedFsVmMinRamSize; + } + public void setDynamicScalingEnabled(Boolean dynamicScalingEnabled) { this.dynamicScalingEnabled = dynamicScalingEnabled; } + + public void setAdditionalConfigEnabled(Boolean additionalConfigEnabled) { + this.additionalConfigEnabled = additionalConfigEnabled; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/CapacityResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/CapacityResponse.java index e9724497c38..2d0e2158651 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/CapacityResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/CapacityResponse.java @@ -16,12 +16,11 @@ // under the License. package org.apache.cloudstack.api.response; -import com.google.gson.annotations.SerializedName; - import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; public class CapacityResponse extends BaseResponse { @SerializedName(ApiConstants.TYPE) @@ -72,6 +71,10 @@ public class CapacityResponse extends BaseResponse { @Param(description = "the percentage of capacity currently in use") private String percentUsed; + @SerializedName(ApiConstants.TAG) + @Param(description = "The tag for the capacity type", since = "4.20.0") + private String tag; + public Short getCapacityType() { return capacityType; } @@ -167,4 +170,8 @@ public class CapacityResponse extends BaseResponse { public void setPercentUsed(String percentUsed) { this.percentUsed = percentUsed; } + + public void setTag(String tag) { + this.tag = tag; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ClusterResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ClusterResponse.java index ca01a2012f6..1c69849239f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/ClusterResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/ClusterResponse.java @@ -91,6 +91,10 @@ public class ClusterResponse extends BaseResponseWithAnnotations { @Param(description = "Meta data associated with the zone (key/value pairs)") private Map resourceDetails; + @SerializedName(ApiConstants.ARCH) + @Param(description = "CPU Arch of the hosts in the cluster", since = "4.20") + private String arch; + public String getId() { return id; } @@ -247,4 +251,12 @@ public class ClusterResponse extends BaseResponseWithAnnotations { public void setCapacities(List capacities) { this.capacities = capacities; } + + public void setArch(String arch) { + this.arch = arch; + } + + public String getArch() { + return arch; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/DataCenterIpv4SubnetResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/DataCenterIpv4SubnetResponse.java new file mode 100644 index 00000000000..a1a87794a88 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/DataCenterIpv4SubnetResponse.java @@ -0,0 +1,151 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.response; + +import java.util.Date; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +@EntityReference(value = DataCenterIpv4GuestSubnet.class) +public class DataCenterIpv4SubnetResponse extends BaseResponse { + @SerializedName(ApiConstants.ID) + @Param(description = "id of the guest IPv4 subnet") + private String id; + + @SerializedName(ApiConstants.SUBNET) + @Param(description = "guest IPv4 subnet") + private String subnet; + + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "id of zone to which the IPv4 subnet belongs to." ) + private String zoneId; + + @SerializedName(ApiConstants.ZONE_NAME) + @Param(description = "name of zone to which the IPv4 subnet belongs to." ) + private String zoneName; + + @SerializedName(ApiConstants.CREATED) + @Param(description = "date when this IPv4 subnet was created." ) + private Date created; + + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the account of the IPv4 subnet") + private String accountName; + + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "the domain ID of the IPv4 subnet") + private String domainId; + + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "the domain name of the IPv4 subnet") + private String domainName; + + @SerializedName(ApiConstants.PROJECT_ID) + @Param(description = "the project id of the IPv4 subnet") + private String projectId; + + @SerializedName(ApiConstants.PROJECT) + @Param(description = "the project name of the IPv4 subnet") + private String projectName; + + public void setId(String id) { + this.id = id; + } + + public void setSubnet(String subnet) { + this.subnet = subnet; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public void setCreated(Date created) { + this.created = created; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public String getId() { + return id; + } + + public String getSubnet() { + return subnet; + } + + public String getZoneId() { + return zoneId; + } + + public String getZoneName() { + return zoneName; + } + + public Date getCreated() { + return created; + } + + public String getAccountName() { + return accountName; + } + + public String getDomainId() { + return domainId; + } + + public String getDomainName() { + return domainName; + } + + public String getProjectId() { + return projectId; + } + + public String getProjectName() { + return projectName; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/DiskOfferingResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/DiskOfferingResponse.java index 5b4434fbd8d..0fed9827ef1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/DiskOfferingResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/DiskOfferingResponse.java @@ -173,6 +173,10 @@ public class DiskOfferingResponse extends BaseResponseWithAnnotations { @Param(description = "additional key/value details tied with this disk offering", since = "4.17") private Map details; + @SerializedName(ApiConstants.SUITABLE_FOR_VM) + @Param(description = "Returns true if the disk offering is suitable for the given virtual machine for disk creation otherwise false", since = "4.20.0") + private Boolean suitableForVm; + public Boolean getDisplayOffering() { return displayOffering; } @@ -403,4 +407,8 @@ public class DiskOfferingResponse extends BaseResponseWithAnnotations { public void setDetails(Map details) { this.details = details; } + + public void setSuitableForVm(Boolean suitableForVm) { + this.suitableForVm = suitableForVm; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/DomainResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/DomainResponse.java index e4e409a40ee..7c6ad3a91c3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/DomainResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/DomainResponse.java @@ -26,6 +26,7 @@ import com.cloud.domain.Domain; import com.cloud.serializer.Param; import java.util.Date; +import java.util.List; import java.util.Map; @EntityReference(value = Domain.class) @@ -184,6 +185,10 @@ public class DomainResponse extends BaseResponseWithAnnotations implements Resou @Param(description = "details for the domain") private Map details; + @SerializedName(ApiConstants.TAGGED_RESOURCES) + @Param(description = "The tagged resource limit and count for the domain", since = "4.20.0") + List taggedResources; + public String getId() { return this.id; } @@ -447,4 +452,9 @@ public class DomainResponse extends BaseResponseWithAnnotations implements Resou public void setDetails(Map details) { this.details = details; } + + @Override + public void setTaggedResourceLimitsAndCounts(List taggedResourceLimitsAndCounts) { + this.taggedResources = taggedResourceLimitsAndCounts; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/DomainRouterResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/DomainRouterResponse.java index b23d0f4b527..4b5e886a16e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/DomainRouterResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/DomainRouterResponse.java @@ -245,6 +245,10 @@ public class DomainRouterResponse extends BaseResponseWithAnnotations implements @Param(description = "the version of the code / software in the router") private String softwareVersion; + @SerializedName(ApiConstants.ARCH) + @Param(description = "CPU arch of the router", since = "4.20.1") + private String arch; + public DomainRouterResponse() { nics = new LinkedHashSet(); } @@ -518,4 +522,8 @@ public class DomainRouterResponse extends BaseResponseWithAnnotations implements public void setSoftwareVersion(String softwareVersion) { this.softwareVersion = softwareVersion; } + + public void setArch(String arch) { + this.arch = arch; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/HostResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/HostResponse.java index 99aabd88913..62bcc07b16d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/HostResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/HostResponse.java @@ -222,6 +222,14 @@ public class HostResponse extends BaseResponseWithAnnotations { @Param(description = "comma-separated list of tags for the host") private String hostTags; + @SerializedName("explicithosttags") + @Param(description = "comma-separated list of explicit host tags for the host", since = "4.20.0") + private String explicitHostTags; + + @SerializedName("implicithosttags") + @Param(description = "comma-separated list of implicit host tags for the host", since = "4.20.0") + private String implicitHostTags; + @SerializedName(ApiConstants.IS_TAG_A_RULE) @Param(description = ApiConstants.PARAMETER_DESCRIPTION_IS_TAG_A_RULE) private Boolean isTagARule; @@ -282,6 +290,10 @@ public class HostResponse extends BaseResponseWithAnnotations { @Param(description = "true if the host supports instance conversion (using virt-v2v)", since = "4.19.1") private Boolean instanceConversionSupported; + @SerializedName(ApiConstants.ARCH) + @Param(description = "CPU Arch of the host", since = "4.20") + private String arch; + @Override public String getObjectId() { return this.getId(); @@ -463,6 +475,22 @@ public class HostResponse extends BaseResponseWithAnnotations { this.hostTags = hostTags; } + public String getExplicitHostTags() { + return explicitHostTags; + } + + public void setExplicitHostTags(String explicitHostTags) { + this.explicitHostTags = explicitHostTags; + } + + public String getImplicitHostTags() { + return implicitHostTags; + } + + public void setImplicitHostTags(String implicitHostTags) { + this.implicitHostTags = implicitHostTags; + } + public void setHasEnoughCapacity(Boolean hasEnoughCapacity) { this.hasEnoughCapacity = hasEnoughCapacity; } @@ -763,6 +791,14 @@ public class HostResponse extends BaseResponseWithAnnotations { isTagARule = tagARule; } + public void setArch(String arch) { + this.arch = arch; + } + + public String getArch() { + return arch; + } + public Long getCpuAllocatedValue() { return cpuAllocatedValue; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/HostTagResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/HostTagResponse.java index 4a924ea78a0..f772da6dcb6 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/HostTagResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/HostTagResponse.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.response; import com.google.gson.annotations.SerializedName; import com.cloud.serializer.Param; +import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; public class HostTagResponse extends BaseResponse { @@ -34,6 +35,10 @@ public class HostTagResponse extends BaseResponse { @Param(description = "the name of the host tag") private String name; + @SerializedName(ApiConstants.IS_IMPLICIT) + @Param(description = "true if the host tag is implicit", since = "4.20.0") + private boolean isImplicit; + public String getId() { return id; } @@ -57,4 +62,12 @@ public class HostTagResponse extends BaseResponse { public void setName(String name) { this.name = name; } + + public boolean isImplicit() { + return isImplicit; + } + + public void setImplicit(boolean implicit) { + isImplicit = implicit; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/IPAddressResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/IPAddressResponse.java index fe7a6c14d73..0018edc8638 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/IPAddressResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/IPAddressResponse.java @@ -171,6 +171,10 @@ public class IPAddressResponse extends BaseResponseWithAnnotations implements Co @Param(description="whether the ip address has Firewall/PortForwarding/LoadBalancing rules defined") private boolean hasRules; + @SerializedName(ApiConstants.FOR_SYSTEM_VMS) + @Param(description="true if range is dedicated for System VMs") + private boolean forSystemVms; + public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } @@ -324,4 +328,8 @@ public class IPAddressResponse extends BaseResponseWithAnnotations implements Co public void setHasRules(final boolean hasRules) { this.hasRules = hasRules; } + + public void setForSystemVms(boolean forSystemVms) { + this.forSystemVms = forSystemVms; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/Ipv4RouteResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/Ipv4RouteResponse.java new file mode 100644 index 00000000000..136c87971b7 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/Ipv4RouteResponse.java @@ -0,0 +1,59 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +public class Ipv4RouteResponse extends BaseResponse { + + @SerializedName(ApiConstants.SUBNET) + @Param(description = "the guest Ipv4 cidr for route") + private String subnet; + + @SerializedName(ApiConstants.GATEWAY) + @Param(description = "the outbound Ipv4 gateway") + private String gateway; + + public Ipv4RouteResponse() { + } + + public Ipv4RouteResponse(String subnet, String gateway) { + this.subnet = subnet; + this.gateway = gateway; + } + + public String getSubnet() { + return subnet; + } + + public void setSubnet(String subnet) { + this.subnet = subnet; + } + + public String getGateway() { + return gateway; + } + + public void setGateway(String gateway) { + this.gateway = gateway; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/Ipv4SubnetForGuestNetworkResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/Ipv4SubnetForGuestNetworkResponse.java new file mode 100644 index 00000000000..1430bcd059c --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/Ipv4SubnetForGuestNetworkResponse.java @@ -0,0 +1,199 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.response; + +import java.util.Date; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.network.Ipv4GuestSubnetNetworkMap; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +@EntityReference(value = Ipv4GuestSubnetNetworkMap.class) +public class Ipv4SubnetForGuestNetworkResponse extends BaseResponse { + @SerializedName(ApiConstants.ID) + @Param(description = "id of the IPv4 subnet for guest network") + private String id; + + @SerializedName(ApiConstants.PARENT_ID) + @Param(description = "id of the data center IPv4 subnet") + private String parentId; + + @SerializedName(ApiConstants.PARENT_SUBNET) + @Param(description = "subnet of the data center IPv4 subnet") + private String parentSubnet; + + @SerializedName(ApiConstants.SUBNET) + @Param(description = "subnet of the IPv4 network") + private String subnet; + + @SerializedName(ApiConstants.STATE) + @Param(description = "state of subnet of the IPv4 network") + private String state; + + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "id of zone to which the IPv4 subnet belongs to." ) + private String zoneId; + + @SerializedName(ApiConstants.ZONE_NAME) + @Param(description = "id of zone to which the IPv4 subnet belongs to." ) + private String zoneName; + + @SerializedName(ApiConstants.NETWORK_ID) + @Param(description = "id of network which the IPv4 subnet is associated with." ) + private String networkId; + + @SerializedName(ApiConstants.NETWORK_NAME) + @Param(description = "name of network which the IPv4 subnet is associated with." ) + private String networkName; + + @SerializedName(ApiConstants.VPC_ID) + @Param(description = "Id of the VPC which the IPv4 subnet is associated with.") + private String vpcId; + + @SerializedName(ApiConstants.VPC_NAME) + @Param(description = "Name of the VPC which the IPv4 subnet is associated with.") + private String vpcName; + + @SerializedName(ApiConstants.CREATED) + @Param(description = "date when this IPv4 subnet was created." ) + private Date created; + + @SerializedName(ApiConstants.REMOVED) + @Param(description = "date when this IPv4 subnet was removed." ) + private Date removed; + + @SerializedName(ApiConstants.ALLOCATED_TIME) + @Param(description = "date when this IPv4 subnet was allocated." ) + private Date allocatedTime; + + public void setId(String id) { + this.id = id; + } + + public void setParentId(String parentId) { + this.parentId = parentId; + } + + public void setParentSubnet(String parentSubnet) { + this.parentSubnet = parentSubnet; + } + + public void setSubnet(String subnet) { + this.subnet = subnet; + } + + public void setState(String state) { + this.state = state; + } + + public void setNetworkId(String networkId) { + this.networkId = networkId; + } + + public void setNetworkName(String networkName) { + this.networkName = networkName; + } + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; + } + + public void setVpcName(String vpcName) { + this.vpcName = vpcName; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public void setCreated(Date created) { + this.created = created; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public void setAllocatedTime(Date allocatedTime) { + this.allocatedTime = allocatedTime; + } + + public String getId() { + return id; + } + + public String getParentId() { + return parentId; + } + + public String getParentSubnet() { + return parentSubnet; + } + + public String getSubnet() { + return subnet; + } + + public String getState() { + return state; + } + + public String getZoneId() { + return zoneId; + } + + public String getZoneName() { + return zoneName; + } + + public String getNetworkId() { + return networkId; + } + + public String getNetworkName() { + return networkName; + } + + public String getVpcId() { + return vpcId; + } + + public String getVpcName() { + return vpcName; + } + + public Date getCreated() { + return created; + } + + public Date getRemoved() { + return removed; + } + + public Date getAllocatedTime() { + return allocatedTime; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ManagementServerResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ManagementServerResponse.java index a471045eb67..d3f1096d39e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/ManagementServerResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/ManagementServerResponse.java @@ -24,7 +24,9 @@ import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.EntityReference; import org.apache.cloudstack.management.ManagementServerHost.State; +import java.util.ArrayList; import java.util.Date; +import java.util.List; @EntityReference(value = ManagementServerHost.class) public class ManagementServerResponse extends BaseResponse { @@ -72,10 +74,19 @@ public class ManagementServerResponse extends BaseResponse { @Param(description = "the running OS kernel version for this Management Server") private String kernelVersion; + @Deprecated @SerializedName(ApiConstants.SERVICE_IP) - @Param(description = "the IP Address for this Management Server") + @Param(description = "the IP Address for this Management Server. This is deprecated, please use 'ipaddress' instead.") private String serviceIp; + @SerializedName(ApiConstants.IP_ADDRESS) + @Param(description = "the IP Address for this Management Server") + private String ipAddress; + + @SerializedName(ApiConstants.PEERS) + @Param(description = "the Management Server Peers") + private List peers; + public String getId() { return this.id; } @@ -120,6 +131,10 @@ public class ManagementServerResponse extends BaseResponse { return serviceIp; } + public String getIpAddress() { + return ipAddress; + } + public void setId(String id) { this.id = id; } @@ -168,7 +183,26 @@ public class ManagementServerResponse extends BaseResponse { this.serviceIp = serviceIp; } + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + public String getKernelVersion() { return kernelVersion; } + + public List getPeers() { + return peers; + } + + public void setPeers(List peers) { + this.peers = peers; + } + + public void addPeer(PeerManagementServerNodeResponse peer) { + if (peers == null) { + peers = new ArrayList<>(); + } + peers.add(peer); + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/NetworkOfferingResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/NetworkOfferingResponse.java index b92725d883e..81a8129ecb7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/NetworkOfferingResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/NetworkOfferingResponse.java @@ -99,10 +99,18 @@ public class NetworkOfferingResponse extends BaseResponseWithAnnotations { @Param(description = "true if network offering can be used by VPC networks only") private Boolean forVpc; + @SerializedName(ApiConstants.FOR_NSX) + @Param(description = "true if network offering can be used by NSX networks only") + private Boolean forNsx; + @SerializedName(ApiConstants.FOR_TUNGSTEN) @Param(description = "true if network offering can be used by Tungsten-Fabric networks only") private Boolean forTungsten; + @SerializedName(ApiConstants.NETWORK_MODE) + @Param(description = "Mode in which the network will operate. The valid values are NATTED and ROUTED") + private String networkMode; + @SerializedName(ApiConstants.IS_PERSISTENT) @Param(description = "true if network offering supports persistent networks, false otherwise") private Boolean isPersistent; @@ -127,6 +135,10 @@ public class NetworkOfferingResponse extends BaseResponseWithAnnotations { @Param(description = "true if network offering supports public access for guest networks", since = "4.10.0") private Boolean supportsPublicAccess; + @SerializedName(ApiConstants.SUPPORTS_INTERNAL_LB) + @Param(description = "true if network offering supports public access for guest networks", since = "4.20.0") + private Boolean supportsInternalLb; + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain ID(s) this disk offering belongs to. Ignore this information as it is not currently applicable.") private String domainId; @@ -147,6 +159,14 @@ public class NetworkOfferingResponse extends BaseResponseWithAnnotations { @Param(description = "the internet protocol of the network offering") private String internetProtocol; + @SerializedName(ApiConstants.SPECIFY_AS_NUMBER) + @Param(description = "true if network offering supports choosing AS numbers") + private Boolean specifyAsNumber; + + @SerializedName(ApiConstants.ROUTING_MODE) + @Param(description = "the routing mode for the network offering, supported types are Static or Dynamic.") + private String routingMode; + public void setId(String id) { this.id = id; } @@ -215,10 +235,18 @@ public class NetworkOfferingResponse extends BaseResponseWithAnnotations { this.forVpc = forVpc; } + public void setForNsx(Boolean forNsx) { + this.forNsx = forNsx; + } + public void setForTungsten(Boolean forTungsten) { this.forTungsten = forTungsten; } + public void setNetworkMode(String networkMode) { + this.networkMode = networkMode; + } + public void setIsPersistent(Boolean isPersistent) { this.isPersistent = isPersistent; } @@ -243,6 +271,10 @@ public class NetworkOfferingResponse extends BaseResponseWithAnnotations { this.supportsPublicAccess = supportsPublicAccess; } + public void setSupportsInternalLb(Boolean supportsInternalLb) { + this.supportsInternalLb = supportsInternalLb; + } + public String getDomainId() { return domainId; } @@ -282,4 +314,20 @@ public class NetworkOfferingResponse extends BaseResponseWithAnnotations { public void setInternetProtocol(String internetProtocol) { this.internetProtocol = internetProtocol; } + + public Boolean getSpecifyAsNumber() { + return specifyAsNumber; + } + + public void setSpecifyAsNumber(Boolean specifyAsNumber) { + this.specifyAsNumber = specifyAsNumber; + } + + public String getRoutingMode() { + return routingMode; + } + + public void setRoutingMode(String routingMode) { + this.routingMode = routingMode; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/NetworkProtocolResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/NetworkProtocolResponse.java new file mode 100644 index 00000000000..775333f7192 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/NetworkProtocolResponse.java @@ -0,0 +1,89 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.response; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +public class NetworkProtocolResponse extends BaseResponse { + @SerializedName(ApiConstants.INDEX) + @Param(description = "the index (ID, Value, Code, Type, Option, etc) of the protocol parameter") + private Integer index; + + @SerializedName(ApiConstants.NAME) + @Param(description = "the name of the protocol parameter") + private String name; + + @SerializedName(ApiConstants.DESCRIPTION) + @Param(description = "the description of the protocol parameter") + private String description; + + @SerializedName(ApiConstants.DETAILS) + @Param(description = "the details of the protocol parameter") + private Map details; + + public NetworkProtocolResponse(Integer index, String name, String description) { + this.index = index; + this.name = name; + this.description = description; + } + + public Integer getIndex() { + return index; + } + + public void setIndex(Integer index) { + this.index = index; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map getDetails() { + return details; + } + + public void setDetails(Map details) { + this.details = details; + } + + public void addDetail(String key, String value) { + if (this.details == null) { + this.details = new LinkedHashMap(); + } + this.details.put(key, value); + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/NetworkResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/NetworkResponse.java index d18c0e1266a..a1ffda72234 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/NetworkResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/NetworkResponse.java @@ -17,6 +17,7 @@ package org.apache.cloudstack.api.response; import java.util.Date; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -134,6 +135,14 @@ public class NetworkResponse extends BaseResponseWithAssociatedNetwork implement @Param(description = "The vlan of the network. This parameter is visible to ROOT admins only") private String vlan; + @SerializedName(ApiConstants.AS_NUMBER_ID) + @Param(description = "UUID of AS NUMBER", since = "4.20.0") + private String asNumberId; + + @SerializedName(ApiConstants.AS_NUMBER) + @Param(description = "AS NUMBER", since = "4.20.0") + private Long asNumber; + @SerializedName(ApiConstants.ACL_TYPE) @Param(description = "acl type - access type to the network") private String aclType; @@ -295,7 +304,7 @@ public class NetworkResponse extends BaseResponseWithAssociatedNetwork implement private String internetProtocol; @SerializedName(ApiConstants.IPV6_ROUTING) - @Param(description = "The routing mode of network offering", since = "4.17.0") + @Param(description = "The Ipv6 routing type of network offering", since = "4.17.0") private String ipv6Routing; @SerializedName(ApiConstants.IPV6_ROUTES) @@ -318,6 +327,18 @@ public class NetworkResponse extends BaseResponseWithAssociatedNetwork implement @Param(description = "the second IPv6 DNS for the network", since = "4.18.0") private String ipv6Dns2; + @SerializedName(ApiConstants.IPV4_ROUTING) + @Param(description = "The IPv4 routing type of network", since = "4.20.0") + private String ipv4Routing; + + @SerializedName(ApiConstants.IPV4_ROUTES) + @Param(description = "The routes for the network to ease adding route in upstream router", since = "4.20.0") + private Set ipv4Routes; + + @SerializedName(ApiConstants.BGP_PEERS) + @Param(description = "The BGP peers for the network", since = "4.20.0") + private Set bgpPeers; + public NetworkResponse() {} public Boolean getDisplayNetwork() { @@ -418,6 +439,14 @@ public class NetworkResponse extends BaseResponseWithAssociatedNetwork implement this.vlan = vlan; } + public void setAsNumber(long asNumber) { + this.asNumber = asNumber; + } + + public void setAsNumberId(String asNumberId) { + this.asNumberId = asNumberId; + } + public void setIsSystem(Boolean isSystem) { this.isSystem = isSystem; } @@ -631,6 +660,18 @@ public class NetworkResponse extends BaseResponseWithAssociatedNetwork implement this.internetProtocol = internetProtocol; } + public void setIpv4Routing(String ipv4Routing) { + this.ipv4Routing = ipv4Routing; + } + + public void setIpv4Routes(Set ipv4Routes) { + this.ipv4Routes = ipv4Routes; + } + + public void addIpv4Route(Ipv4RouteResponse ipv4Route) { + this.ipv4Routes.add(ipv4Route); + } + public void setIpv6Routing(String ipv6Routing) { this.ipv6Routing = ipv6Routing; } @@ -643,6 +684,17 @@ public class NetworkResponse extends BaseResponseWithAssociatedNetwork implement this.ipv6Routes.add(ipv6Route); } + public void setBgpPeers(Set bgpPeers) { + this.bgpPeers = bgpPeers; + } + + public void addBgpPeer(BgpPeerResponse bgpPeer) { + if (this.bgpPeers == null) { + this.setBgpPeers(new LinkedHashSet<>()); + } + this.bgpPeers.add(bgpPeer); + } + public Integer getPublicMtu() { return publicMtu; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/PeerManagementServerNodeResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/PeerManagementServerNodeResponse.java new file mode 100644 index 00000000000..802294171fa --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/PeerManagementServerNodeResponse.java @@ -0,0 +1,100 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.response; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.management.ManagementServerHost.State; + +import java.util.Date; + +public class PeerManagementServerNodeResponse extends BaseResponse { + + @SerializedName(ApiConstants.STATE) + @Param(description = "the state of the management server peer") + private State state; + + @SerializedName(ApiConstants.LAST_UPDATED) + @Param(description = "the last updated time of the management server peer state") + private Date lastUpdated; + + @SerializedName(ApiConstants.PEER_ID) + @Param(description = "the ID of the peer management server") + private String peerId; + + @SerializedName(ApiConstants.PEER_NAME) + @Param(description = "the name of the peer management server") + private String peerName; + + @SerializedName(ApiConstants.PEER_MSID) + @Param(description = "the management ID of the peer management server") + private String peerMsId; + + @SerializedName(ApiConstants.PEER_RUNID) + @Param(description = "the run ID of the peer management server") + private String peerRunId; + + @SerializedName(ApiConstants.PEER_STATE) + @Param(description = "the state of the peer management server") + private String peerState; + + @SerializedName(ApiConstants.PEER_SERVICE_IP) + @Param(description = "the IP Address for the peer Management Server") + private String peerServiceIp; + + @SerializedName(ApiConstants.PEER_SERVICE_PORT) + @Param(description = "the service port for the peer Management Server") + private String peerServicePort; + + public void setState(State state) { + this.state = state; + } + + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + public void setPeerId(String peerId) { + this.peerId = peerId; + } + + public void setPeerName(String peerName) { + this.peerName = peerName; + } + + public void setPeerMsId(String peerMsId) { + this.peerMsId = peerMsId; + } + + public void setPeerRunId(String peerRunId) { + this.peerRunId = peerRunId; + } + + public void setPeerState(String peerState) { + this.peerState = peerState; + } + + public void setPeerServiceIp(String peerServiceIp) { + this.peerServiceIp = peerServiceIp; + } + + public void setPeerServicePort(String peerServicePort) { + this.peerServicePort = peerServicePort; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ProjectResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ProjectResponse.java index c43dd09b127..1c63697559b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/ProjectResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/ProjectResponse.java @@ -216,6 +216,10 @@ public class ProjectResponse extends BaseResponse implements ResourceLimitAndCou @Param(description = "the date this project was created", since = "4.16.0") private Date created; + @SerializedName(ApiConstants.TAGGED_RESOURCES) + @Param(description = "The tagged resource limit and count for the project", since = "4.20.0") + List taggedResources; + public void setId(String id) { this.id = id; } @@ -447,4 +451,9 @@ public class ProjectResponse extends BaseResponse implements ResourceLimitAndCou public void setCreated(Date created) { this.created = created; } + + @Override + public void setTaggedResourceLimitsAndCounts(List taggedResourceLimitsAndCounts) { + this.taggedResources = taggedResourceLimitsAndCounts; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/PurgeExpungedResourcesResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/PurgeExpungedResourcesResponse.java new file mode 100644 index 00000000000..3807d0d5b16 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/PurgeExpungedResourcesResponse.java @@ -0,0 +1,39 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +public class PurgeExpungedResourcesResponse extends BaseResponse { + + @SerializedName(ApiConstants.RESOURCE_COUNT) + @Param(description = "The count of the purged expunged resources") + private Long resourceCount; + + public Long getResourceCount() { + return resourceCount; + } + + public void setResourceCount(Long resourceCount) { + this.resourceCount = resourceCount; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/RegisterResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/RegisterResponse.java index 5faedabfc16..dd17cc5cc8a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/RegisterResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/RegisterResponse.java @@ -18,19 +18,24 @@ package org.apache.cloudstack.api.response; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; public class RegisterResponse extends BaseResponse { - @SerializedName("apikey") + @SerializedName(ApiConstants.API_KEY) @Param(description = "the api key of the registered user", isSensitive = true) private String apiKey; - @SerializedName("secretkey") + @SerializedName(ApiConstants.SECRET_KEY) @Param(description = "the secret key of the registered user", isSensitive = true) private String secretKey; + @SerializedName(ApiConstants.API_KEY_ACCESS) + @Param(description = "whether api key access is allowed or not", isSensitive = true) + private Boolean apiKeyAccess; + public String getApiKey() { return apiKey; } @@ -46,4 +51,8 @@ public class RegisterResponse extends BaseResponse { public void setSecretKey(String secretKey) { this.secretKey = secretKey; } + + public void setApiKeyAccess(Boolean apiKeyAccess) { + this.apiKeyAccess = apiKeyAccess; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ResourceCountResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ResourceCountResponse.java index d7081884daf..74511a0f743 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/ResourceCountResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/ResourceCountResponse.java @@ -16,13 +16,12 @@ // under the License. package org.apache.cloudstack.api.response; -import com.cloud.configuration.Resource; -import com.google.gson.annotations.SerializedName; - import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; +import com.cloud.configuration.Resource; import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") public class ResourceCountResponse extends BaseResponse implements ControlledEntityResponse { @@ -58,10 +57,14 @@ public class ResourceCountResponse extends BaseResponse implements ControlledEnt @Param(description = "resource type name. Values include user_vm, public_ip, volume, snapshot, template, project, network, vpc, cpu, memory, primary_storage, secondary_storage.") private String resourceTypeName; - @SerializedName("resourcecount") - @Param(description = "resource count") + @SerializedName(ApiConstants.RESOURCE_COUNT) + @Param(description = "The resource count") private long resourceCount; + @SerializedName(ApiConstants.TAG) + @Param(description = "Tag for the resource", since = "4.20.0") + private String tag; + @Override public void setAccountName(String accountName) { this.accountName = accountName; @@ -101,4 +104,7 @@ public class ResourceCountResponse extends BaseResponse implements ControlledEnt this.projectName = projectName; } + public void setTag(String tag) { + this.tag = tag; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ResourceLimitAndCountResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ResourceLimitAndCountResponse.java index f247be834cb..f9e6df3a038 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/ResourceLimitAndCountResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/ResourceLimitAndCountResponse.java @@ -20,6 +20,8 @@ have limits and resource count **/ package org.apache.cloudstack.api.response; +import java.util.List; + public interface ResourceLimitAndCountResponse { public void setNetworkLimit(String networkLimit); @@ -92,4 +94,6 @@ public interface ResourceLimitAndCountResponse { public void setVmRunning(Integer vmRunning); + public void setTaggedResourceLimitsAndCounts(List taggedResourceLimitsAndCounts); + } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ResourceLimitResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ResourceLimitResponse.java index 7780d46f7f6..b5b03873f3f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/ResourceLimitResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/ResourceLimitResponse.java @@ -16,15 +16,14 @@ // under the License. package org.apache.cloudstack.api.response; -import com.cloud.configuration.Resource; -import com.google.gson.annotations.SerializedName; - import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.EntityReference; +import com.cloud.configuration.Resource; import com.cloud.configuration.ResourceLimit; import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; @EntityReference(value = ResourceLimit.class) @SuppressWarnings("unused") @@ -65,6 +64,10 @@ public class ResourceLimitResponse extends BaseResponse implements ControlledEnt @Param(description = "the project name of the resource limit") private String projectName; + @SerializedName(ApiConstants.TAG) + @Param(description = "The tag for the resource limit", since = "4.20.0") + private String tag; + @Override public void setAccountName(String accountName) { this.accountName = accountName; @@ -102,4 +105,8 @@ public class ResourceLimitResponse extends BaseResponse implements ControlledEnt public void setProjectId(String projectId) { this.projectId = projectId; } + + public void setTag(String tag) { + this.tag = tag; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/RoleResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/RoleResponse.java index 1861028f0ed..92e3b46139f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/RoleResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/RoleResponse.java @@ -36,6 +36,10 @@ public class RoleResponse extends BaseRoleResponse { @Param(description = "true if role is default, false otherwise") private Boolean isDefault; + @SerializedName(ApiConstants.STATE) + @Param(description = "the state of the role") + private String state; + public void setRoleType(RoleType roleType) { if (roleType != null) { this.roleType = roleType.name(); @@ -45,4 +49,8 @@ public class RoleResponse extends BaseRoleResponse { public void setIsDefault(Boolean isDefault) { this.isDefault = isDefault; } + + public void setState(String state) { + this.state = state; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ServiceOfferingResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ServiceOfferingResponse.java index c7740c19214..0622b936f6e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/ServiceOfferingResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/ServiceOfferingResponse.java @@ -234,6 +234,10 @@ public class ServiceOfferingResponse extends BaseResponseWithAnnotations { @Param(description = "true if virtual machine root disk will be encrypted on storage", since = "4.18") private Boolean encryptRoot; + @SerializedName(ApiConstants.PURGE_RESOURCES) + @Param(description = "Whether to cleanup VM and its associated resource upon expunge", since = "4.20") + private Boolean purgeResources; + public ServiceOfferingResponse() { } @@ -555,4 +559,8 @@ public class ServiceOfferingResponse extends BaseResponseWithAnnotations { } public void setEncryptRoot(Boolean encrypt) { this.encryptRoot = encrypt; } + + public void setPurgeResources(Boolean purgeResources) { + this.purgeResources = purgeResources; + } } diff --git a/server/src/main/java/com/cloud/api/query/vo/HostTagVO.java b/api/src/main/java/org/apache/cloudstack/api/response/SharedFSProviderResponse.java similarity index 55% rename from server/src/main/java/com/cloud/api/query/vo/HostTagVO.java rename to api/src/main/java/org/apache/cloudstack/api/response/SharedFSProviderResponse.java index 0a279e5c490..4d92945646f 100644 --- a/server/src/main/java/com/cloud/api/query/vo/HostTagVO.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/SharedFSProviderResponse.java @@ -14,48 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.query.vo; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +package org.apache.cloudstack.api.response; -import org.apache.cloudstack.api.InternalIdentity; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; -/** - * Storage Tags DB view. - * - */ -@Entity -@Table(name = "host_tags") -public class HostTagVO extends BaseViewVO implements InternalIdentity { - private static final long serialVersionUID = 1L; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; - @Id - @Column(name = "id") - private long id; - - @Column(name = "tag") +public class SharedFSProviderResponse extends BaseResponse { + @SerializedName(ApiConstants.NAME) + @Param(description = "the name of the shared filesystem provider") private String name; - @Column(name = "host_id") - long hostId; - - @Override - public long getId() { - return id; - } - public String getName() { return name; } - public long getHostId() { - return hostId; - } - - public void setHostId(long hostId) { - this.hostId = hostId; + public void setName(String name) { + this.name = name; } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/SharedFSResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/SharedFSResponse.java new file mode 100644 index 00000000000..bac348fe36e --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/SharedFSResponse.java @@ -0,0 +1,369 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponseWithTagInformation; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.storage.sharedfs.SharedFS; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +import java.util.ArrayList; +import java.util.List; + + +@EntityReference(value = SharedFS.class) +public class SharedFSResponse extends BaseResponseWithTagInformation implements ControlledViewEntityResponse { + + @SerializedName(ApiConstants.ID) + @Param(description = "ID of the shared filesystem") + private String id; + + @SerializedName(ApiConstants.NAME) + @Param(description = "name of the shared filesystem") + private String name; + + @SerializedName(ApiConstants.DESCRIPTION) + @Param(description = "description of the shared filesystem") + private String description; + + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "ID of the availability zone") + private String zoneId; + + @SerializedName(ApiConstants.ZONE_NAME) + @Param(description = "Name of the availability zone") + private String zoneName; + + @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) + @Param(description = "ID of the storage fs vm") + private String virtualMachineId; + + @SerializedName(ApiConstants.VIRTUAL_MACHINE_STATE) + @Param(description = "ID of the storage fs vm") + private String virtualMachineState; + + @SerializedName(ApiConstants.VOLUME_NAME) + @Param(description = "name of the storage fs data volume") + private String volumeName; + + @SerializedName(ApiConstants.VOLUME_ID) + @Param(description = "ID of the storage fs data volume") + private String volumeId; + + @SerializedName(ApiConstants.STORAGE) + @Param(description = "name of the storage pool hosting the data volume") + private String storagePoolName; + + @SerializedName(ApiConstants.STORAGE_ID) + @Param(description = "ID of the storage pool hosting the data volume") + private String storagePoolId; + + @SerializedName(ApiConstants.SIZE) + @Param(description = "size of the shared filesystem") + private Long size; + + @SerializedName(ApiConstants.SIZEGB) + @Param(description = "size of the shared filesystem in GiB") + private String sizeGB; + + @SerializedName(ApiConstants.DISK_OFFERING_ID) + @Param(description = "disk offering ID for the shared filesystem") + private String diskOfferingId; + + @SerializedName("diskofferingname") + @Param(description = "disk offering for the shared filesystem") + private String diskOfferingName; + + @SerializedName("iscustomdiskoffering") + @Param(description = "disk offering for the shared filesystem has custom size") + private Boolean isCustomDiskOffering; + + @SerializedName("diskofferingdisplaytext") + @Param(description = "disk offering display text for the shared filesystem") + private String diskOfferingDisplayText; + + @SerializedName(ApiConstants.SERVICE_OFFERING_ID) + @Param(description = "service offering ID for the shared filesystem") + private String serviceOfferingId; + + @SerializedName("serviceofferingname") + @Param(description = "service offering for the shared filesystem") + private String serviceOfferingName; + + @SerializedName(ApiConstants.NETWORK_ID) + @Param(description = "Network ID of the shared filesystem") + private String networkId; + + @SerializedName(ApiConstants.NETWORK_NAME) + @Param(description = "Network name of the shared filesystem") + private String networkName; + + @SerializedName(ApiConstants.NIC) + @Param(description = "the list of nics associated with the shared filesystem", responseObject = NicResponse.class) + private List nics; + + @SerializedName(ApiConstants.PATH) + @Param(description = "path to mount the shared filesystem") + private String path; + + @SerializedName(ApiConstants.STATE) + @Param(description = "the state of the shared filesystem") + private String state; + + @SerializedName(ApiConstants.PROVIDER) + @Param(description = "the shared filesystem provider") + private String provider; + + @SerializedName(ApiConstants.FILESYSTEM) + @Param(description = "the filesystem format") + private String filesystem; + + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the account associated with the shared filesystem") + private String accountName; + + @SerializedName(ApiConstants.PROJECT_ID) + @Param(description = "the project ID of the shared filesystem") + private String projectId; + + @SerializedName(ApiConstants.PROJECT) + @Param(description = "the project name of the shared filesystem") + private String projectName; + + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "the ID of the domain associated with the shared filesystem") + private String domainId; + + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "the domain associated with the shared filesystem") + private String domainName; + + @SerializedName(ApiConstants.DOMAIN_PATH) + @Param(description = "path of the domain to which the shared filesystem") + private String domainPath; + + @SerializedName(ApiConstants.PROVISIONINGTYPE) + @Param(description = "provisioning type used in the shared filesystem") + private String provisioningType; + + @SerializedName(ApiConstants.DISK_IO_READ) + @Param(description = "the read (IO) of disk on the shared filesystem") + private Long diskIORead; + + @SerializedName(ApiConstants.DISK_IO_WRITE) + @Param(description = "the write (IO) of disk on the shared filesystem") + private Long diskIOWrite; + + @SerializedName(ApiConstants.DISK_KBS_READ) + @Param(description = "the shared filesystem's disk read in KiB") + private Long diskKbsRead; + + @SerializedName(ApiConstants.DISK_KBS_WRITE) + @Param(description = "the shared filesystem's disk write in KiB") + private Long diskKbsWrite; + + @SerializedName(ApiConstants.VIRTUAL_SIZE) + @Param(description = "the bytes allocated") + private Long virtualSize; + + @SerializedName(ApiConstants.PHYSICAL_SIZE) + @Param(description = "the bytes actually consumed on disk") + private Long physicalSize; + + @SerializedName(ApiConstants.UTILIZATION) + @Param(description = "the disk utilization") + private String utilization; + + @Override + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + @Override + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + @Override + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public void setId(String id) { + this.id = id; + } + + public void setName(String name) { + this.name = name; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; + } + + public void setState(String state) { + this.state = state; + } + + public void setVolumeId(String volumeId) { + this.volumeId = volumeId; + } + + public void setNetworkId(String networkId) { + this.networkId = networkId; + } + + public void setNetworkName(String networkName) { + this.networkName = networkName; + } + + public List getNics() { + return nics; + } + + public void addNic(NicResponse nic) { + if (this.nics == null) { + this.nics = new ArrayList<>(); + } + this.nics.add(nic); + } + + public void setSize(Long size) { + this.size = size; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setPath(String path) { + this.path = path; + } + + public void setVolumeName(String volumeName) { + this.volumeName = volumeName; + } + + public void setStoragePoolName(String storagePoolName) { + this.storagePoolName = storagePoolName; + } + + public void setStoragePoolId(String storagePoolId) { + this.storagePoolId = storagePoolId; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public void setFilesystem(String filesystem) { + this.filesystem = filesystem; + } + + public void setSizeGB(Long size) { + if (size != null) { + this.sizeGB = String.format("%.2f GiB", size / (1024.0 * 1024.0 * 1024.0)); + } + } + + public void setDiskOfferingId(String diskOfferingId) { + this.diskOfferingId = diskOfferingId; + } + + public void setDiskOfferingName(String diskOfferingName) { + this.diskOfferingName = diskOfferingName; + } + + public void setDiskOfferingDisplayText(String diskOfferingDisplayText) { + this.diskOfferingDisplayText = diskOfferingDisplayText; + } + + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; + } + + public void setServiceOfferingName(String serviceOfferingName) { + this.serviceOfferingName = serviceOfferingName; + } + + public void setProvisioningType(String provisioningType) { + this.provisioningType = provisioningType; + } + + public void setDiskIORead(Long diskIORead) { + this.diskIORead = diskIORead; + } + + public void setDiskIOWrite(Long diskIOWrite) { + this.diskIOWrite = diskIOWrite; + } + + public void setDiskKbsRead(Long diskKbsRead) { + this.diskKbsRead = diskKbsRead; + } + + public void setDiskKbsWrite(Long diskKbsWrite) { + this.diskKbsWrite = diskKbsWrite; + } + + public void setVirtualSize(Long virtualSize) { + this.virtualSize = virtualSize; + } + + public void setPhysicalSize(Long physicalSize) { + this.physicalSize = physicalSize; + } + + public void setUtilization(String utilization) { + this.utilization = utilization; + } + + public void setIsCustomDiskOffering(Boolean isCustomDiskOffering) { + this.isCustomDiskOffering = isCustomDiskOffering; + } + + public void setVirtualMachineState(String virtualMachineState) { + this.virtualMachineState = virtualMachineState; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/StoragePoolResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/StoragePoolResponse.java index 06d5103d731..676803ea86b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/StoragePoolResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/StoragePoolResponse.java @@ -97,6 +97,10 @@ public class StoragePoolResponse extends BaseResponseWithAnnotations { @Param(description = "total min IOPS currently in use by volumes") private Long allocatedIops; + @SerializedName(ApiConstants.USED_IOPS) + @Param(description = "total IOPS currently in use", since = "4.20.1") + private Long usedIops; + @SerializedName(ApiConstants.STORAGE_CUSTOM_STATS) @Param(description = "the storage pool custom stats", since = "4.18.1") private Map customStats; @@ -312,6 +316,14 @@ public class StoragePoolResponse extends BaseResponseWithAnnotations { this.allocatedIops = allocatedIops; } + public Long getUsedIops() { + return usedIops; + } + + public void setUsedIops(Long usedIops) { + this.usedIops = usedIops; + } + public Map getCustomStats() { return customStats; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/SystemVmResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/SystemVmResponse.java index 31a8b731491..be9f14f5060 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/SystemVmResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/SystemVmResponse.java @@ -186,6 +186,10 @@ public class SystemVmResponse extends BaseResponseWithAnnotations { @Param(description = "the name of the service offering of the system virtual machine.") private String serviceOfferingName; + @SerializedName(ApiConstants.ARCH) + @Param(description = "CPU arch of the system VM", since = "4.20.1") + private String arch; + @Override public String getObjectId() { return this.getId(); @@ -490,4 +494,8 @@ public class SystemVmResponse extends BaseResponseWithAnnotations { public void setServiceOfferingName(String serviceOfferingName) { this.serviceOfferingName = serviceOfferingName; } + + public void setArch(String arch) { + this.arch = arch; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/TaggedResourceLimitAndCountResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/TaggedResourceLimitAndCountResponse.java new file mode 100644 index 00000000000..bfb03b7667c --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/TaggedResourceLimitAndCountResponse.java @@ -0,0 +1,86 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; + +import com.cloud.configuration.Resource; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +public class TaggedResourceLimitAndCountResponse extends BaseResponse { + + @SerializedName(ApiConstants.RESOURCE_TYPE) + @Param(description = "Numerical value for the type of the resource. See the ResourceType for more information on these values.") + private Integer resourceType; + + @SerializedName(ApiConstants.RESOURCE_TYPE_NAME) + @Param(description = "Name for the type of the resource") + private String resourceTypeName; + + @SerializedName(ApiConstants.TAG) + @Param(description = "The tag for the resource type") + private String tag; + + @SerializedName(ApiConstants.LIMIT) + @Param(description = "The limit for the resource count for the type and tag for the owner") + private Long limit; + + @SerializedName(ApiConstants.TOTAL) + @Param(description = "The total amount of the resource for the type and tag that is used by the owner") + private Long total; + + @SerializedName(ApiConstants.AVAILABLE) + @Param(description = "The available amount of the resource for the type and tag that is available for the owner") + private Long available; + + + public void setResourceType(Resource.ResourceType resourceType) { + this.resourceType = resourceType.getOrdinal(); + this.resourceTypeName = resourceType.getName(); + } + + public void setTag(String tag) { + this.tag = tag; + } + + public void setLimit(Long limit) { + this.limit = limit; + } + + public void setTotal(Long total) { + this.total = total; + } + + public void setAvailable(Long available) { + this.available = available; + } + + public Long getLimit() { + return limit; + } + + public Long getTotal() { + return total; + } + + public Long getAvailable() { + return available; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/TemplateResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/TemplateResponse.java index 604c9f0955f..98e96091d8c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/TemplateResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/TemplateResponse.java @@ -183,6 +183,10 @@ public class TemplateResponse extends BaseResponseWithTagInformation implements @Param(description = "Lists the download progress of a template across all secondary storages") private List> downloadDetails; + @SerializedName(ApiConstants.ARCH) + @Param(description = "CPU Arch of the template", since = "4.20") + private String arch; + @SerializedName(ApiConstants.BITS) @Param(description = "the processor bit size", since = "4.10") private int bits; @@ -520,4 +524,8 @@ public class TemplateResponse extends BaseResponseWithTagInformation implements public void setUserDataParams(String userDataParams) { this.userDataParams = userDataParams; } + + public void setArch(String arch) { + this.arch = arch; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/UsageRecordResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/UsageRecordResponse.java index 25382f3aaf9..4aeded64287 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/UsageRecordResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/UsageRecordResponse.java @@ -16,6 +16,7 @@ // under the License. package org.apache.cloudstack.api.response; +import java.util.Date; import java.util.LinkedHashSet; import java.util.Set; @@ -137,11 +138,11 @@ public class UsageRecordResponse extends BaseResponseWithTagInformation implemen @SerializedName(ApiConstants.START_DATE) @Param(description = "start date of the usage record") - private String startDate; + private Date startDate; @SerializedName(ApiConstants.END_DATE) @Param(description = "end date of the usage record") - private String endDate; + private Date endDate; @SerializedName("issourcenat") @Param(description = "True if the IPAddress is source NAT") @@ -164,7 +165,7 @@ public class UsageRecordResponse extends BaseResponseWithTagInformation implemen private String vpcId; public UsageRecordResponse() { - tags = new LinkedHashSet(); + tags = new LinkedHashSet<>(); } public void setTags(Set tags) { @@ -249,11 +250,11 @@ public class UsageRecordResponse extends BaseResponseWithTagInformation implemen this.size = size; } - public void setStartDate(String startDate) { + public void setStartDate(Date startDate) { this.startDate = startDate; } - public void setEndDate(String endDate) { + public void setEndDate(Date endDate) { this.endDate = endDate; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/UsageTypeResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/UsageTypeResponse.java index 83b97f00c15..5beef5ac556 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/UsageTypeResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/UsageTypeResponse.java @@ -25,12 +25,16 @@ import com.cloud.serializer.Param; public class UsageTypeResponse extends BaseResponse { - @SerializedName("usagetypeid") - @Param(description = "usage type") + @SerializedName("id") + @Param(description = "Usage type ID") private Integer usageType; + @SerializedName(ApiConstants.NAME) + @Param(description = "Usage type name") + private String name; + @SerializedName(ApiConstants.DESCRIPTION) - @Param(description = "description of usage type") + @Param(description = "Usage type description") private String description; public String getDescription() { @@ -49,10 +53,10 @@ public class UsageTypeResponse extends BaseResponse { this.usageType = usageType; } - public UsageTypeResponse(Integer usageType, String description) { + public UsageTypeResponse(Integer usageType, String name, String description) { this.usageType = usageType; + this.name = name; this.description = description; setObjectName("usagetype"); } - } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/UserDataResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/UserDataResponse.java index 2dfc66fa7d5..ce344596aeb 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/UserDataResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/UserDataResponse.java @@ -27,41 +27,41 @@ import org.apache.cloudstack.api.EntityReference; public class UserDataResponse extends BaseResponseWithAnnotations implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) - @Param(description = "ID of the ssh keypair") + @Param(description = "ID of the User Data") private String id; @SerializedName(ApiConstants.NAME) - @Param(description = "Name of the userdata") + @Param(description = "Name of the User Data") private String name; - @SerializedName(ApiConstants.ACCOUNT_ID) @Param(description="the owner id of the userdata") + @SerializedName(ApiConstants.ACCOUNT_ID) @Param(description="the owner id of the User Data") private String accountId; - @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner of the userdata") + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner of the User Data") private String accountName; @SerializedName(ApiConstants.PROJECT_ID) - @Param(description = "the project id of the userdata", since = "4.19.1") + @Param(description = "the project id of the User Data", since = "4.19.1") private String projectId; @SerializedName(ApiConstants.PROJECT) - @Param(description = "the project name of the userdata", since = "4.19.1") + @Param(description = "the project name of the User Data", since = "4.19.1") private String projectName; - @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the userdata owner") + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the User Data owner") private String domainId; - @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the userdata owner") + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the User Data owner") private String domain; @SerializedName(ApiConstants.DOMAIN_PATH) - @Param(description = "path of the domain to which the userdata owner belongs", since = "4.19.2.0") + @Param(description = "path of the domain to which the User Data owner belongs", since = "4.19.2.0") private String domainPath; - @SerializedName(ApiConstants.USER_DATA) @Param(description="base64 encoded userdata content") + @SerializedName(ApiConstants.USER_DATA) @Param(description="base64 encoded User Data content") private String userData; - @SerializedName(ApiConstants.PARAMS) @Param(description="list of parameters which contains the list of keys or string parameters that are needed to be passed for any variables declared in userdata") + @SerializedName(ApiConstants.PARAMS) @Param(description="list of parameters which contains the list of keys or string parameters that are needed to be passed for any variables declared in the User Data") private String params; public UserDataResponse() { diff --git a/api/src/main/java/org/apache/cloudstack/api/response/UserResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/UserResponse.java index 1a17f3b8698..df97a915700 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/UserResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/UserResponse.java @@ -128,6 +128,10 @@ public class UserResponse extends BaseResponse implements SetResourceIconRespons @Param(description = "true if user has two factor authentication is mandated", since = "4.18.0.0") private Boolean is2FAmandated; + @SerializedName(ApiConstants.API_KEY_ACCESS) + @Param(description = "whether api key access is Enabled, Disabled or set to Inherit (it inherits the value from the parent)", since = "4.20.1.0") + ApiConstants.ApiKeyAccess apiKeyAccess; + @Override public String getObjectId() { return this.getId(); @@ -309,4 +313,8 @@ public class UserResponse extends BaseResponse implements SetResourceIconRespons public void set2FAmandated(Boolean is2FAmandated) { this.is2FAmandated = is2FAmandated; } + + public void setApiKeyAccess(Boolean apiKeyAccess) { + this.apiKeyAccess = ApiConstants.ApiKeyAccess.fromBoolean(apiKeyAccess); + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/UserVmResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/UserVmResponse.java index a9e4587169c..2f519ccf3a5 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/UserVmResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/UserVmResponse.java @@ -31,13 +31,13 @@ import org.apache.cloudstack.affinity.AffinityGroupResponse; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponseWithTagInformation; import org.apache.cloudstack.api.EntityReference; +import org.apache.commons.collections.CollectionUtils; import com.cloud.network.router.VirtualRouter; import com.cloud.serializer.Param; import com.cloud.uservm.UserVm; import com.cloud.vm.VirtualMachine; import com.google.gson.annotations.SerializedName; -import org.apache.commons.collections.CollectionUtils; @SuppressWarnings("unused") @EntityReference(value = {VirtualMachine.class, UserVm.class, VirtualRouter.class}) @@ -320,6 +320,10 @@ public class UserVmResponse extends BaseResponseWithTagInformation implements Co @Param(description = "true if vm contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory.") private Boolean isDynamicallyScalable; + @SerializedName(ApiConstants.DELETE_PROTECTION) + @Param(description = "true if vm has delete protection.", since = "4.20.0") + private boolean deleteProtection; + @SerializedName(ApiConstants.SERVICE_STATE) @Param(description = "State of the Service from LB rule") private String serviceState; @@ -388,6 +392,14 @@ public class UserVmResponse extends BaseResponseWithTagInformation implements Co @Param(description = "VNF details", since = "4.19.0") private Map vnfDetails; + @SerializedName((ApiConstants.VM_TYPE)) + @Param(description = "User VM type", since = "4.20.0") + private String vmType; + + @SerializedName(ApiConstants.ARCH) + @Param(description = "CPU arch of the VM", since = "4.20.1") + private String arch; + public UserVmResponse() { securityGroupList = new LinkedHashSet<>(); nics = new TreeSet<>(Comparator.comparingInt(x -> Integer.parseInt(x.getDeviceId()))); @@ -991,6 +1003,14 @@ public class UserVmResponse extends BaseResponseWithTagInformation implements Co isDynamicallyScalable = dynamicallyScalable; } + public boolean isDeleteProtection() { + return deleteProtection; + } + + public void setDeleteProtection(boolean deleteProtection) { + this.deleteProtection = deleteProtection; + } + public String getOsTypeId() { return osTypeId; } @@ -1142,7 +1162,23 @@ public class UserVmResponse extends BaseResponseWithTagInformation implements Co this.vnfDetails.put(key,value); } + public void setVmType(String vmType) { + this.vmType = vmType; + } + + public String getVmType() { + return vmType; + } + public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } + + public String getArch() { + return arch; + } + + public void setArch(String arch) { + this.arch = arch; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/VlanIpRangeResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/VlanIpRangeResponse.java index 5f5af69f6a9..1492c23e882 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/VlanIpRangeResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/VlanIpRangeResponse.java @@ -127,6 +127,10 @@ public class VlanIpRangeResponse extends BaseResponse implements ControlledEntit @Param(description = "indicates whether VLAN IP range is dedicated to system vms or not") private Boolean forSystemVms; + @SerializedName(ApiConstants.FOR_NSX) + @Param(description = "indicates whether IP range is dedicated to NSX resources or not") + private Boolean forNsx; + public void setId(String id) { this.id = id; } @@ -244,4 +248,8 @@ public class VlanIpRangeResponse extends BaseResponse implements ControlledEntit public void setIp6Cidr(String ip6Cidr) { this.ip6Cidr = ip6Cidr; } + + public void setForNsx(Boolean forNsx) { + this.forNsx = forNsx; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/VolumeResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/VolumeResponse.java index 623499822cb..209ca57c50d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/VolumeResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/VolumeResponse.java @@ -93,7 +93,7 @@ public class VolumeResponse extends BaseResponseWithTagInformation implements Co @Param(description = "display name of the virtual machine") private String virtualMachineDisplayName; - @SerializedName("vmstate") + @SerializedName(ApiConstants.VIRTUAL_MACHINE_STATE) @Param(description = "state of the virtual machine") private String virtualMachineState; @@ -261,12 +261,16 @@ public class VolumeResponse extends BaseResponseWithTagInformation implements Co @Param(description = "true if storage snapshot is supported for the volume, false otherwise", since = "4.16") private boolean supportsStorageSnapshot; + @SerializedName(ApiConstants.DELETE_PROTECTION) + @Param(description = "true if volume has delete protection.", since = "4.20.0") + private boolean deleteProtection; + @SerializedName(ApiConstants.PHYSICAL_SIZE) - @Param(description = "the bytes allocated") + @Param(description = "the bytes actually consumed on disk") private Long physicalsize; @SerializedName(ApiConstants.VIRTUAL_SIZE) - @Param(description = "the bytes actually consumed on disk") + @Param(description = "the bytes allocated") private Long virtualsize; @SerializedName(ApiConstants.UTILIZATION) @@ -584,6 +588,14 @@ public class VolumeResponse extends BaseResponseWithTagInformation implements Co return this.supportsStorageSnapshot; } + public boolean isDeleteProtection() { + return deleteProtection; + } + + public void setDeleteProtection(boolean deleteProtection) { + this.deleteProtection = deleteProtection; + } + public String getIsoId() { return isoId; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/VpcOfferingResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/VpcOfferingResponse.java index 6881969646b..b11764da7d9 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/VpcOfferingResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/VpcOfferingResponse.java @@ -63,9 +63,17 @@ public class VpcOfferingResponse extends BaseResponse { private Boolean supportsDistributedRouter; @SerializedName((ApiConstants.SUPPORTS_REGION_LEVEL_VPC)) - @Param(description = " indicated if the offering can support region level vpc", since = "4.4") + @Param(description = "indicated if the offering can support region level vpc", since = "4.4") private Boolean supportsRegionLevelVpc; + @SerializedName(ApiConstants.FOR_NSX) + @Param(description = "true if vpc offering can be used by NSX networks only") + private Boolean forNsx; + + @SerializedName(ApiConstants.NETWORK_MODE) + @Param(description = "Mode in which the network will operate. The valid values are NATTED and ROUTED") + private String networkMode; + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain ID(s) this disk offering belongs to. Ignore this information as it is not currently applicable.") private String domainId; @@ -86,6 +94,14 @@ public class VpcOfferingResponse extends BaseResponse { @Param(description = "the internet protocol of the vpc offering") private String internetProtocol; + @SerializedName(ApiConstants.SPECIFY_AS_NUMBER) + @Param(description = "true if network offering supports choosing AS numbers") + private Boolean specifyAsNumber; + + @SerializedName(ApiConstants.ROUTING_MODE) + @Param(description = "the routing mode for the network offering, supported types are Static or Dynamic.") + private String routingMode; + public void setId(String id) { this.id = id; } @@ -138,6 +154,14 @@ public class VpcOfferingResponse extends BaseResponse { this.domain = domain; } + public void setForNsx(Boolean forNsx) { + this.forNsx = forNsx; + } + + public void setNetworkMode(String networkMode) { + this.networkMode = networkMode; + } + public String getZoneId() { return zoneId; } @@ -161,4 +185,20 @@ public class VpcOfferingResponse extends BaseResponse { public void setInternetProtocol(String internetProtocol) { this.internetProtocol = internetProtocol; } + + public Boolean getSpecifyAsNumber() { + return specifyAsNumber; + } + + public void setSpecifyAsNumber(Boolean specifyAsNumber) { + this.specifyAsNumber = specifyAsNumber; + } + + public String getRoutingMode() { + return routingMode; + } + + public void setRoutingMode(String routingMode) { + this.routingMode = routingMode; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/VpcResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/VpcResponse.java index 6f91da7d2d7..56479506686 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/VpcResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/VpcResponse.java @@ -17,6 +17,7 @@ package org.apache.cloudstack.api.response; import java.util.Date; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -160,6 +161,26 @@ public class VpcResponse extends BaseResponseWithAnnotations implements Controll @Param(description = "the second IPv6 DNS for the VPC", since = "4.18.0") private String ipv6Dns2; + @SerializedName(ApiConstants.IPV4_ROUTING) + @Param(description = "The IPv4 routing mode of VPC", since = "4.20.0") + private String ipv4Routing; + + @SerializedName(ApiConstants.IPV4_ROUTES) + @Param(description = "The routes for the VPC to ease adding route in upstream router", since = "4.20.0") + private Set ipv4Routes; + + @SerializedName(ApiConstants.AS_NUMBER_ID) + @Param(description = "UUID of AS NUMBER", since = "4.20.0") + private String asNumberId; + + @SerializedName(ApiConstants.AS_NUMBER) + @Param(description = "AS NUMBER", since = "4.20.0") + private Long asNumber; + + @SerializedName(ApiConstants.BGP_PEERS) + @Param(description = "The BGP peers for the VPC", since = "4.20.0") + private Set bgpPeers; + public void setId(final String id) { this.id = id; } @@ -279,6 +300,18 @@ public class VpcResponse extends BaseResponseWithAnnotations implements Controll this.icon = icon; } + public void setIpv4Routing(String ipv4Routing) { + this.ipv4Routing = ipv4Routing; + } + + public void setIpv4Routes(Set ipv4Routes) { + this.ipv4Routes = ipv4Routes; + } + + public void addIpv4Route(Ipv4RouteResponse ipv4Route) { + this.ipv4Routes.add(ipv4Route); + } + public void setIpv6Routes(Set ipv6Routes) { this.ipv6Routes = ipv6Routes; } @@ -306,4 +339,23 @@ public class VpcResponse extends BaseResponseWithAnnotations implements Controll public void setIpv6Dns2(String ipv6Dns2) { this.ipv6Dns2 = ipv6Dns2; } + + public void setAsNumber(long asNumber) { + this.asNumber = asNumber; + } + + public void setAsNumberId(String asNumberId) { + this.asNumberId = asNumberId; + } + + public void setBgpPeers(Set bgpPeers) { + this.bgpPeers = bgpPeers; + } + + public void addBgpPeer(BgpPeerResponse bgpPeer) { + if (this.bgpPeers == null) { + this.setBgpPeers(new LinkedHashSet<>()); + } + this.bgpPeers.add(bgpPeer); + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ZoneResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ZoneResponse.java index efcd461cb2d..4a5279753a1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/ZoneResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/ZoneResponse.java @@ -145,6 +145,23 @@ public class ZoneResponse extends BaseResponseWithAnnotations implements SetReso @Param(description = "the type of the zone - core or edge", since = "4.18.0") String type; + @SerializedName(ApiConstants.NSX_ENABLED) + @Param(description = "true, if zone is NSX enabled", since = "4.20.0") + private boolean nsxEnabled = false; + + @SerializedName(ApiConstants.MULTI_ARCH) + @Param(description = "true, if zone contains clusters and hosts from different CPU architectures", since = "4.20") + private boolean multiArch; + + @SerializedName(ApiConstants.ASN_RANGE) + @Param(description = "AS Number Range") + private String asnRange; + + @SerializedName(ApiConstants.ROUTED_MODE_ENABLED) + @Param(description = "true, if routed network/vpc is enabled", since = "4.20.1") + private boolean routedModeEnabled = false; + + public ZoneResponse() { tags = new LinkedHashSet(); } @@ -308,10 +325,6 @@ public class ZoneResponse extends BaseResponseWithAnnotations implements SetReso return networkType; } - public boolean isSecurityGroupsEnabled() { - return securityGroupsEnabled; - } - public String getAllocationState() { return allocationState; } @@ -328,10 +341,6 @@ public class ZoneResponse extends BaseResponseWithAnnotations implements SetReso return capacities; } - public boolean isLocalStorageEnabled() { - return localStorageEnabled; - } - public Set getTags() { return tags; } @@ -340,6 +349,14 @@ public class ZoneResponse extends BaseResponseWithAnnotations implements SetReso return resourceDetails; } + public boolean isSecurityGroupsEnabled() { + return securityGroupsEnabled; + } + + public boolean isLocalStorageEnabled() { + return localStorageEnabled; + } + public Boolean getAllowUserSpecifyVRMtu() { return allowUserSpecifyVRMtu; } @@ -352,6 +369,10 @@ public class ZoneResponse extends BaseResponseWithAnnotations implements SetReso return routerPublicInterfaceMaxMtu; } + public boolean isNsxEnabled() { + return nsxEnabled; + } + @Override public void setResourceIconResponse(ResourceIconResponse resourceIconResponse) { this.resourceIconResponse = resourceIconResponse; @@ -380,4 +401,28 @@ public class ZoneResponse extends BaseResponseWithAnnotations implements SetReso public String getType() { return type; } + + public void setNsxEnabled(boolean nsxEnabled) { + this.nsxEnabled = nsxEnabled; + } + + public void setMultiArch(boolean multiArch) { + this.multiArch = multiArch; + } + + public void setAsnRange(String asnRange) { + this.asnRange = asnRange; + } + + public String getAsnRange() { + return asnRange; + } + + public boolean isRoutedModeEnabled() { + return routedModeEnabled; + } + + public void setRoutedModeEnabled(boolean routedModeEnabled) { + this.routedModeEnabled = routedModeEnabled; + } } diff --git a/api/src/main/java/org/apache/cloudstack/backup/Backup.java b/api/src/main/java/org/apache/cloudstack/backup/Backup.java index df1b243dbab..f21f20adb33 100644 --- a/api/src/main/java/org/apache/cloudstack/backup/Backup.java +++ b/api/src/main/java/org/apache/cloudstack/backup/Backup.java @@ -18,6 +18,7 @@ package org.apache.cloudstack.backup; import java.util.Date; +import java.util.List; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.Identity; @@ -141,5 +142,6 @@ public interface Backup extends ControlledEntity, InternalIdentity, Identity { Backup.Status getStatus(); Long getSize(); Long getProtectedSize(); + List getBackedUpVolumes(); long getZoneId(); } diff --git a/api/src/main/java/org/apache/cloudstack/backup/BackupManager.java b/api/src/main/java/org/apache/cloudstack/backup/BackupManager.java index 7b39804c738..78d189c3bf1 100644 --- a/api/src/main/java/org/apache/cloudstack/backup/BackupManager.java +++ b/api/src/main/java/org/apache/cloudstack/backup/BackupManager.java @@ -22,6 +22,7 @@ import java.util.List; import org.apache.cloudstack.api.command.admin.backup.ImportBackupOfferingCmd; import org.apache.cloudstack.api.command.admin.backup.UpdateBackupOfferingCmd; import org.apache.cloudstack.api.command.user.backup.CreateBackupScheduleCmd; +import org.apache.cloudstack.api.command.user.backup.DeleteBackupScheduleCmd; import org.apache.cloudstack.api.command.user.backup.ListBackupOfferingsCmd; import org.apache.cloudstack.api.command.user.backup.ListBackupsCmd; import org.apache.cloudstack.framework.config.ConfigKey; @@ -107,14 +108,14 @@ public interface BackupManager extends BackupService, Configurable, PluggableSer * @param vmId * @return */ - BackupSchedule listBackupSchedule(Long vmId); + List listBackupSchedule(Long vmId); /** * Deletes VM backup schedule for a VM - * @param vmId + * @param cmd * @return */ - boolean deleteBackupSchedule(Long vmId); + boolean deleteBackupSchedule(DeleteBackupScheduleCmd cmd); /** * Creates backup of a VM diff --git a/api/src/main/java/org/apache/cloudstack/backup/BackupProvider.java b/api/src/main/java/org/apache/cloudstack/backup/BackupProvider.java index 9c1b14ae60f..d36dfb7360f 100644 --- a/api/src/main/java/org/apache/cloudstack/backup/BackupProvider.java +++ b/api/src/main/java/org/apache/cloudstack/backup/BackupProvider.java @@ -93,7 +93,7 @@ public interface BackupProvider { /** * Restore a volume from a backup */ - Pair restoreBackedUpVolume(Backup backup, String volumeUuid, String hostIp, String dataStoreUuid); + Pair restoreBackedUpVolume(Backup backup, String volumeUuid, String hostIp, String dataStoreUuid, Pair vmNameAndState); /** * Returns backup metrics for a list of VMs in a zone diff --git a/api/src/main/java/org/apache/cloudstack/backup/BackupRepository.java b/api/src/main/java/org/apache/cloudstack/backup/BackupRepository.java new file mode 100644 index 00000000000..8e5c9740e69 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/backup/BackupRepository.java @@ -0,0 +1,34 @@ +//Licensed to the Apache Software Foundation (ASF) under one +//or more contributor license agreements. See the NOTICE file +//distributed with this work for additional information +//regarding copyright ownership. The ASF licenses this file +//to you under the Apache License, Version 2.0 (the +//"License"); you may not use this file except in compliance +//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. +package org.apache.cloudstack.backup; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +import java.util.Date; + +public interface BackupRepository extends InternalIdentity, Identity { + String getProvider(); + long getZoneId(); + String getName(); + String getType(); + String getAddress(); + String getMountOptions(); + Long getCapacityBytes(); + Long getUsedBytes(); + Date getCreated(); +} diff --git a/api/src/main/java/org/apache/cloudstack/backup/BackupRepositoryService.java b/api/src/main/java/org/apache/cloudstack/backup/BackupRepositoryService.java new file mode 100644 index 00000000000..ae71053e400 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/backup/BackupRepositoryService.java @@ -0,0 +1,34 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +// + +package org.apache.cloudstack.backup; + +import com.cloud.utils.Pair; +import org.apache.cloudstack.api.command.user.backup.repository.AddBackupRepositoryCmd; +import org.apache.cloudstack.api.command.user.backup.repository.DeleteBackupRepositoryCmd; +import org.apache.cloudstack.api.command.user.backup.repository.ListBackupRepositoriesCmd; + +import java.util.List; + +public interface BackupRepositoryService { + BackupRepository addBackupRepository(AddBackupRepositoryCmd cmd); + boolean deleteBackupRepository(DeleteBackupRepositoryCmd cmd); + Pair, Integer> listBackupRepositories(ListBackupRepositoriesCmd cmd); + +} diff --git a/api/src/main/java/org/apache/cloudstack/cluster/ClusterDrsAlgorithm.java b/api/src/main/java/org/apache/cloudstack/cluster/ClusterDrsAlgorithm.java index 15f7fcd8174..665f95842b0 100644 --- a/api/src/main/java/org/apache/cloudstack/cluster/ClusterDrsAlgorithm.java +++ b/api/src/main/java/org/apache/cloudstack/cluster/ClusterDrsAlgorithm.java @@ -21,6 +21,7 @@ package org.apache.cloudstack.cluster; import com.cloud.host.Host; import com.cloud.offering.ServiceOffering; +import com.cloud.org.Cluster; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Adapter; @@ -55,8 +56,8 @@ public interface ClusterDrsAlgorithm extends Adapter { * @throws ConfigurationException * if there is an error in the configuration */ - boolean needsDrs(long clusterId, List> cpuList, - List> memoryList) throws ConfigurationException; + boolean needsDrs(Cluster cluster, List> cpuList, + List> memoryList) throws ConfigurationException; /** @@ -79,7 +80,7 @@ public interface ClusterDrsAlgorithm extends Adapter { * * @return a ternary containing improvement, cost, benefit */ - Ternary getMetrics(long clusterId, VirtualMachine vm, ServiceOffering serviceOffering, + Ternary getMetrics(Cluster cluster, VirtualMachine vm, ServiceOffering serviceOffering, Host destHost, Map> hostCpuMap, Map> hostMemoryMap, Boolean requiresStorageMotion) throws ConfigurationException; diff --git a/api/src/main/java/org/apache/cloudstack/consoleproxy/ConsoleAccessManager.java b/api/src/main/java/org/apache/cloudstack/consoleproxy/ConsoleAccessManager.java index f19b5398dd9..5bd9699b201 100644 --- a/api/src/main/java/org/apache/cloudstack/consoleproxy/ConsoleAccessManager.java +++ b/api/src/main/java/org/apache/cloudstack/consoleproxy/ConsoleAccessManager.java @@ -20,6 +20,7 @@ import com.cloud.utils.component.Manager; import org.apache.cloudstack.api.command.user.consoleproxy.ConsoleEndpoint; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; +import java.util.Date; public interface ConsoleAccessManager extends Manager, Configurable { @@ -44,4 +45,7 @@ public interface ConsoleAccessManager extends Manager, Configurable { void removeSessions(String[] sessionUuids); void acquireSession(String sessionUuid); + + String genAccessTicket(String host, String port, String sid, String tag, String sessionUuid); + String genAccessTicket(String host, String port, String sid, String tag, Date normalizedHashTime, String sessionUuid); } diff --git a/api/src/main/java/org/apache/cloudstack/context/CallContext.java b/api/src/main/java/org/apache/cloudstack/context/CallContext.java index ecc109977eb..69376e4f6d7 100644 --- a/api/src/main/java/org/apache/cloudstack/context/CallContext.java +++ b/api/src/main/java/org/apache/cloudstack/context/CallContext.java @@ -23,8 +23,8 @@ import java.util.UUID; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.managed.threadlocal.ManagedThreadLocal; -import org.apache.log4j.Logger; -import org.apache.log4j.NDC; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.exception.CloudAuthenticationException; import com.cloud.projects.Project; @@ -33,6 +33,7 @@ import com.cloud.user.User; import com.cloud.utils.UuidUtils; import com.cloud.utils.db.EntityManager; import com.cloud.utils.exception.CloudRuntimeException; +import org.apache.logging.log4j.ThreadContext; /** * CallContext records information about the environment the call is made. This @@ -40,7 +41,7 @@ import com.cloud.utils.exception.CloudRuntimeException; * entry point must set the context and remove it when the thread finishes. */ public class CallContext { - private static final Logger s_logger = Logger.getLogger(CallContext.class); + protected static Logger LOGGER = LogManager.getLogger(CallContext.class); private static ManagedThreadLocal s_currentContext = new ManagedThreadLocal(); private static ManagedThreadLocal> s_currentContextStack = new ManagedThreadLocal>() { @Override @@ -178,9 +179,9 @@ public class CallContext { callingContext = new CallContext(userId, accountId, contextId); } s_currentContext.set(callingContext); - NDC.push("ctx-" + UuidUtils.first(contextId)); - if (s_logger.isTraceEnabled()) { - s_logger.trace("Registered: " + callingContext); + ThreadContext.push("ctx-" + UuidUtils.first(contextId)); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Registered: " + callingContext); } s_currentContextStack.get().push(callingContext); @@ -209,7 +210,7 @@ public class CallContext { assert context.getCallingUserId() == User.UID_SYSTEM : "You are calling a very specific method that registers a one time system context. This method is meant for background threads that does processing."; return context; } catch (Exception e) { - s_logger.error("Failed to register the system call context.", e); + LOGGER.error("Failed to register the system call context.", e); throw new CloudRuntimeException("Failed to register system call context", e); } } @@ -278,18 +279,18 @@ public class CallContext { return null; } s_currentContext.remove(); - if (s_logger.isTraceEnabled()) { - s_logger.trace("Unregistered: " + context); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Unregistered: " + context); } String contextId = context.getContextId(); String sessionIdOnStack = null; String sessionIdPushedToNDC = "ctx-" + UuidUtils.first(contextId); - while ((sessionIdOnStack = NDC.pop()) != null) { + while ((sessionIdOnStack = ThreadContext.pop()) != null) { if (sessionIdOnStack.isEmpty() || sessionIdPushedToNDC.equals(sessionIdOnStack)) { break; } - if (s_logger.isTraceEnabled()) { - s_logger.trace("Popping from NDC: " + contextId); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Popping from NDC: " + contextId); } } diff --git a/api/src/main/java/org/apache/cloudstack/context/LogContext.java b/api/src/main/java/org/apache/cloudstack/context/LogContext.java index c81d0f499cb..c367975aba3 100644 --- a/api/src/main/java/org/apache/cloudstack/context/LogContext.java +++ b/api/src/main/java/org/apache/cloudstack/context/LogContext.java @@ -20,8 +20,8 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; -import org.apache.log4j.Logger; -import org.apache.log4j.MDC; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.apache.cloudstack.managed.threadlocal.ManagedThreadLocal; @@ -31,13 +31,14 @@ import com.cloud.user.User; import com.cloud.utils.UuidUtils; import com.cloud.utils.db.EntityManager; import com.cloud.utils.exception.CloudRuntimeException; +import org.apache.logging.log4j.ThreadContext; /** * LogContext records information about the environment the API call is made. This * class must be always be available in all CloudStack code. */ public class LogContext { - private static final Logger s_logger = Logger.getLogger(LogContext.class); + protected static Logger LOGGER = LogManager.getLogger(LogContext.class); private static ManagedThreadLocal s_currentContext = new ManagedThreadLocal(); private String logContextId; @@ -134,9 +135,9 @@ public class LogContext { callingContext = new LogContext(userId, accountId, contextId); } s_currentContext.set(callingContext); - MDC.put("logcontextid", UuidUtils.first(contextId)); - if (s_logger.isTraceEnabled()) { - s_logger.trace("Registered for log: " + callingContext); + ThreadContext.put("logcontextid", UuidUtils.first(contextId)); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Registered for log: " + callingContext); } return callingContext; } @@ -160,7 +161,7 @@ public class LogContext { assert context.getCallingUserId() == User.UID_SYSTEM : "You are calling a very specific method that registers a one time system context. This method is meant for background threads that does processing."; return context; } catch (Exception e) { - s_logger.error("Failed to register the system log context.", e); + LOGGER.error("Failed to register the system log context.", e); throw new CloudRuntimeException("Failed to register system log context", e); } } @@ -206,11 +207,11 @@ public class LogContext { LogContext context = s_currentContext.get(); if (context != null) { s_currentContext.remove(); - if (s_logger.isTraceEnabled()) { - s_logger.trace("Unregistered: " + context); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Unregistered: " + context); } } - MDC.clear(); + ThreadContext.clearMap(); } public void setStartEventId(long startEventId) { diff --git a/api/src/main/java/org/apache/cloudstack/datacenter/DataCenterIpv4GuestSubnet.java b/api/src/main/java/org/apache/cloudstack/datacenter/DataCenterIpv4GuestSubnet.java new file mode 100644 index 00000000000..90d55cc5751 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/datacenter/DataCenterIpv4GuestSubnet.java @@ -0,0 +1,36 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.datacenter; + +import java.util.Date; + +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface DataCenterIpv4GuestSubnet extends InfrastructureEntity, InternalIdentity, Identity { + Long getDataCenterId(); + + String getSubnet(); + + Long getDomainId(); + + Long getAccountId(); + + Date getCreated(); +} diff --git a/api/src/main/java/org/apache/cloudstack/dedicated/DedicatedResourceResponse.java b/api/src/main/java/org/apache/cloudstack/dedicated/DedicatedResourceResponse.java new file mode 100644 index 00000000000..fc116cbb91e --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/dedicated/DedicatedResourceResponse.java @@ -0,0 +1,44 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.dedicated; + +import com.cloud.dc.DedicatedResources; +import com.cloud.serializer.Param; + +import com.google.gson.annotations.SerializedName; + +import org.apache.cloudstack.api.BaseResponse; + +public class DedicatedResourceResponse extends BaseResponse { + @SerializedName("resourceid") + @Param(description = "the ID of the resource") + private String resourceId; + + @SerializedName("resourcename") + @Param(description = "the name of the resource") + private String resourceName; + + @SerializedName("resourcetype") + @Param(description = "the type of the resource") + private DedicatedResources.Type resourceType; + + public DedicatedResourceResponse(String resourceId, String resourceName, DedicatedResources.Type resourceType) { + this.resourceId = resourceId; + this.resourceName = resourceName; + this.resourceType = resourceType; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/network/BgpPeer.java b/api/src/main/java/org/apache/cloudstack/network/BgpPeer.java new file mode 100644 index 00000000000..e1d7eca0a03 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/network/BgpPeer.java @@ -0,0 +1,50 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.network; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +import java.util.Date; + +public interface BgpPeer extends Identity, InternalIdentity { + + Long getDomainId(); + + Long getAccountId(); + + enum State { + Active, Add, Revoke + } + + enum Detail { + EBGP_MultiHop + } + + long getDataCenterId(); + + String getIp4Address(); + + String getIp6Address(); + + Long getAsNumber(); + + String getPassword(); + + Date getCreated(); +} diff --git a/api/src/main/java/org/apache/cloudstack/network/BgpPeerTO.java b/api/src/main/java/org/apache/cloudstack/network/BgpPeerTO.java new file mode 100644 index 00000000000..b0503314616 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/network/BgpPeerTO.java @@ -0,0 +1,91 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.network; + +import java.util.Map; + +public class BgpPeerTO { + Long peerId; + Long peerAsNumber; + String ip4Address; + String ip6Address; + String peerPassword; + Long networkId; + Long networkAsNumber; + String guestIp4Cidr; + String guestIp6Cidr; + + Map details; + + public BgpPeerTO(Long peerId, String ip4Address, String ip6Address, Long peerAsNumber, String peerPassword, + Long networkId, Long networkAsNumber, String guestIp4Cidr, String guestIp6Cidr, Map details) { + this.peerId = peerId; + this.ip4Address = ip4Address; + this.ip6Address = ip6Address; + this.peerAsNumber = peerAsNumber; + this.peerPassword = peerPassword; + this.networkId = networkId; + this.networkAsNumber = networkAsNumber; + this.guestIp4Cidr = guestIp4Cidr; + this.guestIp6Cidr = guestIp6Cidr; + this.details = details; + } + + public BgpPeerTO(Long networkId) { + this.networkId = networkId; + } + + public Long getPeerId() { + return peerId; + } + + public String getIp4Address() { + return ip4Address; + } + + public String getIp6Address() { + return ip6Address; + } + + public Long getPeerAsNumber() { + return peerAsNumber; + } + + public String getPeerPassword() { + return peerPassword; + } + + public Long getNetworkId() { + return networkId; + } + + public Long getNetworkAsNumber() { + return networkAsNumber; + } + + public String getGuestIp4Cidr() { + return guestIp4Cidr; + } + + public String getGuestIp6Cidr() { + return guestIp6Cidr; + } + + public Map getDetails() { + return details; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/network/Ipv4GuestSubnetNetworkMap.java b/api/src/main/java/org/apache/cloudstack/network/Ipv4GuestSubnetNetworkMap.java new file mode 100644 index 00000000000..569ed22c164 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/network/Ipv4GuestSubnetNetworkMap.java @@ -0,0 +1,47 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.network; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +import java.util.Date; + +public interface Ipv4GuestSubnetNetworkMap extends Identity, InternalIdentity { + Date getAllocated(); + + Date getCreated(); + + enum State { + Allocating, // The subnet will be assigned to a network + Allocated, // The subnet is in use. + Releasing, // The subnet is being released. + Free // The subnet is ready to be allocated. + } + + Long getParentId(); + + String getSubnet(); + + Long getVpcId(); + + Long getNetworkId(); + + State getState(); + +} diff --git a/api/src/main/java/org/apache/cloudstack/network/RoutedIpv4Manager.java b/api/src/main/java/org/apache/cloudstack/network/RoutedIpv4Manager.java new file mode 100644 index 00000000000..221a550ad63 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/network/RoutedIpv4Manager.java @@ -0,0 +1,208 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.network; + +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.network.Network; +import com.cloud.network.rules.FirewallRule; +import com.cloud.network.vpc.Vpc; +import com.cloud.network.vpc.VpcOffering; +import com.cloud.offering.NetworkOffering; +import com.cloud.user.Account; +import com.cloud.utils.Pair; +import com.cloud.utils.component.PluggableService; + +import org.apache.cloudstack.api.command.admin.network.CreateIpv4SubnetForZoneCmd; +import org.apache.cloudstack.api.command.admin.network.CreateIpv4SubnetForGuestNetworkCmd; +import org.apache.cloudstack.api.command.admin.network.DedicateIpv4SubnetForZoneCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteIpv4SubnetForZoneCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteIpv4SubnetForGuestNetworkCmd; +import org.apache.cloudstack.api.command.admin.network.ListIpv4SubnetsForZoneCmd; +import org.apache.cloudstack.api.command.admin.network.ListIpv4SubnetsForGuestNetworkCmd; +import org.apache.cloudstack.api.command.admin.network.ReleaseDedicatedIpv4SubnetForZoneCmd; +import org.apache.cloudstack.api.command.admin.network.UpdateIpv4SubnetForZoneCmd; +import org.apache.cloudstack.api.command.admin.network.bgp.ChangeBgpPeersForNetworkCmd; +import org.apache.cloudstack.api.command.admin.network.bgp.ChangeBgpPeersForVpcCmd; +import org.apache.cloudstack.api.command.admin.network.bgp.CreateBgpPeerCmd; +import org.apache.cloudstack.api.command.admin.network.bgp.DedicateBgpPeerCmd; +import org.apache.cloudstack.api.command.admin.network.bgp.DeleteBgpPeerCmd; +import org.apache.cloudstack.api.command.admin.network.bgp.ListBgpPeersCmd; +import org.apache.cloudstack.api.command.admin.network.bgp.ReleaseDedicatedBgpPeerCmd; +import org.apache.cloudstack.api.command.admin.network.bgp.UpdateBgpPeerCmd; +import org.apache.cloudstack.api.command.user.network.routing.CreateRoutingFirewallRuleCmd; +import org.apache.cloudstack.api.command.user.network.routing.ListRoutingFirewallRulesCmd; +import org.apache.cloudstack.api.command.user.network.routing.UpdateRoutingFirewallRuleCmd; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.api.response.Ipv4SubnetForGuestNetworkResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; +import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.framework.config.Configurable; + +import java.util.List; + +public interface RoutedIpv4Manager extends PluggableService, Configurable { + + ConfigKey RoutedNetworkVpcEnabled = new ConfigKey<>(ConfigKey.CATEGORY_NETWORK, Boolean.class, + "routed.network.vpc.enabled", + "true", + "If true, the Routed network and VPC are enabled in the zone.", + true, + ConfigKey.Scope.Zone); + + ConfigKey RoutedNetworkIPv4MaxCidrSize = new ConfigKey<>(ConfigKey.CATEGORY_NETWORK, Integer.class, + "routed.network.ipv4.max.cidr.size", "30", "The maximum value of the cidr size for isolated networks in ROUTED mode", + true, ConfigKey.Scope.Account); + + ConfigKey RoutedNetworkIPv4MinCidrSize = new ConfigKey<>(ConfigKey.CATEGORY_NETWORK, Integer.class, + "routed.network.ipv4.min.cidr.size", "24", "The minimum value of the cidr size for isolated networks in ROUTED mode", + true, ConfigKey.Scope.Account); + + ConfigKey RoutedVpcIPv4MaxCidrSize = new ConfigKey<>(ConfigKey.CATEGORY_NETWORK, Integer.class, + "routed.ipv4.vpc.max.cidr.size", "28", "The maximum value of the cidr size for VPC in ROUTED mode", + true, ConfigKey.Scope.Account); + + ConfigKey RoutedVpcIPv4MinCidrSize = new ConfigKey<>(ConfigKey.CATEGORY_NETWORK, Integer.class, + "routed.ipv4.vpc.min.cidr.size", "22", "The minimum value of the cidr size for VPC in ROUTED mode", + true, ConfigKey.Scope.Account); + + ConfigKey RoutedIPv4NetworkCidrAutoAllocationEnabled = new ConfigKey<>(ConfigKey.CATEGORY_NETWORK, Boolean.class, + "routed.ipv4.network.cidr.auto.allocation.enabled", + "true", + "Indicates whether the auto-allocation of network CIDR for routed network is enabled or not.", + true, + ConfigKey.Scope.Account); + + ConfigKey UseSystemBgpPeers = new ConfigKey<>(ConfigKey.CATEGORY_NETWORK, Boolean.class, + "use.system.bgp.peers", + "true", + "If true, when account has dedicated bgp peers(s), the guest networks with dynamic routing will use both system and dedicated bgp peers. If false, only dedicated bgp peers will be used.", + true, + ConfigKey.Scope.Account); + + // Methods for DataCenterIpv4GuestSubnet APIs + DataCenterIpv4GuestSubnet createDataCenterIpv4GuestSubnet(CreateIpv4SubnetForZoneCmd createIpv4SubnetForZoneCmd); + + DataCenterIpv4SubnetResponse createDataCenterIpv4SubnetResponse(DataCenterIpv4GuestSubnet result); + + boolean deleteDataCenterIpv4GuestSubnet(DeleteIpv4SubnetForZoneCmd deleteIpv4SubnetForZoneCmd); + + DataCenterIpv4GuestSubnet updateDataCenterIpv4GuestSubnet(UpdateIpv4SubnetForZoneCmd updateIpv4SubnetForZoneCmd); + + List listDataCenterIpv4GuestSubnets(ListIpv4SubnetsForZoneCmd listIpv4SubnetsForZoneCmd); + + DataCenterIpv4GuestSubnet dedicateDataCenterIpv4GuestSubnet(DedicateIpv4SubnetForZoneCmd dedicateIpv4SubnetForZoneCmd); + + DataCenterIpv4GuestSubnet releaseDedicatedDataCenterIpv4GuestSubnet(ReleaseDedicatedIpv4SubnetForZoneCmd releaseDedicatedIpv4SubnetForZoneCmd); + + // Methods for Ipv4SubnetForGuestNetwork APIs + Ipv4GuestSubnetNetworkMap createIpv4SubnetForGuestNetwork(CreateIpv4SubnetForGuestNetworkCmd createIpv4SubnetForGuestNetworkCmd); + + boolean deleteIpv4SubnetForGuestNetwork(DeleteIpv4SubnetForGuestNetworkCmd deleteIpv4SubnetForGuestNetworkCmd); + + void releaseIpv4SubnetForGuestNetwork(long networkId); + + void releaseIpv4SubnetForVpc(long vpcId); + + List listIpv4GuestSubnetsForGuestNetwork(ListIpv4SubnetsForGuestNetworkCmd listIpv4SubnetsForGuestNetworkCmd); + + Ipv4SubnetForGuestNetworkResponse createIpv4SubnetForGuestNetworkResponse(Ipv4GuestSubnetNetworkMap subnet); + + // Methods for internal calls + void getOrCreateIpv4SubnetForGuestNetwork(Network network, String networkCidr); + + Ipv4GuestSubnetNetworkMap getOrCreateIpv4SubnetForGuestNetwork(Long domainId, Long accountId, Long zoneId, Integer networkCidrSize); + + void getOrCreateIpv4SubnetForVpc(Vpc vpc, String networkCidr); + + Ipv4GuestSubnetNetworkMap getOrCreateIpv4SubnetForVpc(Vpc vpc, Integer vpcCidrSize); + + void assignIpv4SubnetToNetwork(Network network); + + void assignIpv4SubnetToVpc(Vpc vpc); + + // Methods for Routing firewall rules + FirewallRule createRoutingFirewallRule(CreateRoutingFirewallRuleCmd createRoutingFirewallRuleCmd) throws NetworkRuleConflictException; + + Pair, Integer> listRoutingFirewallRules(ListRoutingFirewallRulesCmd listRoutingFirewallRulesCmd); + + FirewallRule updateRoutingFirewallRule(UpdateRoutingFirewallRuleCmd updateRoutingFirewallRuleCmd); + + boolean revokeRoutingFirewallRule(Long id); + + boolean applyRoutingFirewallRule(long id); + + boolean isVirtualRouterGateway(Network network); + + boolean isVirtualRouterGateway(NetworkOffering networkOffering); + + boolean isRoutedNetwork(Network network); + + boolean isDynamicRoutedNetwork(Network network); + + boolean isDynamicRoutedNetwork(NetworkOffering networkOffering); + + boolean isRoutedVpc(Vpc vpc); + + boolean isVpcVirtualRouterGateway(VpcOffering vpcOffering); + + BgpPeer createBgpPeer(CreateBgpPeerCmd createBgpPeerCmd); + + BgpPeerResponse createBgpPeerResponse(BgpPeer result); + + boolean deleteBgpPeer(DeleteBgpPeerCmd deleteBgpPeerCmd); + + BgpPeer updateBgpPeer(UpdateBgpPeerCmd updateBgpPeerCmd); + + BgpPeer dedicateBgpPeer(DedicateBgpPeerCmd dedicateBgpPeerCmd); + + BgpPeer releaseDedicatedBgpPeer(ReleaseDedicatedBgpPeerCmd releaseDedicatedBgpPeerCmd); + + List listBgpPeers(ListBgpPeersCmd listBgpPeersCmd); + + Network changeBgpPeersForNetwork(ChangeBgpPeersForNetworkCmd changeBgpPeersForNetworkCmd); + + Network removeBgpPeersFromNetwork(Network network); + + void validateBgpPeers(Account owner, Long zoneId, List bgpPeerIds); + + void persistBgpPeersForGuestNetwork(long networkId, List bgpPeerIds); + + void releaseBgpPeersForGuestNetwork(long networkId); + + boolean isDynamicRoutedVpc(Vpc vpc); + + boolean isDynamicRoutedVpc(VpcOffering vpcOff); + + void persistBgpPeersForVpc(long vpcId, List bgpPeerIds); + + void releaseBgpPeersForVpc(long vpcId); + + Vpc changeBgpPeersForVpc(ChangeBgpPeersForVpcCmd changeBgpPeersForVpcCmd); + + List getBgpPeerIdsForAccount(Account owner, long zoneIdd); + + void removeIpv4SubnetsForZoneByAccountId(long accountId); + + void removeIpv4SubnetsForZoneByDomainId(long domainId); + + void removeBgpPeersByAccountId(long accountId); + + void removeBgpPeersByDomainId(long domainId); + + Boolean isRoutedNetworkVpcEnabled(long zoneId); +} diff --git a/api/src/main/java/org/apache/cloudstack/network/element/InternalLoadBalancerElementService.java b/api/src/main/java/org/apache/cloudstack/network/element/InternalLoadBalancerElementService.java index 76706a4cfc9..1fff54f5f8f 100644 --- a/api/src/main/java/org/apache/cloudstack/network/element/InternalLoadBalancerElementService.java +++ b/api/src/main/java/org/apache/cloudstack/network/element/InternalLoadBalancerElementService.java @@ -52,4 +52,6 @@ public interface InternalLoadBalancerElementService extends PluggableService { * @return */ List searchForInternalLoadBalancerElements(Long id, Long ntwkSvsProviderId, Boolean enabled); + + VirtualRouterProvider.Type getProviderType(); } diff --git a/api/src/main/java/org/apache/cloudstack/outofbandmanagement/OutOfBandManagementService.java b/api/src/main/java/org/apache/cloudstack/outofbandmanagement/OutOfBandManagementService.java index d670e4d3a88..4f6f1ad66c9 100644 --- a/api/src/main/java/org/apache/cloudstack/outofbandmanagement/OutOfBandManagementService.java +++ b/api/src/main/java/org/apache/cloudstack/outofbandmanagement/OutOfBandManagementService.java @@ -39,7 +39,7 @@ public interface OutOfBandManagementService { long getId(); boolean isOutOfBandManagementEnabled(Host host); void submitBackgroundPowerSyncTask(Host host); - boolean transitionPowerStateToDisabled(List hosts); + boolean transitionPowerStateToDisabled(List hostIds); OutOfBandManagementResponse enableOutOfBandManagement(DataCenter zone); OutOfBandManagementResponse enableOutOfBandManagement(Cluster cluster); diff --git a/api/src/main/java/org/apache/cloudstack/query/QueryService.java b/api/src/main/java/org/apache/cloudstack/query/QueryService.java index c93e43d9f37..0f658e5d20d 100644 --- a/api/src/main/java/org/apache/cloudstack/query/QueryService.java +++ b/api/src/main/java/org/apache/cloudstack/query/QueryService.java @@ -16,9 +16,11 @@ // under the License. package org.apache.cloudstack.query; +import java.util.Arrays; import java.util.List; import org.apache.cloudstack.affinity.AffinityGroupResponse; +import org.apache.cloudstack.api.ResponseObject; import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd; import org.apache.cloudstack.api.command.admin.host.ListHostTagsCmd; import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; @@ -96,6 +98,7 @@ import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.framework.config.ConfigKey; import com.cloud.exception.PermissionDeniedException; +import com.cloud.vm.VmDetailConstants; /** * Service used for list api query. @@ -103,15 +106,17 @@ import com.cloud.exception.PermissionDeniedException; */ public interface QueryService { + List RootAdminOnlyVmSettings = Arrays.asList(VmDetailConstants.GUEST_CPU_MODE, VmDetailConstants.GUEST_CPU_MODEL); + // Config keys ConfigKey AllowUserViewDestroyedVM = new ConfigKey<>("Advanced", Boolean.class, "allow.user.view.destroyed.vm", "false", "Determines whether users can view their destroyed or expunging vm ", true, ConfigKey.Scope.Account); - static final ConfigKey UserVMDeniedDetails = new ConfigKey<>(String.class, + ConfigKey UserVMDeniedDetails = new ConfigKey<>(String.class, "user.vm.denied.details", "Advanced", "rootdisksize, cpuOvercommitRatio, memoryOvercommitRatio, Message.ReservedCapacityFreed.Flag", "Determines whether users can view certain VM settings. When set to empty, default value used is: rootdisksize, cpuOvercommitRatio, memoryOvercommitRatio, Message.ReservedCapacityFreed.Flag.", true, ConfigKey.Scope.Global, null, null, null, null, null, ConfigKey.Kind.CSV, null); - static final ConfigKey UserVMReadOnlyDetails = new ConfigKey<>(String.class, + ConfigKey UserVMReadOnlyDetails = new ConfigKey<>(String.class, "user.vm.readonly.details", "Advanced", "dataDiskController, rootDiskController", "List of read-only VM settings/details as comma separated string", true, ConfigKey.Scope.Global, null, null, null, null, null, ConfigKey.Kind.CSV, null); @@ -120,17 +125,21 @@ public interface QueryService { "network offering, zones), we use the flag to determine if the entities should be sorted ascending (when flag is true) " + "or descending (when flag is false). Within the scope of the config all users see the same result.", true, ConfigKey.Scope.Global); - public static final ConfigKey AllowUserViewAllDomainAccounts = new ConfigKey<>("Advanced", Boolean.class, + ConfigKey AllowUserViewAllDomainAccounts = new ConfigKey<>("Advanced", Boolean.class, "allow.user.view.all.domain.accounts", "false", "Determines whether users can view all user accounts within the same domain", true, ConfigKey.Scope.Domain); - static final ConfigKey SharePublicTemplatesWithOtherDomains = new ConfigKey<>("Advanced", Boolean.class, "share.public.templates.with.other.domains", "true", + ConfigKey AllowUserViewAllDataCenters = new ConfigKey<>("Advanced", Boolean.class, "allow.user.view.all.zones", "true", + "Determines whether for instance a Resource Admin can view zones that are not dedicated to them.", true, ConfigKey.Scope.Domain); + + ConfigKey SharePublicTemplatesWithOtherDomains = new ConfigKey<>("Advanced", Boolean.class, "share.public.templates.with.other.domains", "true", "If false, templates of this domain will not show up in the list templates of other domains.", true, ConfigKey.Scope.Domain); ConfigKey ReturnVmStatsOnVmList = new ConfigKey<>("Advanced", Boolean.class, "list.vm.default.details.stats", "true", "Determines whether VM stats should be returned when details are not explicitly specified in listVirtualMachines API request. When false, details default to [group, nics, secgrp, tmpl, servoff, diskoff, backoff, iso, volume, min, affgrp]. When true, all details are returned including 'stats'.", true, ConfigKey.Scope.Global); - ListResponse searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException; + + ListResponse searchForUsers(ResponseObject.ResponseView responseView, ListUsersCmd cmd) throws PermissionDeniedException; ListResponse searchForUsers(Long domainId, boolean recursive) throws PermissionDeniedException; diff --git a/api/src/main/java/org/apache/cloudstack/resource/ResourceCleanupService.java b/api/src/main/java/org/apache/cloudstack/resource/ResourceCleanupService.java new file mode 100644 index 00000000000..0d72edb0748 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/resource/ResourceCleanupService.java @@ -0,0 +1,74 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.resource; + +import org.apache.cloudstack.api.command.admin.resource.PurgeExpungedResourcesCmd; +import org.apache.cloudstack.framework.config.ConfigKey; + +import com.cloud.vm.VirtualMachine; + +public interface ResourceCleanupService { + int MINIMUM_EXPUNGED_RESOURCE_PURGE_JOB_DELAY_IN_SECONDS = 3 * 60; + ConfigKey ExpungedResourcePurgeEnabled = new ConfigKey<>("Advanced", Boolean.class, + "expunged.resources.purge.enabled", "false", + "Whether to run a background task to purge the DB records of the expunged resources", + false, ConfigKey.Scope.Global); + ConfigKey ExpungedResourcePurgeResources = new ConfigKey<>("Advanced", String.class, + "expunged.resources.purge.resources", "", + "A comma-separated list of resource types that will be considered by the background task " + + "to purge the DB records of the expunged resources. Currently only VirtualMachine is supported. " + + "An empty value will result in considering all resource types for purging", + false, ConfigKey.Scope.Global); + ConfigKey ExpungedResourcesPurgeInterval = new ConfigKey<>("Advanced", Integer.class, + "expunged.resources.purge.interval", "86400", + "Interval (in seconds) for the background task to purge the DB records of the expunged resources", + false); + ConfigKey ExpungedResourcesPurgeDelay = new ConfigKey<>("Advanced", Integer.class, + "expunged.resources.purge.delay", "300", + "Initial delay (in seconds) to start the background task to purge the DB records of the " + + "expunged resources task", false); + ConfigKey ExpungedResourcesPurgeBatchSize = new ConfigKey<>("Advanced", Integer.class, + "expunged.resources.purge.batch.size", "50", + "Batch size to be used during purging of the DB records of the expunged resources", + true); + ConfigKey ExpungedResourcesPurgeStartTime = new ConfigKey<>("Advanced", String.class, + "expunged.resources.purge.start.time", "", + "Start time to be used by the background task to purge the DB records of the expunged " + + "resources. Use format \"yyyy-MM-dd\" or \"yyyy-MM-dd HH:mm:ss\"", true); + ConfigKey ExpungedResourcesPurgeKeepPastDays = new ConfigKey<>("Advanced", Integer.class, + "expunged.resources.purge.keep.past.days", "30", + "The number of days in the past from the execution time of the background task to purge " + + "the DB records of the expunged resources for which the expunged resources must not be purged. " + + "To enable purging DB records of the expunged resource till the execution of the background " + + "task, set the value to zero.", true); + ConfigKey ExpungedResourcePurgeJobDelay = new ConfigKey<>("Advanced", Integer.class, + "expunged.resource.purge.job.delay", + String.valueOf(MINIMUM_EXPUNGED_RESOURCE_PURGE_JOB_DELAY_IN_SECONDS), + String.format("Delay (in seconds) to execute the purging of the DB records of an expunged resource " + + "initiated by the configuration in the offering. Minimum value should be %d seconds " + + "and if a lower value is set then the minimum value will be used", + MINIMUM_EXPUNGED_RESOURCE_PURGE_JOB_DELAY_IN_SECONDS), + true); + + enum ResourceType { + VirtualMachine + } + + long purgeExpungedResources(PurgeExpungedResourcesCmd cmd); + void purgeExpungedVmResourcesLaterIfNeeded(VirtualMachine vm); +} diff --git a/api/src/main/java/org/apache/cloudstack/storage/browser/DataStoreObjectResponse.java b/api/src/main/java/org/apache/cloudstack/storage/browser/DataStoreObjectResponse.java index cac5cc91b03..c281fa115fd 100644 --- a/api/src/main/java/org/apache/cloudstack/storage/browser/DataStoreObjectResponse.java +++ b/api/src/main/java/org/apache/cloudstack/storage/browser/DataStoreObjectResponse.java @@ -41,6 +41,10 @@ public class DataStoreObjectResponse extends BaseResponse { @Param(description = "Template ID associated with the data store object.") private String templateId; + @SerializedName(ApiConstants.TEMPLATE_NAME) + @Param(description = "Template Name associated with the data store object.") + private String templateName; + @SerializedName(ApiConstants.FORMAT) @Param(description = "Format of template associated with the data store object.") private String format; @@ -49,10 +53,18 @@ public class DataStoreObjectResponse extends BaseResponse { @Param(description = "Snapshot ID associated with the data store object.") private String snapshotId; + @SerializedName("snapshotname") + @Param(description = "Snapshot Name associated with the data store object.") + private String snapshotName; + @SerializedName(ApiConstants.VOLUME_ID) @Param(description = "Volume ID associated with the data store object.") private String volumeId; + @SerializedName(ApiConstants.VOLUME_NAME) + @Param(description = "Volume Name associated with the data store object.") + private String volumeName; + @SerializedName(ApiConstants.LAST_UPDATED) @Param(description = "Last modified date of the file/directory.") private Date lastUpdated; @@ -86,6 +98,18 @@ public class DataStoreObjectResponse extends BaseResponse { this.volumeId = volumeId; } + public void setTemplateName(String templateName) { + this.templateName = templateName; + } + + public void setSnapshotName(String snapshotName) { + this.snapshotName = snapshotName; + } + + public void setVolumeName(String volumeName) { + this.volumeName = volumeName; + } + public String getName() { return name; } @@ -117,4 +141,16 @@ public class DataStoreObjectResponse extends BaseResponse { public Date getLastUpdated() { return lastUpdated; } + + public String getTemplateName() { + return templateName; + } + + public String getSnapshotName() { + return snapshotName; + } + + public String getVolumeName() { + return volumeName; + } } diff --git a/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFS.java b/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFS.java new file mode 100644 index 00000000000..bcba425abbf --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFS.java @@ -0,0 +1,189 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.storage.sharedfs; + +import com.cloud.utils.fsm.StateMachine2; +import com.cloud.utils.fsm.StateObject; + +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; +import org.apache.cloudstack.framework.config.ConfigKey; + +import java.util.Date; + +public interface SharedFS extends ControlledEntity, Identity, InternalIdentity, StateObject { + + static final ConfigKey SharedFSFeatureEnabled = new ConfigKey("Advanced", Boolean.class, + "sharedfs.feature.enabled", + "true", + " Indicates whether the Shared FileSystem feature is enabled or not. Management server restart needed on change", + false); + + ConfigKey SharedFSCleanupInterval = new ConfigKey<>(Integer.class, + "sharedfs.cleanup.interval", + "Advanced", + "14400", + "The interval (in seconds) to wait before running the shared filesystem cleanup thread.", + false, + ConfigKey.Scope.Global, + null, + SharedFSFeatureEnabled.key()); + + ConfigKey SharedFSCleanupDelay = new ConfigKey<>(Integer.class, + "sharedfs.cleanup.delay", + "Advanced", + "86400", + "Determines how long (in seconds) to wait before actually expunging destroyed shared filesystem.", + false, + ConfigKey.Scope.Global, + null, + SharedFSFeatureEnabled.key()); + + ConfigKey SharedFSExpungeWorkers = new ConfigKey<>(Integer.class, + "sharedfs.expunge.workers", + "Advanced", + "2", + "Determines how many threads are created to do the work of expunging destroyed shared filesystem.", + false, + ConfigKey.Scope.Global, + null, + SharedFSFeatureEnabled.key()); + + String SharedFSVmNamePrefix = "sharedfs"; + String SharedFSPath = "/export"; + + enum FileSystemType { + EXT4, XFS + } + + enum Protocol { + NFS + } + + enum State { + Allocated(false, "The shared filesystem is allocated in db but hasn't been created or started yet."), + Ready(false, "The shared filesystem is ready to use."), + Stopping(true, "The shared filesystem is being stopped"), + Stopped(false, "The shared filesystem is in stopped state. It can not be used but the data is still there."), + Starting(true, "The shared filesystem is being started."), + Destroyed(false, "The shared filesystem is destroyed."), + Expunging(true, "The shared filesystem is being expunged."), + Expunged(false, "The shared filesystem has been expunged."), + Error(false, "The shared filesystem is in error state."); + + boolean _transitional; + String _description; + + /** + * SharedFS State + * + * @param transitional true for transition/non-final state, otherwise false + * @param description description of the state + */ + State(boolean transitional, String description) { + _transitional = transitional; + _description = description; + } + + public boolean isTransitional() { + return _transitional; + } + + public String getDescription() { + return _description; + } + + private final static StateMachine2 s_fsm = new StateMachine2(); + + public static StateMachine2 getStateMachine() { + return s_fsm; + } + + static { + s_fsm.addTransition(new StateMachine2.Transition(Allocated, Event.OperationFailed, Error, null)); + s_fsm.addTransition(new StateMachine2.Transition(Allocated, Event.OperationSucceeded, Ready, null)); + s_fsm.addTransition(new StateMachine2.Transition(Error, Event.DestroyRequested, Destroyed, null)); + s_fsm.addTransition(new StateMachine2.Transition(Stopped, Event.StartRequested, Starting, null)); + s_fsm.addTransition(new StateMachine2.Transition(Starting, Event.OperationSucceeded, Ready, null)); + s_fsm.addTransition(new StateMachine2.Transition(Starting, Event.OperationFailed, Stopped, null)); + s_fsm.addTransition(new StateMachine2.Transition(Ready, Event.StopRequested, Stopping, null)); + s_fsm.addTransition(new StateMachine2.Transition(Stopping, Event.OperationSucceeded, Stopped, null)); + s_fsm.addTransition(new StateMachine2.Transition(Stopping, Event.OperationFailed, Ready, null)); + s_fsm.addTransition(new StateMachine2.Transition(Stopped, Event.DestroyRequested, Destroyed, null)); + s_fsm.addTransition(new StateMachine2.Transition(Destroyed, Event.RecoveryRequested, Stopped, null)); + s_fsm.addTransition(new StateMachine2.Transition(Destroyed, Event.ExpungeOperation, Expunging, null)); + s_fsm.addTransition(new StateMachine2.Transition(Error, Event.ExpungeOperation, Expunging, null)); + s_fsm.addTransition(new StateMachine2.Transition(Expunging, Event.ExpungeOperation, Expunging, null)); + s_fsm.addTransition(new StateMachine2.Transition(Expunging, Event.OperationSucceeded, Expunged, null)); + } + } + + enum Event { + StopRequested, + StartRequested, + DestroyRequested, + OperationSucceeded, + OperationFailed, + ExpungeOperation, + RecoveryRequested, + } + + static String getSharedFSPath() { + return SharedFSPath; + } + + long getId(); + + String getName(); + + void setName(String name); + + String getUuid(); + + String getDescription(); + + void setDescription(String description); + + Long getDataCenterId(); + + State getState(); + + String getFsProviderName(); + + Protocol getProtocol(); + + Long getVolumeId(); + + void setVolumeId(Long volumeId); + + Long getVmId(); + + void setVmId(Long vmId); + + FileSystemType getFsType(); + + Long getServiceOfferingId(); + + void setServiceOfferingId(Long serviceOfferingId); + + Date getUpdated(); + + public long getUpdatedCount(); + + public void incrUpdatedCount(); +} diff --git a/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFSLifeCycle.java b/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFSLifeCycle.java new file mode 100644 index 00000000000..552dcf79f78 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFSLifeCycle.java @@ -0,0 +1,43 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.storage.sharedfs; + +import com.cloud.dc.DataCenter; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ManagementServerException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.exception.VirtualMachineMigrationException; +import com.cloud.utils.Pair; + +public interface SharedFSLifeCycle { + void checkPrerequisites(DataCenter zone, Long serviceOfferingId); + + Pair deploySharedFS(SharedFS sharedFS, Long networkId, Long diskOfferingId, Long size, Long minIops, Long maxIops) throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException, OperationTimedoutException; + + void startSharedFS(SharedFS sharedFS) throws OperationTimedoutException, ResourceUnavailableException, InsufficientCapacityException; + + boolean stopSharedFS(SharedFS sharedFS, Boolean forced); + + boolean deleteSharedFS(SharedFS sharedFS); + + boolean reDeploySharedFS(SharedFS sharedFS) throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException, OperationTimedoutException; + + boolean changeSharedFSServiceOffering(SharedFS sharedFS, Long serviceOfferingId) throws ManagementServerException, ResourceUnavailableException, VirtualMachineMigrationException; +} diff --git a/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFSProvider.java b/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFSProvider.java new file mode 100644 index 00000000000..3966970f188 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFSProvider.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.storage.sharedfs; + +import com.cloud.utils.component.Adapter; + +public interface SharedFSProvider extends Adapter { + + enum SharedFSProviderType { + SHAREDFSVM + } + + void configure(); + + SharedFSLifeCycle getSharedFSLifeCycle(); +} diff --git a/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFSService.java b/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFSService.java new file mode 100644 index 00000000000..21184de27a2 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/storage/sharedfs/SharedFSService.java @@ -0,0 +1,72 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.storage.sharedfs; + +import java.util.List; + +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.command.user.storage.sharedfs.ChangeSharedFSDiskOfferingCmd; +import org.apache.cloudstack.api.command.user.storage.sharedfs.ChangeSharedFSServiceOfferingCmd; +import org.apache.cloudstack.api.command.user.storage.sharedfs.CreateSharedFSCmd; +import org.apache.cloudstack.api.command.user.storage.sharedfs.DestroySharedFSCmd; + +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ManagementServerException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.exception.VirtualMachineMigrationException; + +import org.apache.cloudstack.api.command.user.storage.sharedfs.ListSharedFSCmd; +import org.apache.cloudstack.api.command.user.storage.sharedfs.UpdateSharedFSCmd; +import org.apache.cloudstack.api.response.SharedFSResponse; +import org.apache.cloudstack.api.response.ListResponse; + +public interface SharedFSService { + + List getSharedFSProviders(); + + boolean stateTransitTo(SharedFS sharedFS, SharedFS.Event event); + + void setSharedFSProviders(List sharedFSProviders); + + SharedFSProvider getSharedFSProvider(String sharedFSProviderName); + + SharedFS allocSharedFS(CreateSharedFSCmd cmd); + + SharedFS deploySharedFS(CreateSharedFSCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException, OperationTimedoutException; + + SharedFS startSharedFS(Long sharedFSId) throws OperationTimedoutException, ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException; + + SharedFS stopSharedFS(Long sharedFSId, Boolean forced); + + SharedFS restartSharedFS(Long sharedFSId, boolean cleanup) throws OperationTimedoutException, ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException; + + ListResponse searchForSharedFS(ResponseObject.ResponseView respView, ListSharedFSCmd cmd); + + SharedFS updateSharedFS(UpdateSharedFSCmd cmd); + + SharedFS changeSharedFSDiskOffering(ChangeSharedFSDiskOfferingCmd cmd) throws ResourceAllocationException; + + SharedFS changeSharedFSServiceOffering(ChangeSharedFSServiceOfferingCmd cmd) throws OperationTimedoutException, ResourceUnavailableException, InsufficientCapacityException, ManagementServerException, VirtualMachineMigrationException; + + Boolean destroySharedFS(DestroySharedFSCmd cmd); + + SharedFS recoverSharedFS(Long sharedFSId); + + void deleteSharedFS(Long sharedFSId); +} diff --git a/api/src/main/java/org/apache/cloudstack/usage/UsageService.java b/api/src/main/java/org/apache/cloudstack/usage/UsageService.java index 73962ba5875..00e8b431f8f 100644 --- a/api/src/main/java/org/apache/cloudstack/usage/UsageService.java +++ b/api/src/main/java/org/apache/cloudstack/usage/UsageService.java @@ -20,7 +20,6 @@ import com.cloud.utils.Pair; import org.apache.cloudstack.api.command.admin.usage.GenerateUsageRecordsCmd; import org.apache.cloudstack.api.command.admin.usage.ListUsageRecordsCmd; import org.apache.cloudstack.api.command.admin.usage.RemoveRawUsageRecordsCmd; -import org.apache.cloudstack.api.response.UsageTypeResponse; import java.util.List; import java.util.TimeZone; @@ -62,6 +61,4 @@ public interface UsageService { TimeZone getUsageTimezone(); boolean removeRawUsageRecords(RemoveRawUsageRecordsCmd cmd); - - List listUsageTypes(); } diff --git a/api/src/main/java/org/apache/cloudstack/usage/UsageTypes.java b/api/src/main/java/org/apache/cloudstack/usage/UsageTypes.java index 32ae34056ec..5ad360a8026 100644 --- a/api/src/main/java/org/apache/cloudstack/usage/UsageTypes.java +++ b/api/src/main/java/org/apache/cloudstack/usage/UsageTypes.java @@ -51,31 +51,31 @@ public class UsageTypes { public static List listUsageTypes() { List responseList = new ArrayList(); - responseList.add(new UsageTypeResponse(RUNNING_VM, "Running Vm Usage")); - responseList.add(new UsageTypeResponse(ALLOCATED_VM, "Allocated Vm Usage")); - responseList.add(new UsageTypeResponse(IP_ADDRESS, "IP Address Usage")); - responseList.add(new UsageTypeResponse(NETWORK_BYTES_SENT, "Network Usage (Bytes Sent)")); - responseList.add(new UsageTypeResponse(NETWORK_BYTES_RECEIVED, "Network Usage (Bytes Received)")); - responseList.add(new UsageTypeResponse(VOLUME, "Volume Usage")); - responseList.add(new UsageTypeResponse(TEMPLATE, "Template Usage")); - responseList.add(new UsageTypeResponse(ISO, "ISO Usage")); - responseList.add(new UsageTypeResponse(SNAPSHOT, "Snapshot Usage")); - responseList.add(new UsageTypeResponse(SECURITY_GROUP, "Security Group Usage")); - responseList.add(new UsageTypeResponse(LOAD_BALANCER_POLICY, "Load Balancer Usage")); - responseList.add(new UsageTypeResponse(PORT_FORWARDING_RULE, "Port Forwarding Usage")); - responseList.add(new UsageTypeResponse(NETWORK_OFFERING, "Network Offering Usage")); - responseList.add(new UsageTypeResponse(VPN_USERS, "VPN users usage")); - responseList.add(new UsageTypeResponse(VM_DISK_IO_READ, "VM Disk usage(I/O Read)")); - responseList.add(new UsageTypeResponse(VM_DISK_IO_WRITE, "VM Disk usage(I/O Write)")); - responseList.add(new UsageTypeResponse(VM_DISK_BYTES_READ, "VM Disk usage(Bytes Read)")); - responseList.add(new UsageTypeResponse(VM_DISK_BYTES_WRITE, "VM Disk usage(Bytes Write)")); - responseList.add(new UsageTypeResponse(VM_SNAPSHOT, "VM Snapshot storage usage")); - responseList.add(new UsageTypeResponse(VOLUME_SECONDARY, "Volume on secondary storage usage")); - responseList.add(new UsageTypeResponse(VM_SNAPSHOT_ON_PRIMARY, "VM Snapshot on primary storage usage")); - responseList.add(new UsageTypeResponse(BACKUP, "Backup storage usage")); - responseList.add(new UsageTypeResponse(BUCKET, "Bucket storage usage")); - responseList.add(new UsageTypeResponse(NETWORK, "Network usage")); - responseList.add(new UsageTypeResponse(VPC, "VPC usage")); + responseList.add(new UsageTypeResponse(RUNNING_VM, "RUNNING_VM", "Running Vm Usage")); + responseList.add(new UsageTypeResponse(ALLOCATED_VM, "ALLOCATED_VM", "Allocated Vm Usage")); + responseList.add(new UsageTypeResponse(IP_ADDRESS, "IP_ADDRESS", "IP Address Usage")); + responseList.add(new UsageTypeResponse(NETWORK_BYTES_SENT, "NETWORK_BYTES_SENT", "Network Usage (Bytes Sent)")); + responseList.add(new UsageTypeResponse(NETWORK_BYTES_RECEIVED, "NETWORK_BYTES_RECEIVED", "Network Usage (Bytes Received)")); + responseList.add(new UsageTypeResponse(VOLUME, "VOLUME", "Volume Usage")); + responseList.add(new UsageTypeResponse(TEMPLATE, "TEMPLATE", "Template Usage")); + responseList.add(new UsageTypeResponse(ISO, "ISO", "ISO Usage")); + responseList.add(new UsageTypeResponse(SNAPSHOT, "SNAPSHOT", "Snapshot Usage")); + responseList.add(new UsageTypeResponse(SECURITY_GROUP, "SECURITY_GROUP", "Security Group Usage")); + responseList.add(new UsageTypeResponse(LOAD_BALANCER_POLICY, "LOAD_BALANCER_POLICY", "Load Balancer Usage")); + responseList.add(new UsageTypeResponse(PORT_FORWARDING_RULE, "PORT_FORWARDING_RULE", "Port Forwarding Usage")); + responseList.add(new UsageTypeResponse(NETWORK_OFFERING, "NETWORK_OFFERING", "Network Offering Usage")); + responseList.add(new UsageTypeResponse(VPN_USERS, "VPN_USERS", "VPN users usage")); + responseList.add(new UsageTypeResponse(VM_DISK_IO_READ, "VM_DISK_IO_READ", "VM Disk usage(I/O Read)")); + responseList.add(new UsageTypeResponse(VM_DISK_IO_WRITE, "VM_DISK_IO_WRITE", "VM Disk usage(I/O Write)")); + responseList.add(new UsageTypeResponse(VM_DISK_BYTES_READ, "VM_DISK_BYTES_READ", "VM Disk usage(Bytes Read)")); + responseList.add(new UsageTypeResponse(VM_DISK_BYTES_WRITE, "VM_DISK_BYTES_WRITE", "VM Disk usage(Bytes Write)")); + responseList.add(new UsageTypeResponse(VM_SNAPSHOT, "VM_SNAPSHOT", "VM Snapshot storage usage")); + responseList.add(new UsageTypeResponse(VOLUME_SECONDARY, "VOLUME_SECONDARY", "Volume on secondary storage usage")); + responseList.add(new UsageTypeResponse(VM_SNAPSHOT_ON_PRIMARY, "VM_SNAPSHOT_ON_PRIMARY", "VM Snapshot on primary storage usage")); + responseList.add(new UsageTypeResponse(BACKUP, "BACKUP", "Backup storage usage")); + responseList.add(new UsageTypeResponse(BUCKET, "BUCKET", "Bucket storage usage")); + responseList.add(new UsageTypeResponse(NETWORK, "NETWORK", "Network usage")); + responseList.add(new UsageTypeResponse(VPC, "VPC", "VPC usage")); return responseList; } } diff --git a/api/src/main/java/org/apache/cloudstack/user/ResourceReservation.java b/api/src/main/java/org/apache/cloudstack/user/ResourceReservation.java index 170193570cf..d49120d4491 100644 --- a/api/src/main/java/org/apache/cloudstack/user/ResourceReservation.java +++ b/api/src/main/java/org/apache/cloudstack/user/ResourceReservation.java @@ -18,9 +18,12 @@ // package org.apache.cloudstack.user; -import com.cloud.configuration.Resource; import org.apache.cloudstack.api.InternalIdentity; +import com.cloud.configuration.Resource; + +import java.util.Date; + /** * an interface defining an {code}AutoClosable{code} reservation object */ @@ -33,5 +36,11 @@ ResourceReservation extends InternalIdentity { Resource.ResourceType getResourceType(); + Long getResourceId(); + + String getTag(); + Long getReservedAmount(); + + Date getCreated(); } diff --git a/api/src/main/java/org/apache/cloudstack/vm/UnmanagedInstanceTO.java b/api/src/main/java/org/apache/cloudstack/vm/UnmanagedInstanceTO.java index f1027b74eca..bba97dff71c 100644 --- a/api/src/main/java/org/apache/cloudstack/vm/UnmanagedInstanceTO.java +++ b/api/src/main/java/org/apache/cloudstack/vm/UnmanagedInstanceTO.java @@ -17,7 +17,7 @@ package org.apache.cloudstack.vm; -import static com.cloud.utils.NumbersUtil.toHumanReadableSize; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import java.util.List; @@ -192,6 +192,13 @@ public class UnmanagedInstanceTO { this.vncPassword = vncPassword; } + @Override + public String toString() { + return String.format("UnmanagedInstanceTO %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "name", "internalCSName", "hostName", "clusterName")); + } + public String getBootType() { return bootType; } @@ -351,12 +358,9 @@ public class UnmanagedInstanceTO { @Override public String toString() { - return "Disk {" + - "diskId='" + diskId + '\'' + - ", capacity=" + toHumanReadableSize(capacity) + - ", controller='" + controller + '\'' + - ", controllerUnit=" + controllerUnit + - "}"; + return String.format("Disk %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "diskId", "internalCSName", "controller", "controllerUnit")); } } @@ -453,11 +457,9 @@ public class UnmanagedInstanceTO { @Override public String toString() { - return "Nic{" + - "nicId='" + nicId + '\'' + - ", adapterType='" + adapterType + '\'' + - ", macAddress='" + macAddress + '\'' + - "}"; + return String.format("Nic %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "nicId", "adapterType", "macAddress")); } } } diff --git a/api/src/main/resources/META-INF/cloudstack/api-config/spring-api-config-context.xml b/api/src/main/resources/META-INF/cloudstack/api-config/spring-api-config-context.xml index 5ea32464ee9..12d3c2361ac 100644 --- a/api/src/main/resources/META-INF/cloudstack/api-config/spring-api-config-context.xml +++ b/api/src/main/resources/META-INF/cloudstack/api-config/spring-api-config-context.xml @@ -28,5 +28,5 @@ > - + diff --git a/api/src/main/resources/META-INF/cloudstack/api-planner/spring-api-planner-context.xml b/api/src/main/resources/META-INF/cloudstack/api-planner/spring-api-planner-context.xml index 8523daf1d21..b614e362950 100644 --- a/api/src/main/resources/META-INF/cloudstack/api-planner/spring-api-planner-context.xml +++ b/api/src/main/resources/META-INF/cloudstack/api-planner/spring-api-planner-context.xml @@ -30,5 +30,5 @@ - + diff --git a/api/src/test/java/com/cloud/agent/api/to/LoadBalancerTOTest.java b/api/src/test/java/com/cloud/agent/api/to/LoadBalancerTOTest.java index b12c1b81d4a..e7ecbebae7b 100644 --- a/api/src/test/java/com/cloud/agent/api/to/LoadBalancerTOTest.java +++ b/api/src/test/java/com/cloud/agent/api/to/LoadBalancerTOTest.java @@ -41,16 +41,19 @@ public class LoadBalancerTOTest { LoadBalancerTO.AutoScaleVmGroupTO vmGroup; private static final Long counterId = 1L; + private static final String counterUuid = "1111-1111-1100"; private static final String counterName = "counter name"; private static final Counter.Source counterSource = Counter.Source.CPU; private static final String counterValue = "counter value"; private static final String counterProvider = "VIRTUALROUTER"; private static final Long conditionId = 2L; + private static final String conditionUuid = "1111-1111-1110"; private static final Long threshold = 100L; private static final Condition.Operator relationalOperator = Condition.Operator.GT; private static final Long scaleUpPolicyId = 11L; + private static final String scaleUpPolicyUuid = "1111-1111-1111"; private static final int scaleUpPolicyDuration = 61; private static final int scaleUpPolicyQuietTime = 31; private static final Date scaleUpPolicyLastQuietTime = new Date(); @@ -85,14 +88,14 @@ public class LoadBalancerTOTest { @Before public void setUp() { - counter = new LoadBalancerTO.CounterTO(counterId, counterName, counterSource, counterValue, counterProvider); - condition = new LoadBalancerTO.ConditionTO(conditionId, threshold, relationalOperator, counter); - scaleUpPolicy = new LoadBalancerTO.AutoScalePolicyTO(scaleUpPolicyId, scaleUpPolicyDuration, scaleUpPolicyQuietTime, - scaleUpPolicyLastQuietTime, AutoScalePolicy.Action.SCALEUP, - Arrays.asList(new LoadBalancerTO.ConditionTO[]{ condition }), false); - scaleDownPolicy = new LoadBalancerTO.AutoScalePolicyTO(scaleDownPolicyId, scaleDownPolicyDuration, scaleDownPolicyQuietTime, - scaleDownPolicyLastQuietTime, AutoScalePolicy.Action.SCALEDOWN, - Arrays.asList(new LoadBalancerTO.ConditionTO[]{ condition }), false); + counter = new LoadBalancerTO.CounterTO(counterId, counterUuid, counterName, counterSource, counterValue, counterProvider); + condition = new LoadBalancerTO.ConditionTO(conditionId, conditionUuid, threshold, relationalOperator, counter); + scaleUpPolicy = new LoadBalancerTO.AutoScalePolicyTO(scaleUpPolicyId, scaleUpPolicyUuid, scaleUpPolicyDuration, + scaleUpPolicyQuietTime, scaleUpPolicyLastQuietTime, + AutoScalePolicy.Action.SCALEUP, Arrays.asList(new LoadBalancerTO.ConditionTO[]{ condition }), false); + scaleDownPolicy = new LoadBalancerTO.AutoScalePolicyTO(scaleDownPolicyId, scaleUpPolicyUuid, scaleDownPolicyDuration, + scaleDownPolicyQuietTime, scaleDownPolicyLastQuietTime, + AutoScalePolicy.Action.SCALEDOWN, Arrays.asList(new LoadBalancerTO.ConditionTO[]{ condition }), false); vmProfile = new LoadBalancerTO.AutoScaleVmProfileTO(zoneId, domainId, cloudStackApiUrl, autoScaleUserApiKey, autoScaleUserSecretKey, serviceOfferingId, templateId, vmName, networkId, otherDeployParams, counterParamList, expungeVmGracePeriod); @@ -113,6 +116,7 @@ public class LoadBalancerTOTest { @Test public void testConditionTO() { Assert.assertEquals(conditionId, condition.getId()); + Assert.assertEquals(conditionUuid, condition.getUuid()); Assert.assertEquals((long) threshold, condition.getThreshold()); Assert.assertEquals(relationalOperator, condition.getRelationalOperator()); Assert.assertEquals(counter, condition.getCounter()); diff --git a/api/src/test/java/com/cloud/cpu/CPUTest.java b/api/src/test/java/com/cloud/cpu/CPUTest.java new file mode 100644 index 00000000000..dfedf21864c --- /dev/null +++ b/api/src/test/java/com/cloud/cpu/CPUTest.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.cpu; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class CPUTest { + @Test + public void testCPUArchGetType() { + assertEquals("i686", CPU.CPUArch.x86.getType()); + assertEquals("x86_64", CPU.CPUArch.amd64.getType()); + assertEquals("aarch64", CPU.CPUArch.arm64.getType()); + } + + @Test + public void testCPUArchGetBits() { + assertEquals(32, CPU.CPUArch.x86.getBits()); + assertEquals(64, CPU.CPUArch.amd64.getBits()); + assertEquals(64, CPU.CPUArch.arm64.getBits()); + } + + @Test + public void testCPUArchFromTypeWithValidValues() { + assertEquals(CPU.CPUArch.x86, CPU.CPUArch.fromType("i686")); + assertEquals(CPU.CPUArch.amd64, CPU.CPUArch.fromType("x86_64")); + assertEquals(CPU.CPUArch.arm64, CPU.CPUArch.fromType("aarch64")); + } + + @Test + public void testCPUArchFromTypeWithDefaultForBlankOrNull() { + assertEquals(CPU.CPUArch.amd64, CPU.CPUArch.fromType("")); + assertEquals(CPU.CPUArch.amd64, CPU.CPUArch.fromType(" ")); + assertEquals(CPU.CPUArch.amd64, CPU.CPUArch.fromType(null)); + } + + @Test + public void testCPUArchFromTypeWithInvalidValue() { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + CPU.CPUArch.fromType("unsupported"); + }); + assertTrue(exception.getMessage().contains("Unsupported arch type: unsupported")); + } + + @Test + public void testCPUArchGetTypesAsCSV() { + String expectedCSV = "i686,x86_64,aarch64"; + assertEquals(expectedCSV, CPU.CPUArch.getTypesAsCSV()); + } +} diff --git a/api/src/test/java/com/cloud/network/NetworksTest.java b/api/src/test/java/com/cloud/network/NetworksTest.java index ef582924342..6f0f3fbd1ef 100644 --- a/api/src/test/java/com/cloud/network/NetworksTest.java +++ b/api/src/test/java/com/cloud/network/NetworksTest.java @@ -37,6 +37,24 @@ public class NetworksTest { public void setUp() { } + @Test + public void nullBroadcastDomainTypeTest() throws URISyntaxException { + BroadcastDomainType type = BroadcastDomainType.getTypeOf(null); + Assert.assertEquals("a null uri should mean a broadcasttype of undecided", BroadcastDomainType.UnDecided, type); + } + + @Test + public void nullBroadcastDomainTypeValueTest() { + URI uri = null; + Assert.assertNull(BroadcastDomainType.getValue(uri)); + } + + @Test + public void nullBroadcastDomainTypeStringValueTest() throws URISyntaxException { + String uriString = null; + Assert.assertNull(BroadcastDomainType.getValue(uriString)); + } + @Test public void emptyBroadcastDomainTypeTest() throws URISyntaxException { BroadcastDomainType type = BroadcastDomainType.getTypeOf(""); diff --git a/api/src/test/java/com/cloud/storage/StorageTest.java b/api/src/test/java/com/cloud/storage/StorageTest.java index 76fd5c5d3a4..2bcc28e2b4b 100644 --- a/api/src/test/java/com/cloud/storage/StorageTest.java +++ b/api/src/test/java/com/cloud/storage/StorageTest.java @@ -74,4 +74,13 @@ public class StorageTest { Assert.assertTrue(StoragePoolType.DatastoreCluster.supportsOverProvisioning()); Assert.assertTrue(StoragePoolType.Linstor.supportsOverProvisioning()); } + + @Test + public void equalityTest() { + StoragePoolType t1 = StoragePoolType.NetworkFilesystem; + StoragePoolType t2 = StoragePoolType.NetworkFilesystem; + Assert.assertTrue(t1 == StoragePoolType.NetworkFilesystem); + Assert.assertTrue(t1.equals(StoragePoolType.NetworkFilesystem)); + Assert.assertFalse(t1.equals(StoragePoolType.EXT)); + } } diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmdTest.java index d26065da21c..365646de7a3 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/account/CreateAccountCmdTest.java @@ -22,7 +22,8 @@ import org.apache.cloudstack.acl.RoleService; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -38,7 +39,7 @@ import com.cloud.user.AccountService; import com.cloud.user.User; public class CreateAccountCmdTest { - public static final Logger s_logger = Logger.getLogger(CreateAccountCmdTest.class.getName()); + protected Logger logger = LogManager.getLogger(getClass()); @Mock private AccountService accountService; diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/CreateASNRangeCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/CreateASNRangeCmdTest.java new file mode 100644 index 00000000000..603cda2040d --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/CreateASNRangeCmdTest.java @@ -0,0 +1,69 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.bgp; + +import com.cloud.bgp.ASNumberRange; +import com.cloud.bgp.BGPService; + +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.response.ASNRangeResponse; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class CreateASNRangeCmdTest { + + BGPService bgpService = Mockito.spy(BGPService.class); + ResponseGenerator _responseGenerator = Mockito.spy(ResponseGenerator.class); + + @Test + public void testCreateASNRangeCmd() { + Long zoneId = 1L; + Long startASNumber = 110000L; + Long endASNumber = 120000L; + + CreateASNRangeCmd cmd = new CreateASNRangeCmd(); + ReflectionTestUtils.setField(cmd, "zoneId", zoneId); + ReflectionTestUtils.setField(cmd, "startASNumber", startASNumber); + ReflectionTestUtils.setField(cmd, "endASNumber", endASNumber); + ReflectionTestUtils.setField(cmd,"bgpService", bgpService); + ReflectionTestUtils.setField(cmd,"_responseGenerator", _responseGenerator); + + Assert.assertEquals(zoneId, cmd.getZoneId()); + Assert.assertEquals(startASNumber, cmd.getStartASNumber()); + Assert.assertEquals(endASNumber, cmd.getEndASNumber()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + + ASNumberRange asnRange = Mockito.mock(ASNumberRange.class); + Mockito.when(bgpService.createASNumberRange(zoneId, startASNumber, endASNumber)).thenReturn(asnRange); + + ASNRangeResponse response = Mockito.mock(ASNRangeResponse.class); + Mockito.when(_responseGenerator.createASNumberRangeResponse(asnRange)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/DeleteASNRangeCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/DeleteASNRangeCmdTest.java new file mode 100644 index 00000000000..2abcf736c5b --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/DeleteASNRangeCmdTest.java @@ -0,0 +1,55 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.bgp; + +import com.cloud.bgp.BGPService; + +import org.apache.cloudstack.api.response.SuccessResponse; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class DeleteASNRangeCmdTest { + + BGPService bgpService = Mockito.spy(BGPService.class); + + @Test + public void testDeleteASNRangeCmd() { + Long id = 200L; + + DeleteASNRangeCmd cmd = new DeleteASNRangeCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd,"bgpService", bgpService); + + Assert.assertEquals(id, cmd.getId()); + + Mockito.when(bgpService.deleteASRange(id)).thenReturn(true); + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Object response = cmd.getResponseObject(); + Assert.assertTrue(response instanceof SuccessResponse); + + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/ListASNRangesCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/ListASNRangesCmdTest.java new file mode 100644 index 00000000000..7f49c61a693 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/ListASNRangesCmdTest.java @@ -0,0 +1,75 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.bgp; + +import com.cloud.bgp.ASNumberRange; +import com.cloud.bgp.BGPService; + +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.response.ASNRangeResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.ArrayList; +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) +public class ListASNRangesCmdTest { + + BGPService bgpService = Mockito.spy(BGPService.class); + ResponseGenerator _responseGenerator = Mockito.spy(ResponseGenerator.class); + + @Test + public void testListASNRangesCmdTest() { + Long zoneId = 1L; + + ListASNRangesCmd cmd = new ListASNRangesCmd(); + ReflectionTestUtils.setField(cmd, "zoneId", zoneId); + ReflectionTestUtils.setField(cmd,"bgpService", bgpService); + ReflectionTestUtils.setField(cmd,"_responseGenerator", _responseGenerator); + + Assert.assertEquals(zoneId, cmd.getZoneId()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + + List ranges = new ArrayList<>(); + ASNumberRange asnRange = Mockito.mock(ASNumberRange.class); + ranges.add(asnRange); + + ASNRangeResponse asnRangeResponse = Mockito.mock(ASNRangeResponse.class); + Mockito.when(_responseGenerator.createASNumberRangeResponse(asnRange)).thenReturn(asnRangeResponse); + + Mockito.when(bgpService.listASNumberRanges(zoneId)).thenReturn(ranges); + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Object response = cmd.getResponseObject(); + Assert.assertTrue(response instanceof ListResponse); + ListResponse listResponse = (ListResponse) response; + Assert.assertEquals(1L, (long) listResponse.getCount()); + Assert.assertTrue(listResponse.getResponses().get(0) instanceof ASNRangeResponse); + ASNRangeResponse firstResponse = (ASNRangeResponse) listResponse.getResponses().get(0); + Assert.assertEquals(asnRangeResponse, firstResponse); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/ReleaseASNumberCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/ReleaseASNumberCmdTest.java new file mode 100644 index 00000000000..1b80e5bff7f --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/bgp/ReleaseASNumberCmdTest.java @@ -0,0 +1,61 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.bgp; + +import com.cloud.bgp.BGPService; +import com.cloud.utils.Pair; + +import org.apache.cloudstack.api.response.SuccessResponse; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class ReleaseASNumberCmdTest { + + BGPService bgpService = Mockito.spy(BGPService.class); + + @Test + public void testReleaseASNumberCmd() { + Long zoneId = 1L; + Long asNumber = 10000L; + + ReleaseASNumberCmd cmd = new ReleaseASNumberCmd(); + ReflectionTestUtils.setField(cmd, "zoneId", zoneId); + ReflectionTestUtils.setField(cmd, "asNumber", asNumber); + ReflectionTestUtils.setField(cmd,"bgpService", bgpService); + + Assert.assertEquals(zoneId, cmd.getZoneId()); + Assert.assertEquals(asNumber, cmd.getAsNumber()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + + Pair resultPair = Mockito.mock(Pair.class); + Mockito.when(resultPair.first()).thenReturn(true); + Mockito.when(bgpService.releaseASNumber(zoneId, asNumber, false)).thenReturn(resultPair); + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Object response = cmd.getResponseObject(); + Assert.assertTrue(response instanceof SuccessResponse); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmdTest.java new file mode 100644 index 00000000000..45f175e9a81 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmdTest.java @@ -0,0 +1,88 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.domain; + +import java.util.List; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.response.DomainResponse; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import com.cloud.user.ResourceLimitService; + +@RunWith(MockitoJUnitRunner.class) +public class ListDomainsCmdTest { + + @Mock + ResourceLimitService resourceLimitService; + + + @Test + public void testGetShowIcon() { + ListDomainsCmd cmd = new ListDomainsCmd(); + ReflectionTestUtils.setField(cmd, "showIcon", null); + Assert.assertFalse(cmd.getShowIcon()); + ReflectionTestUtils.setField(cmd, "showIcon", false); + Assert.assertFalse(cmd.getShowIcon()); + ReflectionTestUtils.setField(cmd, "showIcon", true); + Assert.assertTrue(cmd.getShowIcon()); + } + + @Test + public void testGetTag() { + ListDomainsCmd cmd = new ListDomainsCmd(); + ReflectionTestUtils.setField(cmd, "tag", null); + Assert.assertNull(cmd.getTag()); + String tag = "ABC"; + ReflectionTestUtils.setField(cmd, "tag", tag); + Assert.assertEquals(tag, cmd.getTag()); + } + + @Test + public void testUpdateDomainResponseNoDomains() { + ListDomainsCmd cmd = new ListDomainsCmd(); + cmd._resourceLimitService = resourceLimitService; + cmd.updateDomainResponse(null); + Mockito.verify(resourceLimitService, Mockito.never()).updateTaggedResourceLimitsAndCountsForDomains(Mockito.anyList(), Mockito.anyString()); + } + + @Test + public void testUpdateDomainResponseWithDomains() { + ListDomainsCmd cmd = new ListDomainsCmd(); + cmd._resourceLimitService = resourceLimitService; + ReflectionTestUtils.setField(cmd, "tag", "abc"); + cmd.updateDomainResponse(List.of(Mockito.mock(DomainResponse.class))); + Mockito.verify(resourceLimitService).updateTaggedResourceLimitsAndCountsForDomains(Mockito.any(), Mockito.any()); + } + + @Test + public void testUpdateDomainResponseWithDomainsMinDetails() { + ListDomainsCmd cmd = new ListDomainsCmd(); + ReflectionTestUtils.setField(cmd, "viewDetails", List.of(ApiConstants.DomainDetails.min.toString())); + cmd._resourceLimitService = resourceLimitService; + ReflectionTestUtils.setField(cmd, "tag", "abc"); + cmd.updateDomainResponse(List.of(Mockito.mock(DomainResponse.class))); + Mockito.verify(resourceLimitService, Mockito.never()).updateTaggedResourceLimitsAndCountsForDomains(Mockito.any(), Mockito.any()); + } + +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForGuestNetworkCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForGuestNetworkCmdTest.java new file mode 100644 index 00000000000..e1393e31699 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForGuestNetworkCmdTest.java @@ -0,0 +1,69 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import com.cloud.event.EventTypes; + +import org.apache.cloudstack.api.response.Ipv4SubnetForGuestNetworkResponse; +import org.apache.cloudstack.network.Ipv4GuestSubnetNetworkMap; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class CreateIpv4SubnetForGuestNetworkCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testCreateIpv4SubnetForGuestNetworkCmd() { + Long parentId = 1L; + String subnet = "192.168.1.0/24"; + Integer cidrSize = 26; + + CreateIpv4SubnetForGuestNetworkCmd cmd = new CreateIpv4SubnetForGuestNetworkCmd(); + ReflectionTestUtils.setField(cmd, "parentId", parentId); + ReflectionTestUtils.setField(cmd, "subnet", subnet); + ReflectionTestUtils.setField(cmd, "cidrSize", cidrSize); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(parentId, cmd.getParentId()); + Assert.assertEquals(subnet, cmd.getSubnet()); + Assert.assertEquals(cidrSize, cmd.getCidrSize()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_IP4_GUEST_SUBNET_CREATE, cmd.getEventType()); + Assert.assertEquals(String.format("Creating guest IPv4 subnet %s in zone subnet=%s", subnet, parentId), cmd.getEventDescription()); + + Ipv4GuestSubnetNetworkMap ipv4GuestSubnetNetworkMap = Mockito.mock(Ipv4GuestSubnetNetworkMap.class); + Mockito.when(routedIpv4Manager.createIpv4SubnetForGuestNetwork(cmd)).thenReturn(ipv4GuestSubnetNetworkMap); + + Ipv4SubnetForGuestNetworkResponse response = Mockito.mock(Ipv4SubnetForGuestNetworkResponse.class); + Mockito.when(routedIpv4Manager.createIpv4SubnetForGuestNetworkResponse(ipv4GuestSubnetNetworkMap)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForZoneCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForZoneCmdTest.java new file mode 100644 index 00000000000..51c1eb986c4 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/CreateIpv4SubnetForZoneCmdTest.java @@ -0,0 +1,75 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import com.cloud.event.EventTypes; + +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class CreateIpv4SubnetForZoneCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testCreateIpv4SubnetForZoneCmd() { + Long zoneId = 1L; + String subnet = "192.168.1.0/24"; + String accountName = "user"; + Long projectId = 10L; + Long domainId = 11L; + + CreateIpv4SubnetForZoneCmd cmd = new CreateIpv4SubnetForZoneCmd(); + ReflectionTestUtils.setField(cmd, "zoneId", zoneId); + ReflectionTestUtils.setField(cmd, "subnet", subnet); + ReflectionTestUtils.setField(cmd, "accountName", accountName); + ReflectionTestUtils.setField(cmd,"projectId", projectId); + ReflectionTestUtils.setField(cmd,"domainId", domainId); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(zoneId, cmd.getZoneId()); + Assert.assertEquals(subnet, cmd.getSubnet()); + Assert.assertEquals(accountName, cmd.getAccountName()); + Assert.assertEquals(projectId, cmd.getProjectId()); + Assert.assertEquals(domainId, cmd.getDomainId()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_ZONE_IP4_SUBNET_CREATE, cmd.getEventType()); + Assert.assertEquals(String.format("Creating guest IPv4 subnet %s for zone=%s", subnet, zoneId), cmd.getEventDescription()); + + DataCenterIpv4GuestSubnet zoneSubnet = Mockito.mock(DataCenterIpv4GuestSubnet.class); + Mockito.when(routedIpv4Manager.createDataCenterIpv4GuestSubnet(cmd)).thenReturn(zoneSubnet); + + DataCenterIpv4SubnetResponse response = Mockito.mock(DataCenterIpv4SubnetResponse.class); + Mockito.when(routedIpv4Manager.createDataCenterIpv4SubnetResponse(zoneSubnet)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/DedicateIpv4SubnetForZoneCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/DedicateIpv4SubnetForZoneCmdTest.java new file mode 100644 index 00000000000..7db77098b23 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/DedicateIpv4SubnetForZoneCmdTest.java @@ -0,0 +1,72 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import com.cloud.event.EventTypes; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class DedicateIpv4SubnetForZoneCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testDedicateIpv4SubnetForZoneCmd() { + Long id = 1L; + String accountName = "user"; + Long projectId = 10L; + Long domainId = 11L; + + DedicateIpv4SubnetForZoneCmd cmd = new DedicateIpv4SubnetForZoneCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd, "accountName", accountName); + ReflectionTestUtils.setField(cmd,"projectId", projectId); + ReflectionTestUtils.setField(cmd,"domainId", domainId); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(accountName, cmd.getAccountName()); + Assert.assertEquals(projectId, cmd.getProjectId()); + Assert.assertEquals(domainId, cmd.getDomainId()); + + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_ZONE_IP4_SUBNET_DEDICATE, cmd.getEventType()); + Assert.assertEquals(String.format("Dedicating zone IPv4 subnet %s", id), cmd.getEventDescription()); + + DataCenterIpv4GuestSubnet zoneSubnet = Mockito.mock(DataCenterIpv4GuestSubnet.class); + Mockito.when(routedIpv4Manager.dedicateDataCenterIpv4GuestSubnet(cmd)).thenReturn(zoneSubnet); + + DataCenterIpv4SubnetResponse response = Mockito.mock(DataCenterIpv4SubnetResponse.class); + Mockito.when(routedIpv4Manager.createDataCenterIpv4SubnetResponse(zoneSubnet)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForGuestNetworkCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForGuestNetworkCmdTest.java new file mode 100644 index 00000000000..a4af5ddf748 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForGuestNetworkCmdTest.java @@ -0,0 +1,58 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import com.cloud.event.EventTypes; + +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class DeleteIpv4SubnetForGuestNetworkCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testDeleteIpv4SubnetForGuestNetworkCmd() { + Long id = 1L; + + DeleteIpv4SubnetForGuestNetworkCmd cmd = new DeleteIpv4SubnetForGuestNetworkCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_IP4_GUEST_SUBNET_DELETE, cmd.getEventType()); + Assert.assertEquals(String.format("Deleting guest IPv4 subnet %s", id), cmd.getEventDescription()); + + Mockito.when(routedIpv4Manager.deleteIpv4SubnetForGuestNetwork(cmd)).thenReturn(true); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertTrue(cmd.getResponseObject() instanceof SuccessResponse); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForZoneCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForZoneCmdTest.java new file mode 100644 index 00000000000..7af173f09d9 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/DeleteIpv4SubnetForZoneCmdTest.java @@ -0,0 +1,58 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import com.cloud.event.EventTypes; + +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class DeleteIpv4SubnetForZoneCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testDeleteIpv4SubnetForZoneCmd() { + Long id = 1L; + + DeleteIpv4SubnetForZoneCmd cmd = new DeleteIpv4SubnetForZoneCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_ZONE_IP4_SUBNET_DELETE, cmd.getEventType()); + Assert.assertEquals(String.format("Deleting zone IPv4 subnet %s", id), cmd.getEventDescription()); + + Mockito.when(routedIpv4Manager.deleteDataCenterIpv4GuestSubnet(cmd)).thenReturn(true); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertTrue(cmd.getResponseObject() instanceof SuccessResponse); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForGuestNetworkCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForGuestNetworkCmdTest.java new file mode 100644 index 00000000000..cbfe34f774a --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForGuestNetworkCmdTest.java @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.cloudstack.api.response.Ipv4SubnetForGuestNetworkResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.network.Ipv4GuestSubnetNetworkMap; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Arrays; +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) +public class ListIpv4SubnetsForGuestNetworkCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testListIpv4SubnetsForGuestNetworkCmd() { + Long id = 1L; + Long zoneId = 2L; + Long parentId = 2L; + String subnet = "192.168.1.0/24"; + Long networkId = 10L; + Long vpcId = 11L; + + ListIpv4SubnetsForGuestNetworkCmd cmd = new ListIpv4SubnetsForGuestNetworkCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd, "zoneId", zoneId); + ReflectionTestUtils.setField(cmd, "subnet", subnet); + ReflectionTestUtils.setField(cmd, "parentId", parentId); + ReflectionTestUtils.setField(cmd,"networkId", networkId); + ReflectionTestUtils.setField(cmd,"vpcId", vpcId); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(zoneId, cmd.getZoneId()); + Assert.assertEquals(subnet, cmd.getSubnet()); + Assert.assertEquals(networkId, cmd.getNetworkId()); + Assert.assertEquals(vpcId, cmd.getVpcId()); + Assert.assertEquals(parentId, cmd.getParentId()); + + Assert.assertEquals(0L, cmd.getEntityOwnerId()); + + Ipv4GuestSubnetNetworkMap ipv4GuestSubnetNetworkMap = Mockito.mock(Ipv4GuestSubnetNetworkMap.class); + List ipv4GuestSubnetNetworkMaps = Arrays.asList(ipv4GuestSubnetNetworkMap); + Mockito.when(routedIpv4Manager.listIpv4GuestSubnetsForGuestNetwork(cmd)).thenReturn(ipv4GuestSubnetNetworkMaps); + + Ipv4SubnetForGuestNetworkResponse response = Mockito.mock(Ipv4SubnetForGuestNetworkResponse.class); + Mockito.when(routedIpv4Manager.createIpv4SubnetForGuestNetworkResponse(ipv4GuestSubnetNetworkMap)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertTrue(cmd.getResponseObject() instanceof ListResponse); + ListResponse listResponse = (ListResponse) cmd.getResponseObject(); + Assert.assertEquals(1, (int) listResponse.getCount()); + Assert.assertEquals(response, listResponse.getResponses().get(0)); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForZoneCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForZoneCmdTest.java new file mode 100644 index 00000000000..2c7a246f70f --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/ListIpv4SubnetsForZoneCmdTest.java @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Arrays; +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) +public class ListIpv4SubnetsForZoneCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testListIpv4SubnetsForZoneCmd() { + Long id = 1L; + Long zoneId = 2L; + String subnet = "192.168.1.0/24"; + String accountName = "user"; + Long projectId = 10L; + Long domainId = 11L; + + ListIpv4SubnetsForZoneCmd cmd = new ListIpv4SubnetsForZoneCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd, "zoneId", zoneId); + ReflectionTestUtils.setField(cmd, "subnet", subnet); + ReflectionTestUtils.setField(cmd, "accountName", accountName); + ReflectionTestUtils.setField(cmd,"projectId", projectId); + ReflectionTestUtils.setField(cmd,"domainId", domainId); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(zoneId, cmd.getZoneId()); + Assert.assertEquals(subnet, cmd.getSubnet()); + Assert.assertEquals(accountName, cmd.getAccountName()); + Assert.assertEquals(projectId, cmd.getProjectId()); + Assert.assertEquals(domainId, cmd.getDomainId()); + + Assert.assertEquals(0L, cmd.getEntityOwnerId()); + + DataCenterIpv4GuestSubnet zoneSubnet = Mockito.mock(DataCenterIpv4GuestSubnet.class); + List zoneSubnets = Arrays.asList(zoneSubnet); + Mockito.when(routedIpv4Manager.listDataCenterIpv4GuestSubnets(cmd)).thenReturn(zoneSubnets); + + DataCenterIpv4SubnetResponse response = Mockito.mock(DataCenterIpv4SubnetResponse.class); + Mockito.when(routedIpv4Manager.createDataCenterIpv4SubnetResponse(zoneSubnet)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertTrue(cmd.getResponseObject() instanceof ListResponse); + ListResponse listResponse = (ListResponse) cmd.getResponseObject(); + Assert.assertEquals(1, (int) listResponse.getCount()); + Assert.assertEquals(response, listResponse.getResponses().get(0)); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/ReleaseDedicatedIpv4SubnetForZoneCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/ReleaseDedicatedIpv4SubnetForZoneCmdTest.java new file mode 100644 index 00000000000..9ce9a4f9464 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/ReleaseDedicatedIpv4SubnetForZoneCmdTest.java @@ -0,0 +1,62 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import com.cloud.event.EventTypes; +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class ReleaseDedicatedIpv4SubnetForZoneCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testReleaseDedicatedIpv4SubnetForZoneCmd() { + Long id = 1L; + + ReleaseDedicatedIpv4SubnetForZoneCmd cmd = new ReleaseDedicatedIpv4SubnetForZoneCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_ZONE_IP4_SUBNET_RELEASE, cmd.getEventType()); + Assert.assertEquals(String.format("Releasing a dedicated zone IPv4 subnet %s", id), cmd.getEventDescription()); + + DataCenterIpv4GuestSubnet zoneSubnet = Mockito.mock(DataCenterIpv4GuestSubnet.class); + Mockito.when(routedIpv4Manager.releaseDedicatedDataCenterIpv4GuestSubnet(cmd)).thenReturn(zoneSubnet); + + DataCenterIpv4SubnetResponse response = Mockito.mock(DataCenterIpv4SubnetResponse.class); + Mockito.when(routedIpv4Manager.createDataCenterIpv4SubnetResponse(zoneSubnet)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/UpdateIpv4SubnetForZoneCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/UpdateIpv4SubnetForZoneCmdTest.java new file mode 100644 index 00000000000..cdb9cce22d8 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/UpdateIpv4SubnetForZoneCmdTest.java @@ -0,0 +1,66 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network; + +import com.cloud.event.EventTypes; + +import org.apache.cloudstack.api.response.DataCenterIpv4SubnetResponse; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class UpdateIpv4SubnetForZoneCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testUpdateIpv4SubnetForZoneCmd() { + Long id = 1L; + String subnet = "192.168.1.0/24"; + + UpdateIpv4SubnetForZoneCmd cmd = new UpdateIpv4SubnetForZoneCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd, "subnet", subnet); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(subnet, cmd.getSubnet()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_ZONE_IP4_SUBNET_UPDATE, cmd.getEventType()); + Assert.assertEquals(String.format("Updating zone IPv4 subnet %s", id), cmd.getEventDescription()); + + DataCenterIpv4GuestSubnet zoneSubnet = Mockito.mock(DataCenterIpv4GuestSubnet.class); + Mockito.when(routedIpv4Manager.updateDataCenterIpv4GuestSubnet(cmd)).thenReturn(zoneSubnet); + + DataCenterIpv4SubnetResponse response = Mockito.mock(DataCenterIpv4SubnetResponse.class); + Mockito.when(routedIpv4Manager.createDataCenterIpv4SubnetResponse(zoneSubnet)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForNetworkCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForNetworkCmdTest.java new file mode 100644 index 00000000000..28ddad17afe --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForNetworkCmdTest.java @@ -0,0 +1,74 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import com.cloud.event.EventTypes; + +import com.cloud.network.Network; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Arrays; +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) +public class ChangeBgpPeersForNetworkCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + ResponseGenerator _responseGenerator = Mockito.spy(ResponseGenerator.class); + + @Test + public void testChangeBgpPeersForNetworkCmd() { + Long networkId = 10L; + List bgpPeerIds = Arrays.asList(20L, 21L); + + ChangeBgpPeersForNetworkCmd cmd = new ChangeBgpPeersForNetworkCmd(); + ReflectionTestUtils.setField(cmd, "networkId", networkId); + ReflectionTestUtils.setField(cmd, "bgpPeerIds", bgpPeerIds); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + ReflectionTestUtils.setField(cmd,"_responseGenerator", _responseGenerator); + + Assert.assertEquals(networkId, cmd.getNetworkId()); + Assert.assertEquals(bgpPeerIds, cmd.getBgpPeerIds()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_NETWORK_BGP_PEER_UPDATE, cmd.getEventType()); + Assert.assertEquals(String.format("Changing Bgp Peers for network %s", networkId), cmd.getEventDescription()); + + Network network = Mockito.mock(Network.class); + Mockito.when(routedIpv4Manager.changeBgpPeersForNetwork(cmd)).thenReturn(network); + + NetworkResponse response = Mockito.mock(NetworkResponse.class); + Mockito.when(_responseGenerator.createNetworkResponse(ResponseObject.ResponseView.Full, network)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForVpcCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForVpcCmdTest.java new file mode 100644 index 00000000000..96eb1f020de --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ChangeBgpPeersForVpcCmdTest.java @@ -0,0 +1,74 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import com.cloud.event.EventTypes; + +import com.cloud.network.vpc.Vpc; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Arrays; +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) +public class ChangeBgpPeersForVpcCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + ResponseGenerator _responseGenerator = Mockito.spy(ResponseGenerator.class); + + @Test + public void testChangeBgpPeersForVpcCmd() { + Long VpcId = 10L; + List bgpPeerIds = Arrays.asList(20L, 21L); + + ChangeBgpPeersForVpcCmd cmd = new ChangeBgpPeersForVpcCmd(); + ReflectionTestUtils.setField(cmd, "vpcId", VpcId); + ReflectionTestUtils.setField(cmd, "bgpPeerIds", bgpPeerIds); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + ReflectionTestUtils.setField(cmd,"_responseGenerator", _responseGenerator); + + Assert.assertEquals(VpcId, cmd.getVpcId()); + Assert.assertEquals(bgpPeerIds, cmd.getBgpPeerIds()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_VPC_BGP_PEER_UPDATE, cmd.getEventType()); + Assert.assertEquals(String.format("Changing Bgp Peers for VPC %s", VpcId), cmd.getEventDescription()); + + Vpc Vpc = Mockito.mock(Vpc.class); + Mockito.when(routedIpv4Manager.changeBgpPeersForVpc(cmd)).thenReturn(Vpc); + + VpcResponse response = Mockito.mock(VpcResponse.class); + Mockito.when(_responseGenerator.createVpcResponse(ResponseObject.ResponseView.Full, Vpc)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/CreateBgpPeerCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/CreateBgpPeerCmdTest.java new file mode 100644 index 00000000000..0d802bf3619 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/CreateBgpPeerCmdTest.java @@ -0,0 +1,85 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import com.cloud.event.EventTypes; + +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class CreateBgpPeerCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testCreateBgpPeerCmd() { + Long zoneId = 1L; + String accountName = "user"; + Long projectId = 10L; + Long domainId = 11L; + String ip4Address = "ip4-address"; + String ip6Address = "ip6-address"; + Long peerAsNumber = 15000L; + String peerPassword = "peer-password"; + + CreateBgpPeerCmd cmd = new CreateBgpPeerCmd(); + ReflectionTestUtils.setField(cmd, "zoneId", zoneId); + ReflectionTestUtils.setField(cmd, "ip4Address", ip4Address); + ReflectionTestUtils.setField(cmd, "ip6Address", ip6Address); + ReflectionTestUtils.setField(cmd, "asNumber", peerAsNumber); + ReflectionTestUtils.setField(cmd, "password", peerPassword); + ReflectionTestUtils.setField(cmd, "accountName", accountName); + ReflectionTestUtils.setField(cmd,"projectId", projectId); + ReflectionTestUtils.setField(cmd,"domainId", domainId); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(zoneId, cmd.getZoneId()); + Assert.assertEquals(ip4Address, cmd.getIp4Address()); + Assert.assertEquals(ip6Address, cmd.getIp6Address()); + Assert.assertEquals(peerAsNumber, cmd.getAsNumber()); + Assert.assertEquals(peerPassword, cmd.getPassword()); + Assert.assertEquals(accountName, cmd.getAccountName()); + Assert.assertEquals(projectId, cmd.getProjectId()); + Assert.assertEquals(domainId, cmd.getDomainId()); + + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_BGP_PEER_CREATE, cmd.getEventType()); + Assert.assertEquals(String.format("Creating Bgp Peer %s for zone=%s", peerAsNumber, zoneId), cmd.getEventDescription()); + + BgpPeer bgpPeer = Mockito.mock(BgpPeer.class); + Mockito.when(routedIpv4Manager.createBgpPeer(cmd)).thenReturn(bgpPeer); + + BgpPeerResponse response = Mockito.mock(BgpPeerResponse.class); + Mockito.when(routedIpv4Manager.createBgpPeerResponse(bgpPeer)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/DedicateBgpPeerCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/DedicateBgpPeerCmdTest.java new file mode 100644 index 00000000000..f3ae007da28 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/DedicateBgpPeerCmdTest.java @@ -0,0 +1,72 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import com.cloud.event.EventTypes; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class DedicateBgpPeerCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testDedicateBgpPeerCmd() { + Long id = 1L; + String accountName = "user"; + Long projectId = 10L; + Long domainId = 11L; + + DedicateBgpPeerCmd cmd = new DedicateBgpPeerCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd, "accountName", accountName); + ReflectionTestUtils.setField(cmd,"projectId", projectId); + ReflectionTestUtils.setField(cmd,"domainId", domainId); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(accountName, cmd.getAccountName()); + Assert.assertEquals(projectId, cmd.getProjectId()); + Assert.assertEquals(domainId, cmd.getDomainId()); + + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_BGP_PEER_DEDICATE, cmd.getEventType()); + Assert.assertEquals(String.format("Dedicating Bgp Peer %s", id), cmd.getEventDescription()); + + BgpPeer bgpPeer = Mockito.mock(BgpPeer.class); + Mockito.when(routedIpv4Manager.dedicateBgpPeer(cmd)).thenReturn(bgpPeer); + + BgpPeerResponse response = Mockito.mock(BgpPeerResponse.class); + Mockito.when(routedIpv4Manager.createBgpPeerResponse(bgpPeer)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/DeleteBgpPeerCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/DeleteBgpPeerCmdTest.java new file mode 100644 index 00000000000..5e747188fda --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/DeleteBgpPeerCmdTest.java @@ -0,0 +1,58 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import com.cloud.event.EventTypes; + +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class DeleteBgpPeerCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testDeleteBgpPeerCmd() { + Long id = 1L; + + DeleteBgpPeerCmd cmd = new DeleteBgpPeerCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_BGP_PEER_DELETE, cmd.getEventType()); + Assert.assertEquals(String.format("Deleting Bgp Peer %s", id), cmd.getEventDescription()); + + Mockito.when(routedIpv4Manager.deleteBgpPeer(cmd)).thenReturn(true); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertTrue(cmd.getResponseObject() instanceof SuccessResponse); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ListBgpPeersCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ListBgpPeersCmdTest.java new file mode 100644 index 00000000000..cb2027951ad --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ListBgpPeersCmdTest.java @@ -0,0 +1,96 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Arrays; +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) +public class ListBgpPeersCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testIsDedicated() { + ListBgpPeersCmd cmd = new ListBgpPeersCmd(); + + Assert.assertNull(cmd.getDedicated()); + + ReflectionTestUtils.setField(cmd, "isDedicated", Boolean.TRUE); + Assert.assertTrue(cmd.getDedicated()); + + ReflectionTestUtils.setField(cmd, "isDedicated", Boolean.FALSE); + Assert.assertFalse(cmd.getDedicated()); + } + + @Test + public void testListBgpPeersCmd() { + Long id = 1L; + Long zoneId = 2L; + Long peerAsNumber = 15000L; + String accountName = "user"; + Long projectId = 10L; + Long domainId = 11L; + + ListBgpPeersCmd cmd = new ListBgpPeersCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd, "zoneId", zoneId); + ReflectionTestUtils.setField(cmd, "asNumber", peerAsNumber); + ReflectionTestUtils.setField(cmd, "accountName", accountName); + ReflectionTestUtils.setField(cmd,"projectId", projectId); + ReflectionTestUtils.setField(cmd,"domainId", domainId); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(zoneId, cmd.getZoneId()); + Assert.assertEquals(peerAsNumber, cmd.getAsNumber()); + Assert.assertEquals(accountName, cmd.getAccountName()); + Assert.assertEquals(projectId, cmd.getProjectId()); + Assert.assertEquals(domainId, cmd.getDomainId()); + + Assert.assertEquals(0L, cmd.getEntityOwnerId()); + + BgpPeer bgpPeer = Mockito.mock(BgpPeer.class); + List bgpPeers = Arrays.asList(bgpPeer); + Mockito.when(routedIpv4Manager.listBgpPeers(cmd)).thenReturn(bgpPeers); + + BgpPeerResponse response = Mockito.mock(BgpPeerResponse.class); + Mockito.when(routedIpv4Manager.createBgpPeerResponse(bgpPeer)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertTrue(cmd.getResponseObject() instanceof ListResponse); + ListResponse listResponse = (ListResponse) cmd.getResponseObject(); + Assert.assertEquals(1, (int) listResponse.getCount()); + Assert.assertEquals(response, listResponse.getResponses().get(0)); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ReleaseDedicatedBgpPeerCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ReleaseDedicatedBgpPeerCmdTest.java new file mode 100644 index 00000000000..8c55c4a7347 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/ReleaseDedicatedBgpPeerCmdTest.java @@ -0,0 +1,62 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import com.cloud.event.EventTypes; +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class ReleaseDedicatedBgpPeerCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testReleaseDedicatedBgpPeerCmd() { + Long id = 1L; + + ReleaseDedicatedBgpPeerCmd cmd = new ReleaseDedicatedBgpPeerCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_BGP_PEER_RELEASE, cmd.getEventType()); + Assert.assertEquals(String.format("Releasing a dedicated Bgp Peer %s", id), cmd.getEventDescription()); + + BgpPeer bgpPeer = Mockito.mock(BgpPeer.class); + Mockito.when(routedIpv4Manager.releaseDedicatedBgpPeer(cmd)).thenReturn(bgpPeer); + + BgpPeerResponse response = Mockito.mock(BgpPeerResponse.class); + Mockito.when(routedIpv4Manager.createBgpPeerResponse(bgpPeer)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/UpdateBgpPeerCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/UpdateBgpPeerCmdTest.java new file mode 100644 index 00000000000..003944c6147 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/network/bgp/UpdateBgpPeerCmdTest.java @@ -0,0 +1,87 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.network.bgp; + +import com.cloud.event.EventTypes; + +import org.apache.cloudstack.api.response.BgpPeerResponse; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class UpdateBgpPeerCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + @Test + public void testUpdateBgpPeerCmd() { + Long id = 1L; + String ip4Address = "ip4-address"; + String ip6Address = "ip6-address"; + Long peerAsNumber = 15000L; + String peerPassword = "peer-password"; + + UpdateBgpPeerCmd cmd = new UpdateBgpPeerCmd(); + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd, "ip4Address", ip4Address); + ReflectionTestUtils.setField(cmd, "ip6Address", ip6Address); + ReflectionTestUtils.setField(cmd, "asNumber", peerAsNumber); + ReflectionTestUtils.setField(cmd, "password", peerPassword); + ReflectionTestUtils.setField(cmd,"routedIpv4Manager", routedIpv4Manager); + + Assert.assertEquals(id, cmd.getId()); + Assert.assertEquals(ip4Address, cmd.getIp4Address()); + Assert.assertEquals(ip6Address, cmd.getIp6Address()); + Assert.assertEquals(peerAsNumber, cmd.getAsNumber()); + Assert.assertEquals(peerPassword, cmd.getPassword()); + Assert.assertEquals(1L, cmd.getEntityOwnerId()); + Assert.assertEquals(EventTypes.EVENT_BGP_PEER_UPDATE, cmd.getEventType()); + Assert.assertEquals(String.format("Updating Bgp Peer %s", id), cmd.getEventDescription()); + + BgpPeer bgpPeer = Mockito.mock(BgpPeer.class); + Mockito.when(routedIpv4Manager.updateBgpPeer(cmd)).thenReturn(bgpPeer); + + BgpPeerResponse response = Mockito.mock(BgpPeerResponse.class); + Mockito.when(routedIpv4Manager.createBgpPeerResponse(bgpPeer)).thenReturn(response); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(response, cmd.getResponseObject()); + } + + @Test + public void testUpdateBgpPeerCleanupDetails() { + UpdateBgpPeerCmd cmd = new UpdateBgpPeerCmd(); + Assert.assertFalse(cmd.isCleanupDetails()); + + ReflectionTestUtils.setField(cmd, "cleanupDetails", Boolean.TRUE); + Assert.assertTrue(cmd.isCleanupDetails()); + + ReflectionTestUtils.setField(cmd, "cleanupDetails", Boolean.FALSE); + Assert.assertFalse(cmd.isCleanupDetails()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/CreateNetworkOfferingCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/CreateNetworkOfferingCmdTest.java index 8b95456a84c..ef10ebff467 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/CreateNetworkOfferingCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/CreateNetworkOfferingCmdTest.java @@ -23,14 +23,16 @@ import org.junit.Test; import org.mockito.InjectMocks; import org.springframework.test.util.ReflectionTestUtils; + public class CreateNetworkOfferingCmdTest { @InjectMocks private CreateNetworkOfferingCmd createNetworkOfferingCmd = new CreateNetworkOfferingCmd(); + String netName = "network"; + @Test public void createVpcNtwkOffWithEmptyDisplayText() { - String netName = "network"; ReflectionTestUtils.setField(createNetworkOfferingCmd, "networkOfferingName", netName); Assert.assertEquals(createNetworkOfferingCmd.getDisplayText(), netName); } diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmdTest.java index 717b5c3262d..6daa5de07cb 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmdTest.java @@ -21,7 +21,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; @RunWith(MockitoJUnitRunner.class) @@ -37,4 +37,22 @@ public class CreateServiceOfferingCmdTest { Assert.assertEquals(createServiceOfferingCmd.getDisplayText(), netName); } + @Test + public void testIsPurgeResourcesNoOrNullValue() { + Assert.assertFalse(createServiceOfferingCmd.isPurgeResources()); + ReflectionTestUtils.setField(createServiceOfferingCmd, "purgeResources", false); + Assert.assertFalse(createServiceOfferingCmd.isPurgeResources()); + } + + @Test + public void testIsPurgeResourcesFalse() { + ReflectionTestUtils.setField(createServiceOfferingCmd, "purgeResources", false); + Assert.assertFalse(createServiceOfferingCmd.isPurgeResources()); + } + + @Test + public void testIsPurgeResourcesTrue() { + ReflectionTestUtils.setField(createServiceOfferingCmd, "purgeResources", true); + Assert.assertTrue(createServiceOfferingCmd.isPurgeResources()); + } } diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmdTest.java new file mode 100644 index 00000000000..1bb2be041e1 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmdTest.java @@ -0,0 +1,51 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.offering; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class UpdateServiceOfferingCmdTest { + + @InjectMocks + private UpdateServiceOfferingCmd updateServiceOfferingCmd; + + @Test + public void testIsPurgeResourcesNoOrNullValue() { + Assert.assertFalse(updateServiceOfferingCmd.isPurgeResources()); + ReflectionTestUtils.setField(updateServiceOfferingCmd, "purgeResources", false); + Assert.assertFalse(updateServiceOfferingCmd.isPurgeResources()); + } + + @Test + public void testIsPurgeResourcesFalse() { + ReflectionTestUtils.setField(updateServiceOfferingCmd, "purgeResources", false); + Assert.assertFalse(updateServiceOfferingCmd.isPurgeResources()); + } + + @Test + public void testIsPurgeResourcesTrue() { + ReflectionTestUtils.setField(updateServiceOfferingCmd, "purgeResources", true); + Assert.assertTrue(updateServiceOfferingCmd.isPurgeResources()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmdTest.java new file mode 100644 index 00000000000..fc0e6face52 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmdTest.java @@ -0,0 +1,34 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.admin.resource; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.test.util.ReflectionTestUtils; + +public class ListCapacityCmdTest { + + @Test + public void testGetTag() { + ListCapacityCmd cmd = new ListCapacityCmd(); + ReflectionTestUtils.setField(cmd, "tag", null); + Assert.assertNull(cmd.getTag()); + String tag = "ABC"; + ReflectionTestUtils.setField(cmd, "tag", tag); + Assert.assertEquals(tag, cmd.getTag()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/resource/PurgeExpungedResourcesCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/resource/PurgeExpungedResourcesCmdTest.java new file mode 100644 index 00000000000..a628f13275c --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/resource/PurgeExpungedResourcesCmdTest.java @@ -0,0 +1,104 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.resource; + +import static org.junit.Assert.assertNull; + +import java.util.Date; + +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PurgeExpungedResourcesResponse; +import org.apache.cloudstack.resource.ResourceCleanupService; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; +import org.springframework.test.util.ReflectionTestUtils; + +import com.cloud.utils.exception.CloudRuntimeException; + +@RunWith(MockitoJUnitRunner.class) +public class PurgeExpungedResourcesCmdTest { + @Mock + ResourceCleanupService resourceCleanupService; + + @Spy + @InjectMocks + PurgeExpungedResourcesCmd spyCmd = Mockito.spy(new PurgeExpungedResourcesCmd()); + + @Test + public void testGetResourceType() { + PurgeExpungedResourcesCmd cmd = new PurgeExpungedResourcesCmd(); + assertNull(cmd.getResourceType()); + ReflectionTestUtils.setField(cmd, "resourceType", ResourceCleanupService.ResourceType.VirtualMachine.toString()); + Assert.assertEquals(ResourceCleanupService.ResourceType.VirtualMachine.toString(), cmd.getResourceType()); + } + + @Test + public void testGetBatchSize() { + PurgeExpungedResourcesCmd cmd = new PurgeExpungedResourcesCmd(); + assertNull(cmd.getBatchSize()); + Long batchSize = 100L; + ReflectionTestUtils.setField(cmd, "batchSize", batchSize); + Assert.assertEquals(batchSize, cmd.getBatchSize()); + } + + @Test + public void testGetStartDate() { + PurgeExpungedResourcesCmd cmd = new PurgeExpungedResourcesCmd(); + assertNull(cmd.getStartDate()); + Date date = new Date(); + ReflectionTestUtils.setField(cmd, "startDate", date); + Assert.assertEquals(date, cmd.getStartDate()); + } + + @Test + public void testGetEndDate() { + PurgeExpungedResourcesCmd cmd = new PurgeExpungedResourcesCmd(); + assertNull(cmd.getEndDate()); + Date date = new Date(); + ReflectionTestUtils.setField(cmd, "endDate", date); + Assert.assertEquals(date, cmd.getEndDate()); + } + + @Test + public void testExecute() { + final PurgeExpungedResourcesResponse[] executeResponse = new PurgeExpungedResourcesResponse[1]; + Long result = 100L; + Mockito.when(resourceCleanupService.purgeExpungedResources(Mockito.any())).thenReturn(result); + Mockito.doAnswer((Answer) invocation -> { + executeResponse[0] = (PurgeExpungedResourcesResponse)invocation.getArguments()[0]; + return null; + }).when(spyCmd).setResponseObject(Mockito.any()); + spyCmd.execute(); + PurgeExpungedResourcesResponse response = executeResponse[0]; + Assert.assertNotNull(response); + Assert.assertEquals(result, response.getResourceCount()); + } + + @Test(expected = ServerApiException.class) + public void testExecuteException() { + Mockito.doThrow(CloudRuntimeException.class).when(resourceCleanupService).purgeExpungedResources(Mockito.any()); + spyCmd.execute(); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/AddObjectStoragePoolCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/AddObjectStoragePoolCmdTest.java index f64df167e25..a69a7a858ce 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/AddObjectStoragePoolCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/AddObjectStoragePoolCmdTest.java @@ -24,7 +24,6 @@ import org.apache.cloudstack.api.ResponseGenerator; import org.apache.cloudstack.api.response.ObjectStoreResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.storage.object.ObjectStore; -import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -39,11 +38,10 @@ import org.springframework.test.util.ReflectionTestUtils; import java.util.HashMap; import java.util.Map; -import static org.mockito.ArgumentMatchers.anyObject; +import static org.mockito.ArgumentMatchers.any; @RunWith(MockitoJUnitRunner.class) public class AddObjectStoragePoolCmdTest { - public static final Logger s_logger = Logger.getLogger(AddObjectStoragePoolCmdTest.class.getName()); @Mock StorageService storageService; @@ -65,9 +63,11 @@ public class AddObjectStoragePoolCmdTest { Map details; + private AutoCloseable closeable; + @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); details = new HashMap<>(); addObjectStoragePoolCmdSpy = Mockito.spy(new AddObjectStoragePoolCmd()); ReflectionTestUtils.setField(addObjectStoragePoolCmdSpy, "name", name); @@ -81,14 +81,15 @@ public class AddObjectStoragePoolCmdTest { @After public void tearDown() throws Exception { CallContext.unregister(); + closeable.close(); } @Test public void testAddObjectStore() throws DiscoveryException { Mockito.doReturn(objectStore).when(storageService).discoverObjectStore(Mockito.anyString(), - Mockito.anyString(), Mockito.anyString(), anyObject()); + Mockito.anyString(), Mockito.anyString(), any()); ObjectStoreResponse objectStoreResponse = new ObjectStoreResponse(); - Mockito.doReturn(objectStoreResponse).when(responseGenerator).createObjectStoreResponse(anyObject()); + Mockito.doReturn(objectStoreResponse).when(responseGenerator).createObjectStoreResponse(any()); addObjectStoragePoolCmdSpy.execute(); Mockito.verify(storageService, Mockito.times(1)) diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/DeleteObjectStoragePoolCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/DeleteObjectStoragePoolCmdTest.java index 35be56d0c75..dc5b9f5fa32 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/DeleteObjectStoragePoolCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/DeleteObjectStoragePoolCmdTest.java @@ -20,7 +20,6 @@ package org.apache.cloudstack.api.command.admin.storage; import com.cloud.storage.StorageService; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -30,16 +29,17 @@ import org.mockito.MockitoAnnotations; import org.mockito.Spy; public class DeleteObjectStoragePoolCmdTest { - public static final Logger s_logger = Logger.getLogger(DeleteObjectStoragePoolCmdTest.class.getName()); @Mock private StorageService storageService; @Spy DeleteObjectStoragePoolCmd deleteObjectStoragePoolCmd; + private AutoCloseable closeable; + @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); deleteObjectStoragePoolCmd = Mockito.spy(new DeleteObjectStoragePoolCmd()); deleteObjectStoragePoolCmd._storageService = storageService; } @@ -47,6 +47,7 @@ public class DeleteObjectStoragePoolCmdTest { @After public void tearDown() throws Exception { CallContext.unregister(); + closeable.close(); } @Test diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/FindStoragePoolsForMigrationCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/FindStoragePoolsForMigrationCmdTest.java index 5244ff1ef9a..fbf4d2c495d 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/FindStoragePoolsForMigrationCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/FindStoragePoolsForMigrationCmdTest.java @@ -23,7 +23,7 @@ import org.apache.cloudstack.api.response.StoragePoolResponse; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class FindStoragePoolsForMigrationCmdTest { diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/UpdateObjectStoragePoolCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/UpdateObjectStoragePoolCmdTest.java index ef66c2a1a64..307d80aa3f8 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/UpdateObjectStoragePoolCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/storage/UpdateObjectStoragePoolCmdTest.java @@ -23,7 +23,6 @@ import org.apache.cloudstack.api.ResponseGenerator; import org.apache.cloudstack.api.response.ObjectStoreResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.storage.object.ObjectStore; -import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -33,10 +32,9 @@ import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.springframework.test.util.ReflectionTestUtils; -import static org.mockito.ArgumentMatchers.anyObject; +import static org.mockito.ArgumentMatchers.any; public class UpdateObjectStoragePoolCmdTest { - public static final Logger s_logger = Logger.getLogger(UpdateObjectStoragePoolCmdTest.class.getName()); @Mock private StorageService storageService; @@ -56,9 +54,11 @@ public class UpdateObjectStoragePoolCmdTest { private String provider = "Simulator"; + private AutoCloseable closeable; + @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); updateObjectStoragePoolCmd = Mockito.spy(new UpdateObjectStoragePoolCmd()); updateObjectStoragePoolCmd._storageService = storageService; updateObjectStoragePoolCmd._responseGenerator = responseGenerator; @@ -70,13 +70,14 @@ public class UpdateObjectStoragePoolCmdTest { @After public void tearDown() throws Exception { CallContext.unregister(); + closeable.close(); } @Test public void testUpdateObjectStore() { Mockito.doReturn(objectStore).when(storageService).updateObjectStore(1L, updateObjectStoragePoolCmd); ObjectStoreResponse objectStoreResponse = new ObjectStoreResponse(); - Mockito.doReturn(objectStoreResponse).when(responseGenerator).createObjectStoreResponse(anyObject()); + Mockito.doReturn(objectStoreResponse).when(responseGenerator).createObjectStoreResponse(any()); updateObjectStoragePoolCmd.execute(); Mockito.verify(storageService, Mockito.times(1)) .updateObjectStore(1L, updateObjectStoragePoolCmd); diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/user/CreateUserCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/user/CreateUserCmdTest.java index bc1e1854aa7..8a57ac3eb22 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/admin/user/CreateUserCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/user/CreateUserCmdTest.java @@ -22,7 +22,8 @@ package org.apache.cloudstack.api.command.admin.user; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -38,7 +39,7 @@ import com.cloud.user.AccountService; import com.cloud.user.User; public class CreateUserCmdTest { - public static final Logger s_logger = Logger.getLogger(CreateUserCmdTest.class.getName()); + protected Logger logger = LogManager.getLogger(getClass()); @Mock private AccountService accountService; diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCCmdByAdminTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCCmdByAdminTest.java new file mode 100644 index 00000000000..c4e21bb948b --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCCmdByAdminTest.java @@ -0,0 +1,55 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.admin.vpc; + +import com.cloud.network.vpc.VpcService; +import com.cloud.user.AccountService; +import com.cloud.utils.db.EntityManager; +import junit.framework.TestCase; +import org.apache.cloudstack.api.ResponseGenerator; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) +public class CreateVPCCmdByAdminTest extends TestCase { + + @Mock + public VpcService _vpcService; + @Mock + public EntityManager _entityMgr; + @Mock + public AccountService _accountService; + private ResponseGenerator responseGenerator; + @InjectMocks + CreateVPCCmdByAdmin cmd = new CreateVPCCmdByAdmin(); + + @Test + public void testBgpPeerIds() { + List bgpPeerIds = Mockito.mock(List.class); + ReflectionTestUtils.setField(cmd, "bgpPeerIds", bgpPeerIds); + Assert.assertEquals(bgpPeerIds, cmd.getBgpPeerIds()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java index 16b716d7d63..290a2850c9a 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java @@ -52,15 +52,15 @@ public class CreateVPCOfferingCmdTest { IllegalAccessException { CreateVPCOfferingCmd cmd = new CreateVPCOfferingCmd(); ApiCmdTestUtil.set(cmd, ApiConstants.SERVICE_PROVIDER_LIST, new HashMap>()); - Assert.assertNull(cmd.getServiceProviders()); + Assert.assertTrue(cmd.getServiceProviders().isEmpty()); } @Test - public void getDetailsNull() throws IllegalArgumentException, + public void getDetailsEmpty() throws IllegalArgumentException, IllegalAccessException { CreateVPCOfferingCmd cmd = new CreateVPCOfferingCmd(); ApiCmdTestUtil.set(cmd, ApiConstants.SERVICE_PROVIDER_LIST, null); - Assert.assertNull(cmd.getServiceProviders()); + Assert.assertTrue(cmd.getServiceProviders().isEmpty()); } @Test diff --git a/api/src/test/java/org/apache/cloudstack/api/command/test/ActivateProjectCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/test/ActivateProjectCmdTest.java index 1e4bb326f7e..2c43278a582 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/test/ActivateProjectCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/test/ActivateProjectCmdTest.java @@ -23,7 +23,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.apache.cloudstack.api.command.user.project.ActivateProjectCmd; @@ -57,7 +57,7 @@ public class ActivateProjectCmdTest extends TestCase { @Test public void testGetEntityOwnerIdForNullProject() { ProjectService projectService = Mockito.mock(ProjectService.class); - Mockito.when(projectService.getProject(Matchers.anyLong())).thenReturn(null); + Mockito.when(projectService.getProject(ArgumentMatchers.anyLong())).thenReturn(null); activateProjectCmd._projectService = projectService; try { @@ -74,9 +74,9 @@ public class ActivateProjectCmdTest extends TestCase { ProjectService projectService = Mockito.mock(ProjectService.class); Account account = Mockito.mock(Account.class); Mockito.when(account.getId()).thenReturn(2L); - Mockito.when(projectService.getProject(Matchers.anyLong())).thenReturn(project); + Mockito.when(projectService.getProject(ArgumentMatchers.anyLong())).thenReturn(project); - Mockito.when(projectService.getProjectOwner(Matchers.anyLong())).thenReturn(account); + Mockito.when(projectService.getProjectOwner(ArgumentMatchers.anyLong())).thenReturn(account); activateProjectCmd._projectService = projectService; Assert.assertEquals(2L, activateProjectCmd.getEntityOwnerId()); diff --git a/api/src/test/java/org/apache/cloudstack/api/command/test/AddAccountToProjectCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/test/AddAccountToProjectCmdTest.java index 199ee00551d..f100822b8c7 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/test/AddAccountToProjectCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/test/AddAccountToProjectCmdTest.java @@ -23,7 +23,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.apache.cloudstack.api.command.user.account.AddAccountToProjectCmd; @@ -101,9 +101,9 @@ public class AddAccountToProjectCmdTest extends TestCase { Account account = Mockito.mock(Account.class); Mockito.when(account.getId()).thenReturn(2L); - Mockito.when(projectService.getProject(Matchers.anyLong())).thenReturn(project); + Mockito.when(projectService.getProject(ArgumentMatchers.anyLong())).thenReturn(project); - Mockito.when(projectService.getProjectOwner(Matchers.anyLong())).thenReturn(account); + Mockito.when(projectService.getProjectOwner(ArgumentMatchers.anyLong())).thenReturn(account); addAccountToProjectCmd._projectService = projectService; Assert.assertEquals(2L, addAccountToProjectCmd.getEntityOwnerId()); diff --git a/api/src/test/java/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java b/api/src/test/java/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java index d0cc8be716a..9ea3a6446e8 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/test/AddIpToVmNicTest.java @@ -21,7 +21,7 @@ import junit.framework.TestCase; import org.junit.Before; import org.junit.Test; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.apache.cloudstack.api.ResponseGenerator; import org.apache.cloudstack.api.command.user.vm.AddIpToVmNicCmd; @@ -59,7 +59,7 @@ public class AddIpToVmNicTest extends TestCase { NicSecondaryIp secIp = Mockito.mock(NicSecondaryIp.class); Mockito.when( - networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.any())) + networkService.allocateSecondaryGuestIP(ArgumentMatchers.anyLong(), ArgumentMatchers.any())) .thenReturn(secIp); ipTonicCmd._networkService = networkService; @@ -79,7 +79,7 @@ public class AddIpToVmNicTest extends TestCase { AddIpToVmNicCmd ipTonicCmd = Mockito.mock(AddIpToVmNicCmd.class); Mockito.when( - networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.any())) + networkService.allocateSecondaryGuestIP(ArgumentMatchers.anyLong(), ArgumentMatchers.any())) .thenReturn(null); ipTonicCmd._networkService = networkService; @@ -98,7 +98,7 @@ public class AddIpToVmNicTest extends TestCase { NetworkService networkService = Mockito.mock(NetworkService.class); RemoveIpFromVmNicCmd removeIpFromNic = Mockito.mock(RemoveIpFromVmNicCmd.class); - Mockito.when(networkService.releaseSecondaryIpFromNic(Matchers.anyInt())).thenReturn(true); + Mockito.when(networkService.releaseSecondaryIpFromNic(ArgumentMatchers.anyInt())).thenReturn(true); removeIpFromNic._networkService = networkService; removeIpFromNic.execute(); @@ -109,7 +109,7 @@ public class AddIpToVmNicTest extends TestCase { NetworkService networkService = Mockito.mock(NetworkService.class); RemoveIpFromVmNicCmd removeIpFromNic = Mockito.mock(RemoveIpFromVmNicCmd.class); - Mockito.when(networkService.releaseSecondaryIpFromNic(Matchers.anyInt())).thenReturn(false); + Mockito.when(networkService.releaseSecondaryIpFromNic(ArgumentMatchers.anyInt())).thenReturn(false); removeIpFromNic._networkService = networkService; successResponseGenerator = Mockito.mock(SuccessResponse.class); diff --git a/api/src/test/java/org/apache/cloudstack/api/command/test/AddNetworkServiceProviderCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/test/AddNetworkServiceProviderCmdTest.java index 8760fc87556..a62c29e487a 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/test/AddNetworkServiceProviderCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/test/AddNetworkServiceProviderCmdTest.java @@ -26,7 +26,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.apache.cloudstack.api.ServerApiException; @@ -86,7 +86,7 @@ public class AddNetworkServiceProviderCmdTest extends TestCase { addNetworkServiceProviderCmd._networkService = networkService; PhysicalNetworkServiceProvider physicalNetworkServiceProvider = Mockito.mock(PhysicalNetworkServiceProvider.class); - Mockito.when(networkService.addProviderToPhysicalNetwork(Matchers.anyLong(), Matchers.anyString(), Matchers.anyLong(), Matchers.anyList())).thenReturn( + Mockito.when(networkService.addProviderToPhysicalNetwork(ArgumentMatchers.anyLong(), ArgumentMatchers.anyString(), ArgumentMatchers.anyLong(), ArgumentMatchers.anyList())).thenReturn( physicalNetworkServiceProvider); try { @@ -103,7 +103,7 @@ public class AddNetworkServiceProviderCmdTest extends TestCase { NetworkService networkService = Mockito.mock(NetworkService.class); addNetworkServiceProviderCmd._networkService = networkService; - Mockito.when(networkService.addProviderToPhysicalNetwork(Matchers.anyLong(), Matchers.anyString(), Matchers.anyLong(), Matchers.anyList())).thenReturn(null); + Mockito.when(networkService.addProviderToPhysicalNetwork(ArgumentMatchers.anyLong(), ArgumentMatchers.anyString(), ArgumentMatchers.anyLong(), ArgumentMatchers.anyList())).thenReturn(null); try { addNetworkServiceProviderCmd.create(); diff --git a/api/src/test/java/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java index 46fd6905683..86a53787e08 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java @@ -18,7 +18,7 @@ package org.apache.cloudstack.api.command.test; import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyObject; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isNull; @@ -86,7 +86,7 @@ public class AddSecondaryStorageCmdTest extends TestCase { StorageService resourceService = Mockito.mock(StorageService.class); addImageStoreCmd._storageService = resourceService; - Mockito.when(resourceService.discoverImageStore(anyString(), anyString(), anyString(), anyLong(), (Map)anyObject())) + Mockito.when(resourceService.discoverImageStore(anyString(), anyString(), anyString(), anyLong(), (Map)any())) .thenReturn(null); try { diff --git a/api/src/test/java/org/apache/cloudstack/api/command/test/CreateRoleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/test/CreateRoleCmdTest.java index 4b9d4fd8974..72ce9593364 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/test/CreateRoleCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/test/CreateRoleCmdTest.java @@ -54,6 +54,7 @@ public class CreateRoleCmdTest { when(role.getDescription()).thenReturn("User test"); when(role.getName()).thenReturn("testuser"); when(role.getRoleType()).thenReturn(RoleType.User); + when(role.getState()).thenReturn(Role.State.ENABLED); when(roleService.createRole(createRoleCmd.getRoleName(), createRoleCmd.getRoleType(), createRoleCmd.getRoleDescription(), true)).thenReturn(role); createRoleCmd.execute(); RoleResponse response = (RoleResponse) createRoleCmd.getResponseObject(); @@ -71,6 +72,7 @@ public class CreateRoleCmdTest { when(newRole.getDescription()).thenReturn("User test"); when(newRole.getName()).thenReturn("testuser"); when(newRole.getRoleType()).thenReturn(RoleType.User); + when(newRole.getState()).thenReturn(Role.State.ENABLED); when(roleService.createRole(createRoleCmd.getRoleName(), role, createRoleCmd.getRoleDescription(), true)).thenReturn(newRole); createRoleCmd.execute(); RoleResponse response = (RoleResponse) createRoleCmd.getResponseObject(); diff --git a/api/src/test/java/org/apache/cloudstack/api/command/test/CreateSnapshotCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/test/CreateSnapshotCmdTest.java index c5288067e94..34baebe5257 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/test/CreateSnapshotCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/test/CreateSnapshotCmdTest.java @@ -17,10 +17,10 @@ package org.apache.cloudstack.api.command.test; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.isNull; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.isNull; import java.util.HashMap; import java.util.List; @@ -126,7 +126,7 @@ public class CreateSnapshotCmdTest extends TestCase { try { Mockito.when(volumeApiService.takeSnapshot(nullable(Long.class), nullable(Long.class), nullable(Long.class), - nullable(Account.class), nullable(Boolean.class), nullable(Snapshot.LocationType.class), nullable(Boolean.class), anyObject(), Mockito.anyList())).thenReturn(null); + nullable(Account.class), nullable(Boolean.class), nullable(Snapshot.LocationType.class), nullable(Boolean.class), any(), Mockito.anyList())).thenReturn(null); } catch (Exception e) { Assert.fail("Received exception when success expected " + e.getMessage()); } diff --git a/api/src/test/java/org/apache/cloudstack/api/command/test/ImportRoleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/test/ImportRoleCmdTest.java index 6299c1ed8e2..d2597e5162f 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/test/ImportRoleCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/test/ImportRoleCmdTest.java @@ -32,19 +32,13 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyCollection; -import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.cloud.exception.InvalidParameterValueException; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; -import java.util.regex.Matcher; public class ImportRoleCmdTest { private ImportRoleCmd importRoleCmd; @@ -93,6 +87,7 @@ public class ImportRoleCmdTest { when(role.getDescription()).thenReturn("test user imported"); when(role.getName()).thenReturn("Test User"); when(role.getRoleType()).thenReturn(RoleType.User); + when(role.getState()).thenReturn(Role.State.ENABLED); when(roleService.importRole(anyString(), any(), anyString(), any(), anyBoolean(), anyBoolean())).thenReturn(role); importRoleCmd.execute(); diff --git a/api/src/test/java/org/apache/cloudstack/api/command/test/UpdateRoleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/test/UpdateRoleCmdTest.java index 84b91525742..9a1dae9a480 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/test/UpdateRoleCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/test/UpdateRoleCmdTest.java @@ -62,6 +62,7 @@ public class UpdateRoleCmdTest extends TestCase{ when(role.getId()).thenReturn(1L); when(role.getDescription()).thenReturn("Description Initial"); when(role.getName()).thenReturn("User"); + when(role.getState()).thenReturn(Role.State.ENABLED); updateRoleCmd.execute(); RoleResponse response = (RoleResponse) updateRoleCmd.getResponseObject(); assertEquals((String)ReflectionTestUtils.getField(response, "roleName"),role.getName()); diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/account/ListAccountsCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/account/ListAccountsCmdTest.java new file mode 100644 index 00000000000..a1ba9270345 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/account/ListAccountsCmdTest.java @@ -0,0 +1,87 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.account; + +import java.util.List; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.response.AccountResponse; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import com.cloud.user.ResourceLimitService; + +@RunWith(MockitoJUnitRunner.class) +public class ListAccountsCmdTest { + + @Mock + ResourceLimitService resourceLimitService; + + + @Test + public void testGetShowIcon() { + ListAccountsCmd cmd = new ListAccountsCmd(); + ReflectionTestUtils.setField(cmd, "showIcon", null); + Assert.assertFalse(cmd.getShowIcon()); + ReflectionTestUtils.setField(cmd, "showIcon", false); + Assert.assertFalse(cmd.getShowIcon()); + ReflectionTestUtils.setField(cmd, "showIcon", true); + Assert.assertTrue(cmd.getShowIcon()); + } + + @Test + public void testGetTag() { + ListAccountsCmd cmd = new ListAccountsCmd(); + ReflectionTestUtils.setField(cmd, "tag", null); + Assert.assertNull(cmd.getTag()); + String tag = "ABC"; + ReflectionTestUtils.setField(cmd, "tag", tag); + Assert.assertEquals(tag, cmd.getTag()); + } + + @Test + public void testUpdateAccountResponseNoAccounts() { + ListAccountsCmd cmd = new ListAccountsCmd(); + cmd._resourceLimitService = resourceLimitService; + cmd.updateAccountResponse(null); + Mockito.verify(resourceLimitService, Mockito.never()).updateTaggedResourceLimitsAndCountsForAccounts(Mockito.anyList(), Mockito.anyString()); + } + + @Test + public void testUpdateDomainResponseWithAccounts() { + ListAccountsCmd cmd = new ListAccountsCmd(); + cmd._resourceLimitService = resourceLimitService; + ReflectionTestUtils.setField(cmd, "tag", "abc"); + cmd.updateAccountResponse(List.of(Mockito.mock(AccountResponse.class))); + Mockito.verify(resourceLimitService, Mockito.times(1)).updateTaggedResourceLimitsAndCountsForAccounts(Mockito.any(), Mockito.any()); + } + + @Test + public void testUpdateDomainResponseWithAccountsMinDetails() { + ListAccountsCmd cmd = new ListAccountsCmd(); + ReflectionTestUtils.setField(cmd, "viewDetails", List.of(ApiConstants.DomainDetails.min.toString())); + cmd._resourceLimitService = resourceLimitService; + ReflectionTestUtils.setField(cmd, "tag", "abc"); + cmd.updateAccountResponse(List.of(Mockito.mock(AccountResponse.class))); + Mockito.verify(resourceLimitService, Mockito.never()).updateTaggedResourceLimitsAndCountsForAccounts(Mockito.any(), Mockito.any()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/bgp/ListASNumbersCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/bgp/ListASNumbersCmdTest.java new file mode 100644 index 00000000000..9d7f4ef7cf1 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/bgp/ListASNumbersCmdTest.java @@ -0,0 +1,97 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.user.bgp; + +import com.cloud.bgp.ASNumber; +import com.cloud.bgp.BGPService; + +import com.cloud.utils.Pair; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.response.ASNumberResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.ArrayList; +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) +public class ListASNumbersCmdTest { + + BGPService bgpService = Mockito.spy(BGPService.class); + ResponseGenerator _responseGenerator = Mockito.spy(ResponseGenerator.class); + + @Test + public void testListASNumbersCmdTest() { + Long zoneId = 1L; + Long asNumberRangeId = 2L; + Integer asNumber = 10; + Long networkId = 11L; + Long vpcId = 12L; + String account = "account"; + Long domainId = 13L; + + ListASNumbersCmd cmd = new ListASNumbersCmd(); + ReflectionTestUtils.setField(cmd, "zoneId", zoneId); + ReflectionTestUtils.setField(cmd, "asNumberRangeId", asNumberRangeId); + ReflectionTestUtils.setField(cmd, "asNumber", asNumber); + ReflectionTestUtils.setField(cmd, "networkId", networkId); + ReflectionTestUtils.setField(cmd, "vpcId", vpcId); + ReflectionTestUtils.setField(cmd, "account", account); + ReflectionTestUtils.setField(cmd, "domainId", domainId); + ReflectionTestUtils.setField(cmd, "allocated", Boolean.TRUE); + + ReflectionTestUtils.setField(cmd,"bgpService", bgpService); + ReflectionTestUtils.setField(cmd,"_responseGenerator", _responseGenerator); + + Assert.assertEquals(zoneId, cmd.getZoneId()); + Assert.assertEquals(asNumberRangeId, cmd.getAsNumberRangeId()); + Assert.assertEquals(asNumber, cmd.getAsNumber()); + Assert.assertEquals(networkId, cmd.getNetworkId()); + Assert.assertEquals(vpcId, cmd.getVpcId()); + Assert.assertEquals(account, cmd.getAccount()); + Assert.assertEquals(domainId, cmd.getDomainId()); + Assert.assertTrue(cmd.getAllocated()); + + List asNumbers = new ArrayList<>(); + ASNumber asn = Mockito.mock(ASNumber.class); + asNumbers.add(asn); + Pair, Integer> pair = new Pair<>(asNumbers, 1); + + ASNumberResponse asNumberResponse = Mockito.mock(ASNumberResponse.class); + Mockito.when(_responseGenerator.createASNumberResponse(asn)).thenReturn(asNumberResponse); + + Mockito.when(bgpService.listASNumbers(cmd)).thenReturn(pair); + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Object response = cmd.getResponseObject(); + Assert.assertTrue(response instanceof ListResponse); + ListResponse listResponse = (ListResponse) response; + Assert.assertEquals(1L, (long) listResponse.getCount()); + Assert.assertTrue(listResponse.getResponses().get(0) instanceof ASNumberResponse); + ASNumberResponse firstResponse = (ASNumberResponse) listResponse.getResponses().get(0); + Assert.assertEquals(asNumberResponse, firstResponse); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmdTest.java index 55a41c61ce6..76836caef28 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmdTest.java @@ -21,7 +21,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; @RunWith(MockitoJUnitRunner.class) diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/network/ListNetworkProtocolsCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/network/ListNetworkProtocolsCmdTest.java new file mode 100644 index 00000000000..7c29de69ade --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/network/ListNetworkProtocolsCmdTest.java @@ -0,0 +1,95 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.user.network; + +import com.cloud.utils.net.NetworkProtocols; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkProtocolResponse; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class ListNetworkProtocolsCmdTest { + + @Test + public void testListNetworkProtocolNumbers() { + ListNetworkProtocolsCmd cmd = new ListNetworkProtocolsCmd(); + String option = NetworkProtocols.Option.ProtocolNumber.toString(); + ReflectionTestUtils.setField(cmd, "option", option); + Assert.assertEquals(cmd.getOption(), option); + + try { + cmd.execute(); + } catch (Exception e) { + e.printStackTrace(); + } + Object response = cmd.getResponseObject(); + Assert.assertTrue(response instanceof ListResponse); + ListResponse listResponse = (ListResponse) response; + Assert.assertEquals(BaseCmd.getResponseNameByClass(cmd.getClass()), listResponse.getResponseName()); + Assert.assertNotNull(listResponse.getResponses()); + Assert.assertNotEquals(0, listResponse.getResponses().size()); + Object firstResponse = listResponse.getResponses().get(0); + Assert.assertTrue(firstResponse instanceof NetworkProtocolResponse); + Assert.assertEquals("networkprotocol", ((NetworkProtocolResponse) firstResponse).getObjectName()); + Assert.assertEquals(Integer.valueOf(0), ((NetworkProtocolResponse) firstResponse).getIndex()); + Assert.assertEquals("HOPOPT", ((NetworkProtocolResponse) firstResponse).getName()); + } + + @Test + public void testListIcmpTypes() { + ListNetworkProtocolsCmd cmd = new ListNetworkProtocolsCmd(); + String option = NetworkProtocols.Option.IcmpType.toString(); + ReflectionTestUtils.setField(cmd, "option", option); + Assert.assertEquals(cmd.getOption(), option); + + try { + cmd.execute(); + } catch (Exception e) { + e.printStackTrace(); + } + Object response = cmd.getResponseObject(); + Assert.assertTrue(response instanceof ListResponse); + ListResponse listResponse = (ListResponse) response; + Assert.assertEquals(BaseCmd.getResponseNameByClass(cmd.getClass()), listResponse.getResponseName()); + Assert.assertNotNull(listResponse.getResponses()); + Assert.assertNotEquals(0, listResponse.getResponses().size()); + Object firstResponse = listResponse.getResponses().get(0); + Assert.assertTrue(firstResponse instanceof NetworkProtocolResponse); + Assert.assertEquals("networkprotocol", ((NetworkProtocolResponse) firstResponse).getObjectName()); + Assert.assertEquals(Integer.valueOf(0), ((NetworkProtocolResponse) firstResponse).getIndex()); + Assert.assertNotNull(((NetworkProtocolResponse) firstResponse).getDetails()); + System.out.println(((NetworkProtocolResponse) firstResponse).getDetails()); + Assert.assertEquals("Echo reply", ((NetworkProtocolResponse) firstResponse).getDetails().get("0")); + } + + @Test(expected = IllegalArgumentException.class) + public void testListInvalidOption() { + ListNetworkProtocolsCmd cmd = new ListNetworkProtocolsCmd(); + String option = "invalid-option"; + ReflectionTestUtils.setField(cmd, "option", option); + Assert.assertEquals(cmd.getOption(), option); + + cmd.execute(); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/CreateRoutingFirewallRuleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/CreateRoutingFirewallRuleCmdTest.java new file mode 100644 index 00000000000..11c41f4c92d --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/CreateRoutingFirewallRuleCmdTest.java @@ -0,0 +1,251 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.user.network.routing; + +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.firewall.FirewallService; +import com.cloud.network.rules.FirewallRule; +import com.cloud.utils.net.NetUtils; + +import org.apache.cloudstack.api.ApiCommandResourceType; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +@RunWith(MockitoJUnitRunner.class) +public class CreateRoutingFirewallRuleCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + FirewallService _firewallService = Mockito.spy(FirewallService.class); + + ResponseGenerator _responseGenerator = Mockito.spy(ResponseGenerator.class); + + @Test + public void testIsDisplay() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + assertTrue(cmd.isDisplay()); + + ReflectionTestUtils.setField(cmd, "display", Boolean.TRUE); + assertTrue(cmd.isDisplay()); + + ReflectionTestUtils.setField(cmd, "display", Boolean.FALSE); + assertFalse(cmd.isDisplay()); + } + + @Test + public void testGetProtocolValid() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + assertEquals("", cmd.getProtocol()); + + ReflectionTestUtils.setField(cmd, "protocol", "1"); + assertEquals(NetUtils.ICMP_PROTO, cmd.getProtocol()); + + ReflectionTestUtils.setField(cmd, "protocol", "icmp"); + assertEquals(NetUtils.ICMP_PROTO, cmd.getProtocol()); + + ReflectionTestUtils.setField(cmd, "protocol", "6"); + assertEquals(NetUtils.TCP_PROTO, cmd.getProtocol()); + + ReflectionTestUtils.setField(cmd, "protocol", "tcp"); + assertEquals(NetUtils.TCP_PROTO, cmd.getProtocol()); + + ReflectionTestUtils.setField(cmd, "protocol", "17"); + assertEquals(NetUtils.UDP_PROTO, cmd.getProtocol()); + + ReflectionTestUtils.setField(cmd, "protocol", "udp"); + assertEquals(NetUtils.UDP_PROTO, cmd.getProtocol()); + } + + @Test(expected = InvalidParameterValueException.class) + public void testGetProtocolInValid() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + + ReflectionTestUtils.setField(cmd, "protocol", "100"); + cmd.getProtocol(); + } + + @Test + public void testGetSourceCidrListNull() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + + List result = cmd.getSourceCidrList(); + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(NetUtils.ALL_IP4_CIDRS, result.get(0)); + } + + @Test + public void testGetSourceCidrList() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + + List cidrList = Arrays.asList("192.168.0.0/24", "10.0.0.0/8"); + cmd.sourceCidrList = cidrList; + List result = cmd.getSourceCidrList(); + assertNotNull(result); + assertEquals(cidrList, result); + } + + @Test + public void testGetDestinationCidrListNull() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + + List result = cmd.getDestinationCidrList(); + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(NetUtils.ALL_IP4_CIDRS, result.get(0)); + } + + @Test + public void testGetDestinationCidrList() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + + List cidrList = Arrays.asList("192.168.0.0/24", "10.0.0.0/8"); + cmd.destinationCidrlist = cidrList; + List result = cmd.getDestinationCidrList(); + assertNotNull(result); + assertEquals(cidrList, result); + } + + @Test + public void testGetTrafficTypeValid() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + assertEquals(FirewallRule.TrafficType.Ingress, cmd.getTrafficType()); + + ReflectionTestUtils.setField(cmd, "trafficType", "ingress"); + assertEquals(FirewallRule.TrafficType.Ingress, cmd.getTrafficType()); + + ReflectionTestUtils.setField(cmd, "trafficType", "egress"); + assertEquals(FirewallRule.TrafficType.Egress, cmd.getTrafficType()); + } + + @Test(expected = InvalidParameterValueException.class) + public void testGetTrafficTypeInValid() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + + ReflectionTestUtils.setField(cmd, "trafficType", "invalid"); + cmd.getTrafficType(); + } + + @Test + public void testSourcePortStartEnd() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + assertNull(cmd.getSourcePortStart()); + assertNull(cmd.getSourcePortEnd()); + + ReflectionTestUtils.setField(cmd, "publicStartPort", 1111); + assertEquals(1111, (int) cmd.getSourcePortStart()); + assertEquals(1111, (int) cmd.getSourcePortEnd()); + + ReflectionTestUtils.setField(cmd, "publicEndPort", 2222); + assertEquals(1111, (int) cmd.getSourcePortStart()); + assertEquals(2222, (int) cmd.getSourcePortEnd()); + } + + @Test + public void testNetworkId() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + + ReflectionTestUtils.setField(cmd, "networkId", 1111L); + assertEquals(1111L, (long) cmd.getNetworkId()); + + assertEquals(1111L, (long) cmd.getApiResourceId()); + assertEquals(ApiCommandResourceType.Network, cmd.getApiResourceType()); + assertEquals(EventTypes.EVENT_ROUTING_IPV4_FIREWALL_RULE_CREATE, cmd.getEventType()); + assertEquals("Creating ipv4 firewall rule for routed network", cmd.getEventDescription()); + } + + @Test + public void testIcmpCodeAndType() { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + ReflectionTestUtils.setField(cmd, "protocol", "tcp"); + assertNull(cmd.getIcmpType()); + assertNull(cmd.getIcmpCode()); + + ReflectionTestUtils.setField(cmd, "protocol", "icmp"); + assertEquals(-1, (int) cmd.getIcmpType()); + assertEquals(-1, (int) cmd.getIcmpCode()); + + ReflectionTestUtils.setField(cmd, "icmpType", 1111); + ReflectionTestUtils.setField(cmd, "icmpCode", 2222); + assertEquals(1111, (int) cmd.getIcmpType()); + assertEquals(2222, (int) cmd.getIcmpCode()); + } + + @Test + public void testCreate() throws Exception { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + ReflectionTestUtils.setField(cmd, "routedIpv4Manager", routedIpv4Manager); + + Long id = 1L; + String uuid = "uuid"; + FirewallRule firewallRule = Mockito.spy(FirewallRule.class); + Mockito.when(firewallRule.getId()).thenReturn(id); + Mockito.when(firewallRule.getUuid()).thenReturn(uuid); + Mockito.when(routedIpv4Manager.createRoutingFirewallRule(cmd)).thenReturn(firewallRule); + + try { + cmd.create(); + } catch (Exception ignored) { + } + + assertEquals(id, cmd.getEntityId()); + assertEquals(uuid, cmd.getEntityUuid()); + } + + @Test + public void testExecute() throws Exception { + CreateRoutingFirewallRuleCmd cmd = new CreateRoutingFirewallRuleCmd(); + ReflectionTestUtils.setField(cmd, "routedIpv4Manager", routedIpv4Manager); + ReflectionTestUtils.setField(cmd, "_firewallService", _firewallService); + ReflectionTestUtils.setField(cmd, "_responseGenerator", _responseGenerator); + + Long id = 1L; + FirewallRule firewallRule = Mockito.spy(FirewallRule.class); + Mockito.when(firewallRule.getId()).thenReturn(id); + Mockito.when(_firewallService.getFirewallRule(id)).thenReturn(firewallRule); + Mockito.when(routedIpv4Manager.applyRoutingFirewallRule(id)).thenReturn(true); + + FirewallResponse ruleResponse = Mockito.mock(FirewallResponse.class); + Mockito.when(_responseGenerator.createFirewallResponse(firewallRule)).thenReturn(ruleResponse); + + try { + ReflectionTestUtils.setField(cmd, "id", id); + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(ruleResponse, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/DeleteRoutingFirewallRuleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/DeleteRoutingFirewallRuleCmdTest.java new file mode 100644 index 00000000000..2b55d4c6a58 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/DeleteRoutingFirewallRuleCmdTest.java @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.user.network.routing; + +import com.cloud.event.EventTypes; +import com.cloud.network.firewall.FirewallService; +import com.cloud.network.rules.FirewallRule; + +import org.apache.cloudstack.api.ApiCommandResourceType; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.junit.Assert.assertEquals; + +@RunWith(MockitoJUnitRunner.class) +public class DeleteRoutingFirewallRuleCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + FirewallService _firewallService = Mockito.spy(FirewallService.class); + + @Test + public void testProperties() { + DeleteRoutingFirewallRuleCmd cmd = new DeleteRoutingFirewallRuleCmd(); + ReflectionTestUtils.setField(cmd, "_firewallService", _firewallService); + + long id = 1L; + long accountId = 2L; + long networkId = 3L; + + FirewallRule firewallRule = Mockito.spy(FirewallRule.class); + Mockito.when(firewallRule.getAccountId()).thenReturn(accountId); + Mockito.when(firewallRule.getNetworkId()).thenReturn(networkId); + Mockito.when(_firewallService.getFirewallRule(id)).thenReturn(firewallRule); + + ReflectionTestUtils.setField(cmd, "id", id); + assertEquals(id, (long) cmd.getId()); + assertEquals(accountId, cmd.getEntityOwnerId()); + assertEquals(networkId, (long) cmd.getApiResourceId()); + assertEquals(ApiCommandResourceType.Network, cmd.getApiResourceType()); + assertEquals(EventTypes.EVENT_ROUTING_IPV4_FIREWALL_RULE_DELETE, cmd.getEventType()); + assertEquals(String.format("Deleting ipv4 routing firewall rule ID=%s", id), cmd.getEventDescription()); + } + + + @Test + public void testExecute() throws Exception { + DeleteRoutingFirewallRuleCmd cmd = new DeleteRoutingFirewallRuleCmd(); + ReflectionTestUtils.setField(cmd, "routedIpv4Manager", routedIpv4Manager); + + Long id = 1L; + Mockito.when(routedIpv4Manager.revokeRoutingFirewallRule(id)).thenReturn(true); + + try { + ReflectionTestUtils.setField(cmd, "id", id); + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertTrue(cmd.getResponseObject() instanceof SuccessResponse); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/ListRoutingFirewallRulesCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/ListRoutingFirewallRulesCmdTest.java new file mode 100644 index 00000000000..53ac45917cb --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/ListRoutingFirewallRulesCmdTest.java @@ -0,0 +1,115 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.user.network.routing; + +import com.cloud.network.rules.FirewallRule; +import com.cloud.utils.Pair; + +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +@RunWith(MockitoJUnitRunner.class) +public class ListRoutingFirewallRulesCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + ResponseGenerator _responseGenerator = Mockito.spy(ResponseGenerator.class); + + @Test + public void testIsDisplay() { + ListRoutingFirewallRulesCmd cmd = new ListRoutingFirewallRulesCmd(); + assertTrue(cmd.getDisplay()); + + ReflectionTestUtils.setField(cmd, "display", Boolean.TRUE); + assertTrue(cmd.getDisplay()); + + ReflectionTestUtils.setField(cmd, "display", Boolean.FALSE); + assertFalse(cmd.getDisplay()); + } + + @Test + public void testTrafficType() { + ListRoutingFirewallRulesCmd cmd = new ListRoutingFirewallRulesCmd(); + assertNull(cmd.getTrafficType()); + + ReflectionTestUtils.setField(cmd, "trafficType", "Ingress"); + assertEquals(FirewallRule.TrafficType.Ingress, cmd.getTrafficType()); + + ReflectionTestUtils.setField(cmd, "trafficType", "Egress"); + assertEquals(FirewallRule.TrafficType.Egress, cmd.getTrafficType()); + } + + @Test + public void testOtherProperties() { + ListRoutingFirewallRulesCmd cmd = new ListRoutingFirewallRulesCmd(); + + long id = 1L; + long networkId = 3L; + + ReflectionTestUtils.setField(cmd, "id", id); + ReflectionTestUtils.setField(cmd, "networkId", networkId); + + assertEquals(id, (long) cmd.getId()); + assertEquals(networkId, (long) cmd.getNetworkId()); + assertNull(cmd.getIpAddressId()); + } + + + @Test + public void testExecute() throws Exception { + ListRoutingFirewallRulesCmd cmd = new ListRoutingFirewallRulesCmd(); + ReflectionTestUtils.setField(cmd, "routedIpv4Manager", routedIpv4Manager); + ReflectionTestUtils.setField(cmd, "_responseGenerator", _responseGenerator); + + Long id = 1L; + FirewallRule firewallRule = Mockito.spy(FirewallRule.class); + List firewallRules = Arrays.asList(firewallRule); + Pair, Integer> result = new Pair<>(firewallRules, 1); + + Mockito.when(routedIpv4Manager.listRoutingFirewallRules(cmd)).thenReturn(result); + + FirewallResponse ruleResponse = Mockito.mock(FirewallResponse.class); + Mockito.when(_responseGenerator.createFirewallResponse(firewallRule)).thenReturn(ruleResponse); + + try { + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertTrue(cmd.getResponseObject() instanceof ListResponse); + ListResponse listResponse = (ListResponse) cmd.getResponseObject(); + Assert.assertEquals(1, (int) listResponse.getCount()); + Assert.assertEquals(ruleResponse, listResponse.getResponses().get(0)); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/UpdateRoutingFirewallRuleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/UpdateRoutingFirewallRuleCmdTest.java new file mode 100644 index 00000000000..dd0319df696 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/network/routing/UpdateRoutingFirewallRuleCmdTest.java @@ -0,0 +1,106 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.api.command.user.network.routing; + +import com.cloud.event.EventTypes; +import com.cloud.network.firewall.FirewallService; +import com.cloud.network.rules.FirewallRule; + +import org.apache.cloudstack.api.ApiCommandResourceType; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.network.RoutedIpv4Manager; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +@RunWith(MockitoJUnitRunner.class) +public class UpdateRoutingFirewallRuleCmdTest { + + RoutedIpv4Manager routedIpv4Manager = Mockito.spy(RoutedIpv4Manager.class); + + FirewallService _firewallService = Mockito.spy(FirewallService.class); + + ResponseGenerator _responseGenerator = Mockito.spy(ResponseGenerator.class); + + @Test + public void testIsDisplay() { + UpdateRoutingFirewallRuleCmd cmd = new UpdateRoutingFirewallRuleCmd(); + assertTrue(cmd.isDisplay()); + + ReflectionTestUtils.setField(cmd, "display", Boolean.TRUE); + assertTrue(cmd.isDisplay()); + + ReflectionTestUtils.setField(cmd, "display", Boolean.FALSE); + assertFalse(cmd.isDisplay()); + } + + @Test + public void testOtherProperties() { + UpdateRoutingFirewallRuleCmd cmd = new UpdateRoutingFirewallRuleCmd(); + ReflectionTestUtils.setField(cmd, "_firewallService", _firewallService); + + long id = 1L; + long accountId = 2L; + long networkId = 3L; + + FirewallRule firewallRule = Mockito.spy(FirewallRule.class); + Mockito.when(firewallRule.getAccountId()).thenReturn(accountId); + Mockito.when(firewallRule.getNetworkId()).thenReturn(networkId); + Mockito.when(_firewallService.getFirewallRule(id)).thenReturn(firewallRule); + + ReflectionTestUtils.setField(cmd, "id", id); + assertEquals(id, (long) cmd.getId()); + assertEquals(accountId, cmd.getEntityOwnerId()); + assertEquals(networkId, (long) cmd.getApiResourceId()); + assertEquals(ApiCommandResourceType.Network, cmd.getApiResourceType()); + assertEquals(EventTypes.EVENT_ROUTING_IPV4_FIREWALL_RULE_UPDATE, cmd.getEventType()); + assertEquals("Updating ipv4 routing firewall rule", cmd.getEventDescription()); + } + + + @Test + public void testExecute() throws Exception { + UpdateRoutingFirewallRuleCmd cmd = new UpdateRoutingFirewallRuleCmd(); + ReflectionTestUtils.setField(cmd, "routedIpv4Manager", routedIpv4Manager); + ReflectionTestUtils.setField(cmd, "_firewallService", _firewallService); + ReflectionTestUtils.setField(cmd, "_responseGenerator", _responseGenerator); + + Long id = 1L; + FirewallRule firewallRule = Mockito.spy(FirewallRule.class); + Mockito.when(routedIpv4Manager.updateRoutingFirewallRule(cmd)).thenReturn(firewallRule); + + FirewallResponse ruleResponse = Mockito.mock(FirewallResponse.class); + Mockito.when(_responseGenerator.createFirewallResponse(firewallRule)).thenReturn(ruleResponse); + + try { + ReflectionTestUtils.setField(cmd, "id", id); + cmd.execute(); + } catch (Exception ignored) { + } + + Assert.assertEquals(ruleResponse, cmd.getResponseObject()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmdTest.java new file mode 100644 index 00000000000..598fdd8ac4f --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmdTest.java @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.offering; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class ListDiskOfferingsCmdTest { + + @Test + public void testGetVirtualMachineId() { + ListDiskOfferingsCmd cmd = new ListDiskOfferingsCmd(); + ReflectionTestUtils.setField(cmd, "virtualMachineId", null); + Assert.assertNull(cmd.getVirtualMachineId()); + Long id = 100L; + ReflectionTestUtils.setField(cmd, "virtualMachineId", id); + Assert.assertEquals(id, cmd.getVirtualMachineId()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmdTest.java new file mode 100644 index 00000000000..f408132e5fc --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmdTest.java @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.offering; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + + +@RunWith(MockitoJUnitRunner.class) +public class ListServiceOfferingsCmdTest { + + @Test + public void testGetTemplateId() { + ListServiceOfferingsCmd cmd = new ListServiceOfferingsCmd(); + ReflectionTestUtils.setField(cmd, "templateId", null); + Assert.assertNull(cmd.getTemplateId()); + Long id = 100L; + ReflectionTestUtils.setField(cmd, "templateId", id); + Assert.assertEquals(id, cmd.getTemplateId()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/project/CreateProjectCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/project/CreateProjectCmdTest.java index ee3193123e0..dc1f2ca5189 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/project/CreateProjectCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/project/CreateProjectCmdTest.java @@ -21,7 +21,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; @RunWith(MockitoJUnitRunner.class) diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmdTest.java new file mode 100644 index 00000000000..3e999be2cfd --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmdTest.java @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.resource; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class ListResourceLimitsCmdTest { + + @Test + public void testGetTag() { + ListResourceLimitsCmd cmd = new ListResourceLimitsCmd(); + ReflectionTestUtils.setField(cmd, "tag", null); + Assert.assertNull(cmd.getTag()); + String tag = "ABC"; + ReflectionTestUtils.setField(cmd, "tag", tag); + Assert.assertEquals(tag, cmd.getTag()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmdTest.java new file mode 100644 index 00000000000..ab7d3253ab5 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmdTest.java @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.resource; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class UpdateResourceCountCmdTest { + + @Test + public void testGetTag() { + UpdateResourceCountCmd cmd = new UpdateResourceCountCmd(); + ReflectionTestUtils.setField(cmd, "tag", null); + Assert.assertNull(cmd.getTag()); + String tag = "ABC"; + ReflectionTestUtils.setField(cmd, "tag", tag); + Assert.assertEquals(tag, cmd.getTag()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmdTest.java new file mode 100644 index 00000000000..dff27a20044 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmdTest.java @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.resource; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +@RunWith(MockitoJUnitRunner.class) +public class UpdateResourceLimitCmdTest { + + @Test + public void testGetTag() { + UpdateResourceLimitCmd cmd = new UpdateResourceLimitCmd(); + ReflectionTestUtils.setField(cmd, "tag", null); + Assert.assertNull(cmd.getTag()); + String tag = "ABC"; + ReflectionTestUtils.setField(cmd, "tag", tag); + Assert.assertEquals(tag, cmd.getTag()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmdByAdminTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmdByAdminTest.java index 8639e135599..29b6144fd07 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmdByAdminTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmdByAdminTest.java @@ -28,7 +28,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import java.util.ArrayList; diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmdTest.java index 269a7b8a9e6..fb55e86dc0c 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/template/CopyTemplateCmdTest.java @@ -26,7 +26,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import java.util.ArrayList; diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmdByAdminTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmdByAdminTest.java index 1ba7963b2b9..1dc05888608 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmdByAdminTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmdByAdminTest.java @@ -29,7 +29,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import java.util.ArrayList; @RunWith(MockitoJUnitRunner.class) diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmdTest.java index 0c31e501519..a063f6c2d6b 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmdTest.java @@ -29,7 +29,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmdTest.java new file mode 100644 index 00000000000..03e558b58a8 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmdTest.java @@ -0,0 +1,49 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.command.user.template; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import com.cloud.storage.Storage; + +@RunWith(MockitoJUnitRunner.class) +public class UpdateTemplateCmdTest { + + @Test + public void testGetTemplateType() { + UpdateTemplateCmd cmd = new UpdateTemplateCmd(); + ReflectionTestUtils.setField(cmd, "templateType", null); + Assert.assertNull(cmd.getTemplateType()); + String type = Storage.TemplateType.ROUTING.toString(); + ReflectionTestUtils.setField(cmd, "templateTag", type); + Assert.assertEquals(type, cmd.getTemplateTag()); + } + + @Test + public void testGetTemplateTag() { + UpdateTemplateCmd cmd = new UpdateTemplateCmd(); + ReflectionTestUtils.setField(cmd, "templateTag", null); + Assert.assertNull(cmd.getTemplateTag()); + String tag = "ABC"; + ReflectionTestUtils.setField(cmd, "templateTag", tag); + Assert.assertEquals(tag, cmd.getTemplateTag()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/vm/CreateVMScheduleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/vm/CreateVMScheduleCmdTest.java index 2fdef2acaa9..99bc9d2b3fb 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/vm/CreateVMScheduleCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/vm/CreateVMScheduleCmdTest.java @@ -23,6 +23,7 @@ import com.cloud.utils.db.EntityManager; import com.cloud.vm.VirtualMachine; import org.apache.cloudstack.api.response.VMScheduleResponse; import org.apache.cloudstack.vm.schedule.VMScheduleManager; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -31,8 +32,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import java.security.InvalidParameterException; - public class CreateVMScheduleCmdTest { @Mock public VMScheduleManager vmScheduleManager; @@ -41,9 +40,16 @@ public class CreateVMScheduleCmdTest { @InjectMocks private CreateVMScheduleCmd createVMScheduleCmd = new CreateVMScheduleCmd(); + private AutoCloseable closeable; + @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); + } + + @After + public void tearDown() throws Exception { + closeable.close(); } /** @@ -62,11 +68,11 @@ public class CreateVMScheduleCmdTest { /** * given: "We have a VMScheduleManager and CreateVMScheduleCmd" * when: "CreateVMScheduleCmd is executed with an invalid parameter" - * then: "an InvalidParameterException is thrown" + * then: "an InvalidParameterValueException is thrown" */ - @Test(expected = InvalidParameterException.class) - public void testInvalidParameterException() { - Mockito.when(vmScheduleManager.createSchedule(createVMScheduleCmd)).thenThrow(InvalidParameterException.class); + @Test(expected = InvalidParameterValueException.class) + public void testInvalidParameterValueException() { + Mockito.when(vmScheduleManager.createSchedule(createVMScheduleCmd)).thenThrow(InvalidParameterValueException.class); createVMScheduleCmd.execute(); } @@ -86,7 +92,7 @@ public class CreateVMScheduleCmdTest { /** * given: "We have an EntityManager and CreateVMScheduleCmd" * when: "CreateVMScheduleCmd.getEntityOwnerId is executed for a VM which doesn't exist" - * then: "an InvalidParameterException is thrown" + * then: "an InvalidParameterValueException is thrown" */ @Test(expected = InvalidParameterValueException.class) public void testFailureGetEntityOwnerId() { diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/vm/DeleteVMScheduleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/vm/DeleteVMScheduleCmdTest.java index 6adfc2b905c..1f764a84365 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/vm/DeleteVMScheduleCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/vm/DeleteVMScheduleCmdTest.java @@ -25,6 +25,7 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.vm.schedule.VMSchedule; import org.apache.cloudstack.vm.schedule.VMScheduleManager; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -33,8 +34,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import java.security.InvalidParameterException; - public class DeleteVMScheduleCmdTest { @Mock public VMScheduleManager vmScheduleManager; @@ -44,9 +43,16 @@ public class DeleteVMScheduleCmdTest { @InjectMocks private DeleteVMScheduleCmd deleteVMScheduleCmd = new DeleteVMScheduleCmd(); + private AutoCloseable closeable; + @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); + } + + @After + public void tearDown() throws Exception { + closeable.close(); } /** @@ -81,11 +87,11 @@ public class DeleteVMScheduleCmdTest { /** * given: "We have a VMScheduleManager and DeleteVMScheduleCmd" * when: "DeleteVMScheduleCmd is executed with an invalid parameter" - * then: "an InvalidParameterException is thrown" + * then: "an InvalidParameterValueException is thrown" */ - @Test(expected = InvalidParameterException.class) - public void testInvalidParameterException() { - Mockito.when(vmScheduleManager.removeSchedule(deleteVMScheduleCmd)).thenThrow(InvalidParameterException.class); + @Test(expected = InvalidParameterValueException.class) + public void testInvalidParameterValueException() { + Mockito.when(vmScheduleManager.removeSchedule(deleteVMScheduleCmd)).thenThrow(InvalidParameterValueException.class); deleteVMScheduleCmd.execute(); } @@ -105,7 +111,7 @@ public class DeleteVMScheduleCmdTest { /** * given: "We have an EntityManager and DeleteVMScheduleCmd" * when: "DeleteVMScheduleCmd.getEntityOwnerId is executed for a VM which doesn't exist" - * then: "an InvalidParameterException is thrown" + * then: "an InvalidParameterValueException is thrown" */ @Test(expected = InvalidParameterValueException.class) public void testFailureGetEntityOwnerId() { diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/vm/ListVMScheduleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/vm/ListVMScheduleCmdTest.java index 18657b4c397..f5434de3581 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/vm/ListVMScheduleCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/vm/ListVMScheduleCmdTest.java @@ -18,9 +18,11 @@ */ package org.apache.cloudstack.api.command.user.vm; +import com.cloud.exception.InvalidParameterValueException; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.VMScheduleResponse; import org.apache.cloudstack.vm.schedule.VMScheduleManager; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -29,7 +31,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Collections; @@ -38,10 +39,16 @@ public class ListVMScheduleCmdTest { public VMScheduleManager vmScheduleManager; @InjectMocks private ListVMScheduleCmd listVMScheduleCmd = new ListVMScheduleCmd(); + private AutoCloseable closeable; @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); + } + + @After + public void tearDown() throws Exception { + closeable.close(); } /** @@ -81,11 +88,11 @@ public class ListVMScheduleCmdTest { /** * given: "We have a VMScheduleManager and ListVMScheduleCmd" * when: "ListVMScheduleCmd is executed with an invalid parameter" - * then: "an InvalidParameterException is thrown" + * then: "an InvalidParameterValueException is thrown" */ - @Test(expected = InvalidParameterException.class) - public void testInvalidParameterException() { - Mockito.when(vmScheduleManager.listSchedule(listVMScheduleCmd)).thenThrow(InvalidParameterException.class); + @Test(expected = InvalidParameterValueException.class) + public void testInvalidParameterValueException() { + Mockito.when(vmScheduleManager.listSchedule(listVMScheduleCmd)).thenThrow(InvalidParameterValueException.class); listVMScheduleCmd.execute(); ListResponse actualResponseObject = (ListResponse) listVMScheduleCmd.getResponseObject(); } diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/vm/UpdateVMScheduleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/vm/UpdateVMScheduleCmdTest.java index 044685b579c..2c6c485f25b 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/vm/UpdateVMScheduleCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/vm/UpdateVMScheduleCmdTest.java @@ -24,6 +24,7 @@ import com.cloud.vm.VirtualMachine; import org.apache.cloudstack.api.response.VMScheduleResponse; import org.apache.cloudstack.vm.schedule.VMSchedule; import org.apache.cloudstack.vm.schedule.VMScheduleManager; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -32,8 +33,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import java.security.InvalidParameterException; - public class UpdateVMScheduleCmdTest { @Mock public VMScheduleManager vmScheduleManager; @@ -42,9 +41,16 @@ public class UpdateVMScheduleCmdTest { @InjectMocks private UpdateVMScheduleCmd updateVMScheduleCmd = new UpdateVMScheduleCmd(); + private AutoCloseable closeable; + @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); + } + + @After + public void tearDown() throws Exception { + closeable.close(); } /** @@ -63,11 +69,11 @@ public class UpdateVMScheduleCmdTest { /** * given: "We have a VMScheduleManager and UpdateVMScheduleCmd" * when: "UpdateVMScheduleCmd is executed with an invalid parameter" - * then: "an InvalidParameterException is thrown" + * then: "an InvalidParameterValueException is thrown" */ - @Test(expected = InvalidParameterException.class) - public void testInvalidParameterException() { - Mockito.when(vmScheduleManager.updateSchedule(updateVMScheduleCmd)).thenThrow(InvalidParameterException.class); + @Test(expected = InvalidParameterValueException.class) + public void testInvalidParameterValueException() { + Mockito.when(vmScheduleManager.updateSchedule(updateVMScheduleCmd)).thenThrow(InvalidParameterValueException.class); updateVMScheduleCmd.execute(); } @@ -91,7 +97,7 @@ public class UpdateVMScheduleCmdTest { /** * given: "We have an EntityManager and UpdateVMScheduleCmd" * when: "UpdateVMScheduleCmd.getEntityOwnerId is executed for a VM Schedule which doesn't exist" - * then: "an InvalidParameterException is thrown" + * then: "an InvalidParameterValueException is thrown" */ @Test(expected = InvalidParameterValueException.class) public void testFailureGetEntityOwnerId() { diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmdTest.java index a28e9e9fd04..2505c67e87d 100644 --- a/api/src/test/java/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmdTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmdTest.java @@ -86,6 +86,20 @@ public class CreateVPCCmdTest extends TestCase { Assert.assertEquals(cmd.getCidr(), cidr); } + @Test + public void testGetCidrSize() { + int cidrSize = 24; + ReflectionTestUtils.setField(cmd, "cidrSize", cidrSize); + Assert.assertEquals(cidrSize, (int) cmd.getCidrSize()); + } + + @Test + public void testAsNumber() { + long asNumber = 10000; + ReflectionTestUtils.setField(cmd, "asNumber", asNumber); + Assert.assertEquals(asNumber, (long) cmd.getAsNumber()); + } + @Test public void testGetDisplayText() { String displayText = "VPC Network"; diff --git a/api/src/test/java/org/apache/cloudstack/api/response/ASNRangeResponseTest.java b/api/src/test/java/org/apache/cloudstack/api/response/ASNRangeResponseTest.java new file mode 100644 index 00000000000..50248383b4f --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/response/ASNRangeResponseTest.java @@ -0,0 +1,51 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.response; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Date; + +@RunWith(MockitoJUnitRunner.class) +public final class ASNRangeResponseTest { + + private static String uuid = "uuid"; + private static String zoneId = "zoneid"; + private static long startASNumber = 10; + private static long endASNumber = 20; + private static Date created = new Date(); + + @Test + public void testASNRangeResponse() { + final ASNRangeResponse response = new ASNRangeResponse(); + + response.setId(uuid); + response.setZoneId(zoneId); + response.setStartASNumber(startASNumber); + response.setEndASNumber(endASNumber); + response.setCreated(created); + + Assert.assertEquals(uuid, response.getId()); + Assert.assertEquals(zoneId, response.getZoneId()); + Assert.assertEquals(startASNumber, (long) response.getStartASNumber()); + Assert.assertEquals(endASNumber, (long) response.getEndASNumber()); + Assert.assertEquals(created, response.getCreated()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/response/ASNumberResponseTest.java b/api/src/test/java/org/apache/cloudstack/api/response/ASNumberResponseTest.java new file mode 100644 index 00000000000..9515984134e --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/response/ASNumberResponseTest.java @@ -0,0 +1,92 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.response; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Date; + +@RunWith(MockitoJUnitRunner.class) +public final class ASNumberResponseTest { + + private static String uuid = "uuid"; + private static String accountId = "account-id"; + private static String accountName = "account-name"; + private static String domainId = "domain-uuid"; + private static String domainName = "domain-name"; + private static Long asNumber = 15000L; + private static String asNumberRangeId = "as-number-range-uuid"; + private static String asNumberRange = "10000-20000"; + private static String zoneId = "zone-id"; + private static String zoneName = "zone-name"; + private static Date allocated = new Date(); + private static String allocationState = "allocated"; + + private static String associatedNetworkId = "network-id"; + + private static String associatedNetworkName = "network-name"; + + private static String vpcId = "vpc-uuid"; + private static String vpcName = "vpc-name"; + private static Date created = new Date(); + + + + @Test + public void testASNumberResponse() { + final ASNumberResponse response = new ASNumberResponse(); + + response.setId(uuid); + response.setAccountId(accountId); + response.setAccountName(accountName); + response.setDomainId(domainId); + response.setDomainName(domainName); + response.setAsNumber(asNumber); + response.setAsNumberRangeId(asNumberRangeId); + response.setAsNumberRange(asNumberRange); + response.setZoneId(zoneId); + response.setZoneName(zoneName); + response.setAllocated(allocated); + response.setAllocationState(allocationState); + response.setAssociatedNetworkId(associatedNetworkId); + response.setAssociatedNetworkName(associatedNetworkName); + response.setVpcId(vpcId); + response.setVpcName(vpcName); + response.setCreated(created); + + Assert.assertEquals(uuid, response.getId()); + Assert.assertEquals(accountId, response.getAccountId()); + Assert.assertEquals(accountName, response.getAccountName()); + Assert.assertEquals(domainId, response.getDomainId()); + Assert.assertEquals(domainName, response.getDomainName()); + Assert.assertEquals(asNumber, response.getAsNumber()); + Assert.assertEquals(asNumberRangeId, response.getAsNumberRangeId()); + Assert.assertEquals(asNumberRange, response.getAsNumberRange()); + Assert.assertEquals(zoneId, response.getZoneId()); + Assert.assertEquals(zoneName, response.getZoneName()); + Assert.assertEquals(allocated, response.getAllocated()); + Assert.assertEquals(allocationState, response.getAllocationState()); + Assert.assertEquals(associatedNetworkId, response.getAssociatedNetworkId()); + Assert.assertEquals(associatedNetworkName, response.getAssociatedNetworkName()); + Assert.assertEquals(vpcId, response.getVpcId()); + Assert.assertEquals(vpcName, response.getVpcName()); + Assert.assertEquals(created, response.getCreated()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/response/BgpPeerResponseTest.java b/api/src/test/java/org/apache/cloudstack/api/response/BgpPeerResponseTest.java new file mode 100644 index 00000000000..7c82eb84368 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/response/BgpPeerResponseTest.java @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.response; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@RunWith(MockitoJUnitRunner.class) +public final class BgpPeerResponseTest { + + private static String uuid = "uuid"; + private static String ip4Address = "ip4-address"; + private static String ip6Address = "ip6-address"; + private static Long asNumber = 15000L; + private static String password = "password"; + private static String accountName = "account-name"; + private static String domainId = "domain-uuid"; + private static String domainName = "domain-name"; + private static String projectId = "project-uuid"; + private static String projectName = "project-name"; + private static String zoneId = "zone-id"; + private static String zoneName = "zone-name"; + private static Date created = new Date(); + + @Test + public void testBgpPeerResponse() { + final BgpPeerResponse response = new BgpPeerResponse(); + + response.setId(uuid); + response.setIp4Address(ip4Address); + response.setIp6Address(ip6Address); + response.setAsNumber(asNumber); + response.setPassword(password); + response.setAccountName(accountName); + response.setDomainId(domainId); + response.setDomainName(domainName); + response.setProjectId(projectId); + response.setProjectName(projectName); + response.setZoneId(zoneId); + response.setZoneName(zoneName); + response.setCreated(created); + Map details = new HashMap<>(); + details.put("key", "value"); + response.setDetails(details); + + Assert.assertEquals(uuid, response.getId()); + Assert.assertEquals(ip4Address, response.getIp4Address()); + Assert.assertEquals(ip6Address, response.getIp6Address()); + Assert.assertEquals(asNumber, response.getAsNumber()); + Assert.assertEquals(password, response.getPassword()); + Assert.assertEquals(accountName, response.getAccountName()); + Assert.assertEquals(domainId, response.getDomainId()); + Assert.assertEquals(domainName, response.getDomainName()); + Assert.assertEquals(projectId, response.getProjectId()); + Assert.assertEquals(projectName, response.getProjectName()); + Assert.assertEquals(zoneId, response.getZoneId()); + Assert.assertEquals(zoneName, response.getZoneName()); + Assert.assertEquals(created, response.getCreated()); + Assert.assertEquals(details, response.getDetails()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/response/DataCenterIpv4SubnetResponseTest.java b/api/src/test/java/org/apache/cloudstack/api/response/DataCenterIpv4SubnetResponseTest.java new file mode 100644 index 00000000000..add9544de7d --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/response/DataCenterIpv4SubnetResponseTest.java @@ -0,0 +1,66 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.response; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Date; + +@RunWith(MockitoJUnitRunner.class) +public final class DataCenterIpv4SubnetResponseTest { + + private static String uuid = "uuid"; + private static String subnet = "10.10.10.0/26"; + private static String accountName = "account-name"; + private static String domainId = "domain-uuid"; + private static String domainName = "domain-name"; + private static String projectId = "project-uuid"; + private static String projectName = "project-name"; + private static String zoneId = "zone-id"; + private static String zoneName = "zone-name"; + private static Date created = new Date(); + + @Test + public void testDataCenterIpv4SubnetResponse() { + final DataCenterIpv4SubnetResponse response = new DataCenterIpv4SubnetResponse(); + + response.setId(uuid); + response.setSubnet(subnet); + response.setAccountName(accountName); + response.setDomainId(domainId); + response.setDomainName(domainName); + response.setProjectId(projectId); + response.setProjectName(projectName); + response.setZoneId(zoneId); + response.setZoneName(zoneName); + response.setCreated(created); + + Assert.assertEquals(uuid, response.getId()); + Assert.assertEquals(subnet, response.getSubnet()); + Assert.assertEquals(accountName, response.getAccountName()); + Assert.assertEquals(domainId, response.getDomainId()); + Assert.assertEquals(domainName, response.getDomainName()); + Assert.assertEquals(projectId, response.getProjectId()); + Assert.assertEquals(projectName, response.getProjectName()); + Assert.assertEquals(zoneId, response.getZoneId()); + Assert.assertEquals(zoneName, response.getZoneName()); + Assert.assertEquals(created, response.getCreated()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/response/Ipv4RouteResponseTest.java b/api/src/test/java/org/apache/cloudstack/api/response/Ipv4RouteResponseTest.java new file mode 100644 index 00000000000..717668d054e --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/response/Ipv4RouteResponseTest.java @@ -0,0 +1,48 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.response; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public final class Ipv4RouteResponseTest { + + private static String subnet = "10.10.10.0/24"; + private static String gateway = "10.10.10.1"; + + @Test + public void testIpv4RouteResponse() { + final Ipv4RouteResponse response = new Ipv4RouteResponse(subnet, gateway); + + Assert.assertEquals(subnet, response.getSubnet()); + Assert.assertEquals(gateway, response.getGateway()); + } + + @Test + public void testIpv4RouteResponse2() { + final Ipv4RouteResponse response = new Ipv4RouteResponse(); + + response.setSubnet(subnet); + response.setGateway(gateway); + + Assert.assertEquals(subnet, response.getSubnet()); + Assert.assertEquals(gateway, response.getGateway()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/response/Ipv4SubnetForGuestNetworkResponseTest.java b/api/src/test/java/org/apache/cloudstack/api/response/Ipv4SubnetForGuestNetworkResponseTest.java new file mode 100644 index 00000000000..6fb5141e7a9 --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/response/Ipv4SubnetForGuestNetworkResponseTest.java @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.api.response; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Date; + +@RunWith(MockitoJUnitRunner.class) +public final class Ipv4SubnetForGuestNetworkResponseTest { + + private static String uuid = "uuid"; + private static String parentId = "parent-id"; + private static String parentSubnet = "10.10.0.0/20"; + private static String subnet = "10.10.0.0/24"; + private static String state = "Allocating"; + + private static String zoneId = "zone-id"; + private static String zoneName = "zone-name"; + private static Date allocated = new Date(); + private static String networkId = "network-id"; + private static String networkName = "network-name"; + private static String vpcId = "vpc-uuid"; + private static String vpcName = "vpc-name"; + private static Date created = new Date(); + private static Date removed = new Date(); + + + + @Test + public void testIpv4SubnetForGuestNetworkResponse() { + final Ipv4SubnetForGuestNetworkResponse response = new Ipv4SubnetForGuestNetworkResponse(); + + response.setId(uuid); + response.setSubnet(subnet); + response.setParentId(parentId); + response.setParentSubnet(parentSubnet); + response.setState(state); + response.setZoneId(zoneId); + response.setZoneName(zoneName); + response.setAllocatedTime(allocated); + response.setNetworkId(networkId); + response.setNetworkName(networkName); + response.setVpcId(vpcId); + response.setVpcName(vpcName); + response.setCreated(created); + response.setRemoved(removed); + + Assert.assertEquals(uuid, response.getId()); + Assert.assertEquals(subnet, response.getSubnet()); + Assert.assertEquals(parentId, response.getParentId()); + Assert.assertEquals(parentSubnet, response.getParentSubnet()); + Assert.assertEquals(state, response.getState()); + Assert.assertEquals(zoneId, response.getZoneId()); + Assert.assertEquals(zoneName, response.getZoneName()); + Assert.assertEquals(allocated, response.getAllocatedTime()); + Assert.assertEquals(networkId, response.getNetworkId()); + Assert.assertEquals(networkName, response.getNetworkName()); + Assert.assertEquals(vpcId, response.getVpcId()); + Assert.assertEquals(vpcName, response.getVpcName()); + Assert.assertEquals(created, response.getCreated()); + Assert.assertEquals(removed, response.getRemoved()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/context/CallContextTest.java b/api/src/test/java/org/apache/cloudstack/context/CallContextTest.java index eb1336f90e9..d3537d6f831 100644 --- a/api/src/test/java/org/apache/cloudstack/context/CallContextTest.java +++ b/api/src/test/java/org/apache/cloudstack/context/CallContextTest.java @@ -28,7 +28,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.cloud.user.Account; import com.cloud.user.User; diff --git a/api/src/test/java/org/apache/cloudstack/network/BgpPeerTOTest.java b/api/src/test/java/org/apache/cloudstack/network/BgpPeerTOTest.java new file mode 100644 index 00000000000..2d1f8868ffc --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/network/BgpPeerTOTest.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.network; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +public class BgpPeerTOTest { + + private static Long peerId = 100L; + private static String ip4Address = "ip4-address"; + private static String ip6Address = "ip6-address"; + private static Long peerAsNumber = 15000L; + private static String peerPassword = "peer-password"; + private static Long networkId = 200L; + private static Long networkAsNumber = 20000L; + private static String guestIp4Cidr = "10.10.10.0/24"; + private static String guestIp6Cidr = "fd00:1111:2222:3333::1/64"; + + @Test + public void testBgpPeerTO1() { + BgpPeerTO bgpPeerTO = new BgpPeerTO(networkId); + + Assert.assertEquals(networkId, bgpPeerTO.getNetworkId()); + } + + @Test + public void testBgpPeerTO2() { + Map details = new HashMap<>(); + details.put(BgpPeer.Detail.EBGP_MultiHop, "100"); + + BgpPeerTO bgpPeerTO = new BgpPeerTO(peerId, ip4Address, ip6Address, peerAsNumber, peerPassword, + networkId, networkAsNumber, guestIp4Cidr, guestIp6Cidr, details); + + Assert.assertEquals(peerId, bgpPeerTO.getPeerId()); + Assert.assertEquals(peerAsNumber, bgpPeerTO.getPeerAsNumber()); + Assert.assertEquals(ip4Address, bgpPeerTO.getIp4Address()); + Assert.assertEquals(ip6Address, bgpPeerTO.getIp6Address()); + Assert.assertEquals(peerPassword, bgpPeerTO.getPeerPassword()); + Assert.assertEquals(networkId, bgpPeerTO.getNetworkId()); + Assert.assertEquals(networkAsNumber, bgpPeerTO.getNetworkAsNumber()); + Assert.assertEquals(guestIp4Cidr, bgpPeerTO.getGuestIp4Cidr()); + Assert.assertEquals(guestIp6Cidr, bgpPeerTO.getGuestIp6Cidr()); + + Assert.assertNotNull(bgpPeerTO.getDetails()); + details = bgpPeerTO.getDetails(); + Assert.assertEquals(1, details.size()); + Assert.assertEquals("100", details.get(BgpPeer.Detail.EBGP_MultiHop)); + } +} diff --git a/api/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/api/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker deleted file mode 100644 index 1f0955d450f..00000000000 --- a/api/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker +++ /dev/null @@ -1 +0,0 @@ -mock-maker-inline diff --git a/build/replace.properties b/build/replace.properties index 3d9a4597060..ce38727b80a 100644 --- a/build/replace.properties +++ b/build/replace.properties @@ -5,9 +5,9 @@ # to you 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 diff --git a/client/bindir/cloud-setup-management.in b/client/bindir/cloud-setup-management.in index 70e727b40b2..84c87ae2e44 100755 --- a/client/bindir/cloud-setup-management.in +++ b/client/bindir/cloud-setup-management.in @@ -16,13 +16,27 @@ # specific language governing permissions and limitations # under the License. +import os import sys +# ---- This snippet of code adds the sources path and the waf configured PYTHONDIR to the Python path ---- +# ---- We do this so cloud_utils can be looked up in the following order: +# ---- 1) Sources directory +# ---- 2) waf configured PYTHONDIR +# ---- 3) System Python path +for pythonpath in ( + "@PYTHONDIR@", + os.path.join(os.path.dirname(__file__),os.path.pardir,os.path.pardir,"python","lib"), + ): + if os.path.isdir(pythonpath): sys.path.insert(0,pythonpath) +# ---- End snippet of code ---- + from cloudutils.syscfg import sysConfigFactory from cloudutils.utilities import initLoging, UnknownSystemException from cloudutils.cloudException import CloudRuntimeException, CloudInternalException from cloudutils.globalEnv import globalEnv from cloudutils.serviceConfigServer import cloudManagementConfig from optparse import OptionParser + if __name__ == '__main__': initLoging("@MSLOGDIR@/setupManagement.log") glbEnv = globalEnv() diff --git a/client/bindir/cloud-update-xenserver-licenses.in b/client/bindir/cloud-update-xenserver-licenses.in index 9ce1898dc81..2be3a083f97 100755 --- a/client/bindir/cloud-update-xenserver-licenses.in +++ b/client/bindir/cloud-update-xenserver-licenses.in @@ -7,9 +7,9 @@ # to you 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 @@ -46,7 +46,7 @@ cfg = "@MSCONF@/db.properties" #---------------------- option parsing and command line checks ------------------------ -usage = """%prog <-a | host names / IP addresses...> +usage = """%prog <-a | host names / IP addresses...> This command deploys the license file specified in the command line into a specific XenServer host or all XenServer hosts known to the management server.""" @@ -88,7 +88,7 @@ def parseuserpwfromhosts(hosts): return creds class XenServerConfigurator(Thread): - + def __init__(self,host,user,password,keyfiledata): Thread.__init__(self) self.host = host @@ -99,7 +99,7 @@ class XenServerConfigurator(Thread): self.stdout = "" self.stderr = "" self.state = 'initialized' - + def run(self): try: self.state = 'running' @@ -120,18 +120,18 @@ class XenServerConfigurator(Thread): c.close() if self.retval != 0: self.state = 'failed' else: self.state = 'finished' - + except Exception as e: self.state = 'failed' self.retval = e #raise - + def __str__(self): if self.state == 'failed': return "<%s XenServerConfigurator on %s@%s: %s>"%(self.state,self.user,self.host,str(self.retval)) else: return "<%s XenServerConfigurator on %s@%s>"%(self.state,self.user,self.host) - + #------------- actual code -------------------- (options, args) = parser.parse_args() @@ -162,7 +162,7 @@ for host,(user,password) in list(creds.items()): for c in configurators: c.start() - + for c in configurators: print(c.host + "...", end=' ') c.join() diff --git a/client/conf/db.properties.in b/client/conf/db.properties.in index 8f31aff17e6..0f7d2706a42 100644 --- a/client/conf/db.properties.in +++ b/client/conf/db.properties.in @@ -34,10 +34,14 @@ db.cloud.uri= # CloudStack database tuning parameters +db.cloud.connectionPoolLib=hikaricp db.cloud.maxActive=250 db.cloud.maxIdle=30 -db.cloud.maxWait=10000 -db.cloud.validationQuery=SELECT 1 +db.cloud.maxWait=600000 +db.cloud.minIdleConnections=5 +db.cloud.connectionTimeout=30000 +db.cloud.keepAliveTime=600000 +db.cloud.validationQuery=/* ping */ SELECT 1 db.cloud.testOnBorrow=true db.cloud.testWhileIdle=true db.cloud.timeBetweenEvictionRunsMillis=40000 @@ -70,9 +74,13 @@ db.usage.uri= # usage database tuning parameters +db.usage.connectionPoolLib=hikaricp db.usage.maxActive=100 db.usage.maxIdle=30 -db.usage.maxWait=10000 +db.usage.maxWait=600000 +db.usage.minIdleConnections=5 +db.usage.connectionTimeout=30000 +db.usage.keepAliveTime=600000 db.usage.url.params=serverTimezone=UTC # Simulator database settings @@ -82,9 +90,13 @@ db.simulator.host=@DBHOST@ db.simulator.driver=@DBDRIVER@ db.simulator.port=3306 db.simulator.name=simulator +db.simulator.connectionPoolLib=hikaricp db.simulator.maxActive=250 db.simulator.maxIdle=30 -db.simulator.maxWait=10000 +db.simulator.maxWait=600000 +db.simulator.minIdleConnections=5 +db.simulator.connectionTimeout=30000 +db.simulator.keepAliveTime=600000 db.simulator.autoReconnect=true # Connection URI to the database "simulator". When this property is set, only the following properties will be used along with it: db.simulator.host, db.simulator.port, db.simulator.name, db.simulator.autoReconnect. Other properties will be ignored. diff --git a/client/conf/log4j-cloud.xml.in b/client/conf/log4j-cloud.xml.in index 223692881de..26da171269d 100755 --- a/client/conf/log4j-cloud.xml.in +++ b/client/conf/log4j-cloud.xml.in @@ -17,183 +17,118 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> - + + - - + + net.sf.cglib.proxy + - - - + + + - - - - - - - - - - - - + + + + + + + + - - - - - - - - - - - - - - + + + + + + + - - - - - - - - + + + - - - + + + + - - - - - - - - + + + - - - + + + + - - - - - - - - - - + + + - - - + + + + - - - - - - - + + + - - - + + + + - - - + - - - + - - - + - - - + - - - - + - - - + - - - + - - - + - - - + - - - + - - - + - - - + + + - - - - + - - - - + - - - - + + + + + + + - - - + + + - - - - - - - - + + + + + - - - - - - - - - - - - + + diff --git a/client/pom.xml b/client/pom.xml index 9762594ecdf..5174dfe493a 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -25,7 +25,7 @@ org.apache.cloudstack cloudstack - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT @@ -422,6 +422,11 @@ cloud-mom-kafka ${project.version} + + org.apache.cloudstack + cloud-mom-webhook + ${project.version} + org.apache.cloudstack cloud-framework-agent-lb @@ -607,6 +612,11 @@ cloud-plugin-backup-networker ${project.version} + + org.apache.cloudstack + cloud-plugin-backup-nas + ${project.version} + org.apache.cloudstack cloud-plugin-integrations-kubernetes-service @@ -627,11 +637,21 @@ cloud-plugin-storage-object-minio ${project.version} + + org.apache.cloudstack + cloud-plugin-storage-object-ceph + ${project.version} + org.apache.cloudstack cloud-plugin-storage-object-simulator ${project.version} + + org.apache.cloudstack + cloud-plugin-sharedfs-provider-storagevm + ${project.version} + org.apache.cloudstack cloud-usage @@ -727,7 +747,7 @@ - log4j.configuration + log4j2.configurationFile log4j-cloud.xml @@ -1072,6 +1092,11 @@ cloud-plugin-network-cisco-vnmc ${project.version} + + org.apache.cloudstack + cloud-plugin-network-nsx + ${project.version} + org.apache.cloudstack cloud-plugin-network-tungsten diff --git a/client/src/main/java/org/apache/cloudstack/ServerDaemon.java b/client/src/main/java/org/apache/cloudstack/ServerDaemon.java index e33a4084e4e..c6fd2ff24dc 100644 --- a/client/src/main/java/org/apache/cloudstack/ServerDaemon.java +++ b/client/src/main/java/org/apache/cloudstack/ServerDaemon.java @@ -29,7 +29,6 @@ import java.util.Properties; import org.apache.commons.daemon.Daemon; import org.apache.commons.daemon.DaemonContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; @@ -50,6 +49,8 @@ import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler; import org.eclipse.jetty.webapp.WebAppContext; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.utils.Pair; import com.cloud.utils.PropertiesUtil; @@ -61,7 +62,7 @@ import com.cloud.utils.server.ServerProperties; * Configuration parameters are read from server.properties file available on the classpath. */ public class ServerDaemon implements Daemon { - private static final Logger LOG = Logger.getLogger(ServerDaemon.class); + protected Logger logger = LogManager.getLogger(getClass()); private static final String WEB_XML = "META-INF/webapp/WEB-INF/web.xml"; ///////////////////////////////////////////////////// @@ -118,12 +119,12 @@ public class ServerDaemon implements Daemon { public void init(final DaemonContext context) { final File confFile = PropertiesUtil.findConfigFile("server.properties"); if (confFile == null) { - LOG.warn(String.format("Server configuration file not found. Initializing server daemon on %s, with http.enable=%s, http.port=%s, https.enable=%s, https.port=%s, context.path=%s", + logger.warn(String.format("Server configuration file not found. Initializing server daemon on %s, with http.enable=%s, http.port=%s, https.enable=%s, https.port=%s, context.path=%s", bindInterface, httpEnable, httpPort, httpsEnable, httpsPort, contextPath)); return; } - LOG.info("Server configuration file found: " + confFile.getAbsolutePath()); + logger.info("Server configuration file found: " + confFile.getAbsolutePath()); try { InputStream is = new FileInputStream(confFile); @@ -145,15 +146,15 @@ public class ServerDaemon implements Daemon { setMaxFormContentSize(Integer.valueOf(properties.getProperty(REQUEST_CONTENT_SIZE_KEY, String.valueOf(DEFAULT_REQUEST_CONTENT_SIZE)))); setMaxFormKeys(Integer.valueOf(properties.getProperty(REQUEST_MAX_FORM_KEYS_KEY, String.valueOf(DEFAULT_REQUEST_MAX_FORM_KEYS)))); } catch (final IOException e) { - LOG.warn("Failed to read configuration from server.properties file", e); + logger.warn("Failed to read configuration from server.properties file", e); } finally { // make sure that at least HTTP is enabled if both of them are set to false (misconfiguration) if (!httpEnable && !httpsEnable) { setHttpEnable(true); - LOG.warn("Server configuration malformed, neither http nor https is enabled, http will be enabled."); + logger.warn("Server configuration malformed, neither http nor https is enabled, http will be enabled."); } } - LOG.info(String.format("Initializing server daemon on %s, with http.enable=%s, http.port=%s, https.enable=%s, https.port=%s, context.path=%s", + logger.info(String.format("Initializing server daemon on %s, with http.enable=%s, http.port=%s, https.enable=%s, https.port=%s, context.path=%s", bindInterface, httpEnable, httpPort, httpsEnable, httpsPort, contextPath)); } @@ -258,7 +259,7 @@ public class ServerDaemon implements Daemon { KeyStoreScanner scanner = new KeyStoreScanner(sslContextFactory); server.addBean(scanner); } catch (Exception ex) { - LOG.error("failed to set up keystore scanner, manual refresh of certificates will be required", ex); + logger.error("failed to set up keystore scanner, manual refresh of certificates will be required", ex); } } } diff --git a/client/src/main/resources/META-INF/cloudstack/webApplicationContext.xml b/client/src/main/resources/META-INF/cloudstack/webApplicationContext.xml index 3b3c6dbe35c..e1c46268618 100644 --- a/client/src/main/resources/META-INF/cloudstack/webApplicationContext.xml +++ b/client/src/main/resources/META-INF/cloudstack/webApplicationContext.xml @@ -25,7 +25,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" - > + > diff --git a/client/src/main/webapp/WEB-INF/web.xml b/client/src/main/webapp/WEB-INF/web.xml index 9a3d8bc5b29..43bee7e59d8 100644 --- a/client/src/main/webapp/WEB-INF/web.xml +++ b/client/src/main/webapp/WEB-INF/web.xml @@ -21,7 +21,7 @@ version="2.5"> - log4jConfigLocation + log4jConfiguration classpath:log4j-cloud.xml diff --git a/core/pom.xml b/core/pom.xml index a5280c02db7..0b3cbfb7619 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT diff --git a/core/src/main/java/com/cloud/agent/api/GetStorageStatsAnswer.java b/core/src/main/java/com/cloud/agent/api/GetStorageStatsAnswer.java index 26e7b749586..79753661066 100644 --- a/core/src/main/java/com/cloud/agent/api/GetStorageStatsAnswer.java +++ b/core/src/main/java/com/cloud/agent/api/GetStorageStatsAnswer.java @@ -27,24 +27,46 @@ public class GetStorageStatsAnswer extends Answer implements StorageStats { protected GetStorageStatsAnswer() { } - protected long used; + protected long usedBytes; - protected long capacity; + protected long capacityBytes; + + protected Long capacityIops; + + protected Long usedIops; @Override public long getByteUsed() { - return used; + return usedBytes; } @Override public long getCapacityBytes() { - return capacity; + return capacityBytes; } - public GetStorageStatsAnswer(GetStorageStatsCommand cmd, long capacity, long used) { + @Override + public Long getCapacityIops() { + return capacityIops; + } + + @Override + public Long getUsedIops() { + return usedIops; + } + + public GetStorageStatsAnswer(GetStorageStatsCommand cmd, long capacityBytes, long usedBytes) { super(cmd, true, null); - this.capacity = capacity; - this.used = used; + this.capacityBytes = capacityBytes; + this.usedBytes = usedBytes; + } + + public GetStorageStatsAnswer(GetStorageStatsCommand cmd, long capacityBytes, long usedBytes, Long capacityIops, Long usedIops) { + super(cmd, true, null); + this.capacityBytes = capacityBytes; + this.usedBytes = usedBytes; + this.capacityIops = capacityIops; + this.usedIops = usedIops; } public GetStorageStatsAnswer(GetStorageStatsCommand cmd, String details) { diff --git a/core/src/main/java/com/cloud/agent/api/ReadyCommand.java b/core/src/main/java/com/cloud/agent/api/ReadyCommand.java index 637e4f54da0..e2d974e3878 100644 --- a/core/src/main/java/com/cloud/agent/api/ReadyCommand.java +++ b/core/src/main/java/com/cloud/agent/api/ReadyCommand.java @@ -19,6 +19,8 @@ package com.cloud.agent.api; +import com.cloud.host.Host; + import java.util.List; public class ReadyCommand extends Command { @@ -30,19 +32,24 @@ public class ReadyCommand extends Command { private Long dcId; private Long hostId; + private String hostUuid; + private String hostName; private List msHostList; private String lbAlgorithm; private Long lbCheckInterval; private Boolean enableHumanReadableSizes; + private String arch; public ReadyCommand(Long dcId) { super(); this.dcId = dcId; } - public ReadyCommand(final Long dcId, final Long hostId, boolean enableHumanReadableSizes) { - this(dcId); - this.hostId = hostId; + public ReadyCommand(final Host host, boolean enableHumanReadableSizes) { + this(host.getDataCenterId()); + this.hostId = host.getId(); + this.hostUuid = host.getUuid(); + this.hostName = host.getName(); this.enableHumanReadableSizes = enableHumanReadableSizes; } @@ -67,6 +74,14 @@ public class ReadyCommand extends Command { return hostId; } + public String getHostUuid() { + return hostUuid; + } + + public String getHostName() { + return hostName; + } + public List getMsHostList() { return msHostList; } @@ -94,4 +109,12 @@ public class ReadyCommand extends Command { public Boolean getEnableHumanReadableSizes() { return enableHumanReadableSizes; } + + public String getArch() { + return arch; + } + + public void setArch(String arch) { + this.arch = arch; + } } diff --git a/core/src/main/java/com/cloud/agent/api/SecurityGroupRulesCmd.java b/core/src/main/java/com/cloud/agent/api/SecurityGroupRulesCmd.java index ea4ab96c5a7..5d202172c35 100644 --- a/core/src/main/java/com/cloud/agent/api/SecurityGroupRulesCmd.java +++ b/core/src/main/java/com/cloud/agent/api/SecurityGroupRulesCmd.java @@ -27,7 +27,6 @@ import java.util.zip.DeflaterOutputStream; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; -import org.apache.log4j.Logger; import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.agent.api.to.VirtualMachineTO; @@ -39,7 +38,6 @@ public class SecurityGroupRulesCmd extends Command { public static final char RULE_COMMAND_SEPARATOR = ';'; protected static final String EGRESS_RULE = "E:"; protected static final String INGRESS_RULE = "I:"; - private static final Logger LOGGER = Logger.getLogger(SecurityGroupRulesCmd.class); private final String guestIp; private final String guestIp6; @@ -233,7 +231,7 @@ public class SecurityGroupRulesCmd extends Command { dzip.close(); encodedResult = Base64.encodeBase64String(out.toByteArray()); } catch (final IOException e) { - LOGGER.warn("Exception while compressing security group rules"); + logger.warn("Exception while compressing security group rules"); } return encodedResult; } diff --git a/core/src/main/java/com/cloud/agent/api/SetupGuestNetworkCommand.java b/core/src/main/java/com/cloud/agent/api/SetupGuestNetworkCommand.java index e9781993239..06583f2d0d3 100644 --- a/core/src/main/java/com/cloud/agent/api/SetupGuestNetworkCommand.java +++ b/core/src/main/java/com/cloud/agent/api/SetupGuestNetworkCommand.java @@ -35,6 +35,7 @@ public class SetupGuestNetworkCommand extends NetworkElementCommand { String routerIpv6 = null; String routerIpv6Gateway = null; String routerIpv6Cidr = null; + boolean isVrGuestGateway = false; public NicTO getNic() { return nic; @@ -114,4 +115,12 @@ public class SetupGuestNetworkCommand extends NetworkElementCommand { public void setDefaultIp6Dns2(String defaultIp6Dns2) { this.defaultIp6Dns2 = defaultIp6Dns2; } + + public boolean isVrGuestGateway() { + return isVrGuestGateway; + } + + public void setVrGuestGateway(boolean vrGuestGateway) { + isVrGuestGateway = vrGuestGateway; + } } diff --git a/core/src/main/java/com/cloud/agent/api/StartupAnswer.java b/core/src/main/java/com/cloud/agent/api/StartupAnswer.java index 71652269b66..c619ce75ace 100644 --- a/core/src/main/java/com/cloud/agent/api/StartupAnswer.java +++ b/core/src/main/java/com/cloud/agent/api/StartupAnswer.java @@ -21,14 +21,18 @@ package com.cloud.agent.api; public class StartupAnswer extends Answer { long hostId; + String hostName; + String hostUuid; int pingInterval; protected StartupAnswer() { } - public StartupAnswer(StartupCommand cmd, long hostId, int pingInterval) { + public StartupAnswer(StartupCommand cmd, long hostId, String hostUuid, String hostName, int pingInterval) { super(cmd); this.hostId = hostId; + this.hostUuid = hostUuid; + this.hostName = hostName; this.pingInterval = pingInterval; } @@ -40,6 +44,14 @@ public class StartupAnswer extends Answer { return hostId; } + public String getHostUuid() { + return hostUuid; + } + + public String getHostName() { + return hostName; + } + public int getPingInterval() { return pingInterval; } diff --git a/core/src/main/java/com/cloud/agent/api/StartupCommand.java b/core/src/main/java/com/cloud/agent/api/StartupCommand.java index 5f2c00d0be6..cca5e16b585 100644 --- a/core/src/main/java/com/cloud/agent/api/StartupCommand.java +++ b/core/src/main/java/com/cloud/agent/api/StartupCommand.java @@ -47,6 +47,7 @@ public class StartupCommand extends Command { String resourceName; String gatewayIpAddress; String msHostList; + String arch; public StartupCommand(Host.Type type) { this.type = type; @@ -290,6 +291,14 @@ public class StartupCommand extends Command { this.msHostList = msHostList; } + public String getArch() { + return arch; + } + + public void setArch(String arch) { + this.arch = arch; + } + @Override public boolean executeInSequence() { return false; diff --git a/core/src/main/java/com/cloud/agent/api/StartupRoutingCommand.java b/core/src/main/java/com/cloud/agent/api/StartupRoutingCommand.java index b4f9d20df5e..286fced0c58 100644 --- a/core/src/main/java/com/cloud/agent/api/StartupRoutingCommand.java +++ b/core/src/main/java/com/cloud/agent/api/StartupRoutingCommand.java @@ -32,6 +32,7 @@ public class StartupRoutingCommand extends StartupCommand { Integer cpuSockets; int cpus; long speed; + String cpuArch; long memory; long dom0MinMemory; boolean poolSync; @@ -174,6 +175,10 @@ public class StartupRoutingCommand extends StartupCommand { this.hostTags.add(hostTag); } + public void setHostTags(List hostTags) { + this.hostTags = hostTags; + } + public HashMap> getGpuGroupDetails() { return groupDetails; } @@ -197,4 +202,12 @@ public class StartupRoutingCommand extends StartupCommand { public void setHostHealthCheckResult(Boolean hostHealthCheckResult) { this.hostHealthCheckResult = hostHealthCheckResult; } + + public String getCpuArch() { + return cpuArch; + } + + public void setCpuArch(String cpuArch) { + this.cpuArch = cpuArch; + } } diff --git a/core/src/main/java/com/cloud/agent/api/routing/SetBgpPeersAnswer.java b/core/src/main/java/com/cloud/agent/api/routing/SetBgpPeersAnswer.java new file mode 100644 index 00000000000..9645b300db5 --- /dev/null +++ b/core/src/main/java/com/cloud/agent/api/routing/SetBgpPeersAnswer.java @@ -0,0 +1,46 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +// + +package com.cloud.agent.api.routing; + +import java.util.Arrays; + +import com.cloud.agent.api.Answer; + +public class SetBgpPeersAnswer extends Answer { + String[] results; + + protected SetBgpPeersAnswer() { + } + + public SetBgpPeersAnswer(SetBgpPeersCommand cmd, boolean success, String[] results) { + super(cmd, success, null); + if (results != null) { + assert (cmd.getBpgPeers().length == results.length) : "BGP peers and their results should be the same length"; + this.results = Arrays.copyOf(results, results.length); + } + } + + public String[] getResults() { + if (results != null) { + return Arrays.copyOf(results, results.length); + } + return null; + } +} diff --git a/core/src/main/java/com/cloud/agent/api/routing/SetBgpPeersCommand.java b/core/src/main/java/com/cloud/agent/api/routing/SetBgpPeersCommand.java new file mode 100644 index 00000000000..36371a196c8 --- /dev/null +++ b/core/src/main/java/com/cloud/agent/api/routing/SetBgpPeersCommand.java @@ -0,0 +1,39 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +// + +package com.cloud.agent.api.routing; + +import java.util.List; + +import org.apache.cloudstack.network.BgpPeerTO; + +public class SetBgpPeersCommand extends NetworkElementCommand { + BgpPeerTO[] bpgPeers; + + protected SetBgpPeersCommand() { + } + + public SetBgpPeersCommand(List bpgPeers) { + this.bpgPeers = bpgPeers.toArray(new BgpPeerTO[bpgPeers.size()]); + } + + public BgpPeerTO[] getBpgPeers() { + return bpgPeers; + } +} diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/VRScripts.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/VRScripts.java index e435c838b7d..f9ea3e05e97 100644 --- a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/VRScripts.java +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/VRScripts.java @@ -41,6 +41,7 @@ public class VRScripts { public static final String DHCP_CONFIG = "dhcp.json"; public static final String IP_ALIAS_CONFIG = "ip_aliases.json"; public static final String LOAD_BALANCER_CONFIG = "load_balancer.json"; + public static final String BGP_PEERS_CONFIG = "bgp_peers.json"; public static final String SYSTEM_VM_PATCHED = "patched.sh"; public final static String CONFIG_CACHE_LOCATION = "/var/cache/cloud/"; diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java index 3e085fb0971..4afac9b43cb 100644 --- a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java @@ -52,7 +52,8 @@ import org.apache.cloudstack.diagnostics.PrepareFilesCommand; import org.apache.cloudstack.utils.security.KeyStoreUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.net.util.SubnetUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.joda.time.Duration; import com.cloud.agent.api.Answer; @@ -86,7 +87,7 @@ import com.cloud.utils.exception.CloudRuntimeException; **/ public class VirtualRoutingResource { - private static final Logger s_logger = Logger.getLogger(VirtualRoutingResource.class); + protected Logger logger = LogManager.getLogger(getClass()); private VirtualRouterDeployer _vrDeployer; private Map> _vrAggregateCommandsSet; protected Map _vrLockMap = new HashMap(); @@ -118,7 +119,7 @@ public class VirtualRoutingResource { try { ExecutionResult rc = _vrDeployer.prepareCommand(cmd); if (!rc.isSuccess()) { - s_logger.error("Failed to prepare VR command due to " + rc.getDetails()); + logger.error("Failed to prepare VR command due to " + rc.getDetails()); return new Answer(cmd, false, rc.getDetails()); } @@ -169,7 +170,7 @@ public class VirtualRoutingResource { if (!aggregated) { ExecutionResult rc = _vrDeployer.cleanupCommand(cmd); if (!rc.isSuccess()) { - s_logger.error("Failed to cleanup VR command due to " + rc.getDetails()); + logger.error("Failed to cleanup VR command due to " + rc.getDetails()); } } } @@ -225,15 +226,15 @@ public class VirtualRoutingResource { } else if (cmd instanceof GetRouterMonitorResultsCommand) { return execute((GetRouterMonitorResultsCommand)cmd); } else { - s_logger.error("Unknown query command in VirtualRoutingResource!"); + logger.error("Unknown query command in VirtualRoutingResource!"); return Answer.createUnsupportedCommandAnswer(cmd); } } - private static String getRouterSshControlIp(NetworkElementCommand cmd) { + private String getRouterSshControlIp(NetworkElementCommand cmd) { String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - if (s_logger.isDebugEnabled()) - s_logger.debug("Use router's private IP for SSH control. IP : " + routerIp); + if (logger.isDebugEnabled()) + logger.debug("Use router's private IP for SSH control. IP : " + routerIp); return routerIp; } @@ -248,24 +249,24 @@ public class VirtualRoutingResource { String subnet = address.split("/")[1]; ExecutionResult result = _vrDeployer.executeInVR(routerIp, VRScripts.VR_UPDATE_INTERFACE_CONFIG, ipAddressTO.getPublicIp() + " " + subnet + " " + ipAddressTO.getMtu() + " " + 15); - if (s_logger.isDebugEnabled()) - s_logger.debug("result: " + result.isSuccess() + ", output: " + result.getDetails()); + if (logger.isDebugEnabled()) + logger.debug("result: " + result.isSuccess() + ", output: " + result.getDetails()); if (!Boolean.TRUE.equals(result.isSuccess())) { if (result.getDetails().contains(String.format("Interface with IP %s not found", ipAddressTO.getPublicIp()))) { - s_logger.warn(String.format("Skipping IP: %s as it isn't configured on router interface", ipAddressTO.getPublicIp())); + logger.warn(String.format("Skipping IP: %s as it isn't configured on router interface", ipAddressTO.getPublicIp())); } else if (ipAddressTO.getDetails().get(ApiConstants.REDUNDANT_STATE).equals(VirtualRouter.RedundantState.PRIMARY.name())) { - s_logger.warn(String.format("Failed to update interface mtu to %s on interface with ip: %s", + logger.warn(String.format("Failed to update interface mtu to %s on interface with ip: %s", ipAddressTO.getMtu(), ipAddressTO.getPublicIp())); finalResult = false; } continue; } - s_logger.info(String.format("Successfully updated mtu to %s on interface with ip: %s", + logger.info(String.format("Successfully updated mtu to %s on interface with ip: %s", ipAddressTO.getMtu(), ipAddressTO.getPublicIp())); finalResult &= true; } catch (Exception e) { String msg = "Prepare UpdateNetwork failed due to " + e.toString(); - s_logger.error(msg, e); + logger.error(msg, e); return new Answer(cmd, e); } } @@ -315,9 +316,9 @@ public class VirtualRoutingResource { for (ConfigItem configItem : cfg) { long startTimestamp = System.currentTimeMillis(); ExecutionResult result = applyConfigToVR(cmd.getRouterAccessIp(), configItem, VRScripts.VR_SCRIPT_EXEC_TIMEOUT); - if (s_logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { long elapsed = System.currentTimeMillis() - startTimestamp; - s_logger.debug("Processing " + configItem + " took " + elapsed + "ms"); + logger.debug("Processing " + configItem + " took " + elapsed + "ms"); } if (result == null) { result = new ExecutionResult(false, "null execution result"); @@ -329,7 +330,7 @@ public class VirtualRoutingResource { // Not sure why this matters, but log it anyway if (cmd.getAnswersCount() != results.size()) { - s_logger.warn("Expected " + cmd.getAnswersCount() + " answers while executing " + cmd.getClass().getSimpleName() + " but received " + results.size()); + logger.warn("Expected " + cmd.getAnswersCount() + " answers while executing " + cmd.getClass().getSimpleName() + " but received " + results.size()); } if (results.size() == 1) { @@ -378,7 +379,7 @@ public class VirtualRoutingResource { } else if (!readingFailedChecks && readingMonitorResults) { // Reading monitor checks result monitorResults.append(line); } else { - s_logger.error("Unexpected lines reached while parsing health check response. Skipping line:- " + line); + logger.error("Unexpected lines reached while parsing health check response. Skipping line:- " + line); } } @@ -398,16 +399,16 @@ public class VirtualRoutingResource { } String args = cmd.shouldPerformFreshChecks() ? "true" : "false"; - s_logger.info("Fetching health check result for " + routerIp + " and executing fresh checks: " + args); + logger.info("Fetching health check result for " + routerIp + " and executing fresh checks: " + args); ExecutionResult result = _vrDeployer.executeInVR(routerIp, VRScripts.ROUTER_MONITOR_RESULTS, args); if (!result.isSuccess()) { - s_logger.warn("Result of " + cmd + " failed with details: " + result.getDetails()); + logger.warn("Result of " + cmd + " failed with details: " + result.getDetails()); return new GetRouterMonitorResultsAnswer(cmd, false, null, result.getDetails()); } if (result.getDetails().isEmpty()) { - s_logger.warn("Result of " + cmd + " received no details."); + logger.warn("Result of " + cmd + " received no details."); return new GetRouterMonitorResultsAnswer(cmd, false, null, "No results available."); } @@ -417,12 +418,12 @@ public class VirtualRoutingResource { private Pair checkRouterFileSystem(String routerIp) { ExecutionResult fileSystemWritableTestResult = _vrDeployer.executeInVR(routerIp, VRScripts.ROUTER_FILESYSTEM_WRITABLE_CHECK, null); if (fileSystemWritableTestResult.isSuccess()) { - s_logger.debug("Router connectivity and file system writable check passed"); + logger.debug("Router connectivity and file system writable check passed"); return new Pair(true, "success"); } String resultDetails = fileSystemWritableTestResult.getDetails(); - s_logger.warn("File system writable check failed with details: " + resultDetails); + logger.warn("File system writable check failed with details: " + resultDetails); if (StringUtils.isNotBlank(resultDetails)) { final String readOnlyFileSystemError = "Read-only file system"; if (resultDetails.contains(readOnlyFileSystemError)) { @@ -507,8 +508,8 @@ public class VirtualRoutingResource { if (params.get("router.aggregation.command.each.timeout") != null) { String value = (String)params.get("router.aggregation.command.each.timeout"); _eachTimeout = Duration.standardSeconds(NumbersUtil.parseLong(value, 600)); - if (s_logger.isDebugEnabled()){ - s_logger.debug("The router.aggregation.command.each.timeout in seconds is set to " + _eachTimeout.getStandardSeconds()); + if (logger.isDebugEnabled()){ + logger.debug("The router.aggregation.command.each.timeout in seconds is set to " + _eachTimeout.getStandardSeconds()); } } @@ -529,8 +530,8 @@ public class VirtualRoutingResource { value = (String)params.get("router.aggregation.command.each.timeout"); _eachTimeout = Duration.standardSeconds(NumbersUtil.parseInt(value, (int)VRScripts.VR_SCRIPT_EXEC_TIMEOUT.getStandardSeconds())); - if (s_logger.isDebugEnabled()){ - s_logger.debug("The router.aggregation.command.each.timeout in seconds is set to " + _eachTimeout.getStandardSeconds()); + if (logger.isDebugEnabled()){ + logger.debug("The router.aggregation.command.each.timeout in seconds is set to " + _eachTimeout.getStandardSeconds()); } if (_vrDeployer == null) { @@ -553,8 +554,8 @@ public class VirtualRoutingResource { for (int i = 0; i <= retry; i++) { SocketChannel sch = null; try { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Trying to connect to " + ipAddress); + if (logger.isDebugEnabled()) { + logger.debug("Trying to connect to " + ipAddress); } sch = SocketChannel.open(); sch.configureBlocking(true); @@ -563,8 +564,8 @@ public class VirtualRoutingResource { sch.connect(addr); return true; } catch (final IOException e) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Could not connect to " + ipAddress); + if (logger.isDebugEnabled()) { + logger.debug("Could not connect to " + ipAddress); } } finally { if (sch != null) { @@ -580,7 +581,7 @@ public class VirtualRoutingResource { } } - s_logger.debug("Unable to logon to " + ipAddress); + logger.debug("Unable to logon to " + ipAddress); return false; } @@ -590,7 +591,7 @@ public class VirtualRoutingResource { * [TODO] Still have to migrate LoadBalancerConfigCommand and BumpUpPriorityCommand * [FIXME] Have a look at SetSourceNatConfigItem */ - s_logger.debug("Transforming " + cmd.getClass().getCanonicalName() + " to ConfigItems"); + logger.debug("Transforming " + cmd.getClass().getCanonicalName() + " to ConfigItems"); final AbstractConfigItemFacade configItemFacade = AbstractConfigItemFacade.getInstance(cmd.getClass()); @@ -620,7 +621,7 @@ public class VirtualRoutingResource { answerCounts += command.getAnswersCount(); List cfg = generateCommandCfg(command); if (cfg == null) { - s_logger.warn("Unknown commands for VirtualRoutingResource, but continue: " + cmd.toString()); + logger.warn("Unknown commands for VirtualRoutingResource, but continue: " + cmd.toString()); continue; } @@ -635,8 +636,8 @@ public class VirtualRoutingResource { ScriptConfigItem scriptConfigItem = new ScriptConfigItem(VRScripts.VR_CFG, "-c " + VRScripts.CONFIG_CACHE_LOCATION + cfgFileName); // 120s is the minimal timeout Duration timeout = _eachTimeout.withDurationAdded(_eachTimeout.getStandardSeconds(), answerCounts); - if (s_logger.isDebugEnabled()){ - s_logger.debug("Aggregate action timeout in seconds is " + timeout.getStandardSeconds()); + if (logger.isDebugEnabled()){ + logger.debug("Aggregate action timeout in seconds is " + timeout.getStandardSeconds()); } ExecutionResult result = applyConfigToVR(cmd.getRouterAccessIp(), fileConfigItem, timeout); diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/AbstractConfigItemFacade.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/AbstractConfigItemFacade.java index bed472b6880..83dfa2a62ca 100644 --- a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/AbstractConfigItemFacade.java +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/AbstractConfigItemFacade.java @@ -24,7 +24,6 @@ import java.util.LinkedList; import java.util.List; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.agent.api.BumpUpPriorityCommand; import com.cloud.agent.api.SetupGuestNetworkCommand; @@ -38,6 +37,7 @@ import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; import com.cloud.agent.api.routing.SavePasswordCommand; +import com.cloud.agent.api.routing.SetBgpPeersCommand; import com.cloud.agent.api.routing.SetFirewallRulesCommand; import com.cloud.agent.api.routing.SetIpv6FirewallRulesCommand; import com.cloud.agent.api.routing.SetMonitorServiceCommand; @@ -59,10 +59,12 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; public abstract class AbstractConfigItemFacade { - private static final Logger s_logger = Logger.getLogger(AbstractConfigItemFacade.class); + protected Logger logger = LogManager.getLogger(getClass()); private final static Gson gson; @@ -97,6 +99,7 @@ public abstract class AbstractConfigItemFacade { flyweight.put(SetSourceNatCommand.class, new SetSourceNatConfigItem()); flyweight.put(IpAssocCommand.class, new IpAssociationConfigItem()); flyweight.put(IpAssocVpcCommand.class, new IpAssociationConfigItem()); + flyweight.put(SetBgpPeersCommand.class, new SetBgpPeersConfigItem()); } protected String destinationFile; @@ -123,8 +126,8 @@ public abstract class AbstractConfigItemFacade { final List cfg = new LinkedList<>(); final String remoteFilename = appendUuidToJsonFiles(destinationFile); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Transformed filename: " + destinationFile + " to: " + remoteFilename); + if (logger.isDebugEnabled()) { + logger.debug("Transformed filename: " + destinationFile + " to: " + remoteFilename); } final ConfigItem configFile = new FileConfigItem(VRScripts.CONFIG_PERSIST_LOCATION, remoteFilename, gson.toJson(configuration)); diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersConfigItem.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersConfigItem.java new file mode 100644 index 00000000000..68f4275bb6b --- /dev/null +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersConfigItem.java @@ -0,0 +1,46 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +// + +package com.cloud.agent.resource.virtualnetwork.facade; + +import java.util.Arrays; +import java.util.List; + +import com.cloud.agent.api.routing.NetworkElementCommand; +import com.cloud.agent.api.routing.SetBgpPeersCommand; +import com.cloud.agent.resource.virtualnetwork.ConfigItem; +import com.cloud.agent.resource.virtualnetwork.VRScripts; +import com.cloud.agent.resource.virtualnetwork.model.BgpPeers; +import com.cloud.agent.resource.virtualnetwork.model.ConfigBase; + +public class SetBgpPeersConfigItem extends AbstractConfigItemFacade { + + @Override + public List generateConfig(final NetworkElementCommand cmd) { + final SetBgpPeersCommand command = (SetBgpPeersCommand) cmd; + return generateConfigItems(new BgpPeers(Arrays.asList(command.getBpgPeers()))); + } + + @Override + protected List generateConfigItems(final ConfigBase configuration) { + destinationFile = VRScripts.BGP_PEERS_CONFIG; + + return super.generateConfigItems(configuration); + } +} diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetGuestNetworkConfigItem.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetGuestNetworkConfigItem.java index aee1e779571..1a6824ceb7f 100644 --- a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetGuestNetworkConfigItem.java +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetGuestNetworkConfigItem.java @@ -75,6 +75,7 @@ public class SetGuestNetworkConfigItem extends AbstractConfigItemFacade { guestNetwork.setRouterIp6(command.getRouterIpv6()); guestNetwork.setRouterIp6Gateway(command.getRouterIpv6Gateway()); guestNetwork.setRouterIp6Cidr(command.getRouterIpv6Cidr()); + guestNetwork.setVrGuestGateway(command.isVrGuestGateway()); return generateConfigItems(guestNetwork); } diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetMonitorServiceConfigItem.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetMonitorServiceConfigItem.java index 52d8442b5ac..227675ebf4e 100644 --- a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetMonitorServiceConfigItem.java +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetMonitorServiceConfigItem.java @@ -21,7 +21,6 @@ package com.cloud.agent.resource.virtualnetwork.facade; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.SetMonitorServiceCommand; @@ -32,7 +31,6 @@ import com.cloud.agent.resource.virtualnetwork.model.ConfigBase; import com.cloud.agent.resource.virtualnetwork.model.MonitorService; public class SetMonitorServiceConfigItem extends AbstractConfigItemFacade { - private static final Logger s_logger = Logger.getLogger(SetMonitorServiceConfigItem.class); @Override public List generateConfig(final NetworkElementCommand cmd) { @@ -58,14 +56,14 @@ public class SetMonitorServiceConfigItem extends AbstractConfigItemFacade { try { monitorService.setHealthChecksBasicRunInterval(Integer.parseInt(command.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_BASIC_INTERVAL))); } catch (NumberFormatException exception) { - s_logger.error("Unexpected health check basic interval set" + command.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_BASIC_INTERVAL) + + logger.error("Unexpected health check basic interval set" + command.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_BASIC_INTERVAL) + ". Exception: " + exception + "Will use default value"); } try { monitorService.setHealthChecksAdvancedRunInterval(Integer.parseInt(command.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_ADVANCED_INTERVAL))); } catch (NumberFormatException exception) { - s_logger.error("Unexpected health check advanced interval set" + command.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_ADVANCED_INTERVAL) + + logger.error("Unexpected health check advanced interval set" + command.getAccessDetail(SetMonitorServiceCommand.ROUTER_HEALTH_CHECKS_ADVANCED_INTERVAL) + ". Exception: " + exception + "Will use default value"); } diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetNetworkAclConfigItem.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetNetworkAclConfigItem.java index a64328d516a..f4c3275aa2b 100644 --- a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetNetworkAclConfigItem.java +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetNetworkAclConfigItem.java @@ -22,7 +22,6 @@ package com.cloud.agent.resource.virtualnetwork.facade; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.SetNetworkACLCommand; @@ -41,7 +40,6 @@ import com.cloud.utils.net.NetUtils; public class SetNetworkAclConfigItem extends AbstractConfigItemFacade { - public static final Logger s_logger = Logger.getLogger(SetNetworkAclConfigItem.class.getName()); @Override public List generateConfig(final NetworkElementCommand cmd) { @@ -81,7 +79,7 @@ public class SetNetworkAclConfigItem extends AbstractConfigItemFacade { try { aclRule = new ProtocolAclRule(ruleParts[4], "ACCEPT".equals(ruleParts[5]), Integer.parseInt(ruleParts[1])); } catch (final Exception e) { - s_logger.warn("Problem occurred when reading the entries in the ruleParts array. Actual array size is '" + ruleParts.length + "', but trying to read from index 5."); + logger.warn("Problem occurred when reading the entries in the ruleParts array. Actual array size is '" + ruleParts.length + "', but trying to read from index 5."); continue; } } diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/BgpPeers.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/BgpPeers.java new file mode 100644 index 00000000000..54a1ab2e091 --- /dev/null +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/BgpPeers.java @@ -0,0 +1,45 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +// + +package com.cloud.agent.resource.virtualnetwork.model; + +import org.apache.cloudstack.network.BgpPeerTO; + +import java.util.List; + +public class BgpPeers extends ConfigBase { + private List peers; + + public BgpPeers() { + super(ConfigBase.BGP_PEERS); + } + + public BgpPeers(List bgpPeers) { + super(ConfigBase.BGP_PEERS); + this.peers = bgpPeers; + } + + public List getPeers() { + return peers; + } + + public void setPeers(List bgpPeers) { + this.peers = bgpPeers; + } +} diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/ConfigBase.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/ConfigBase.java index ade80d71384..e370b764f22 100644 --- a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/ConfigBase.java +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/ConfigBase.java @@ -39,6 +39,7 @@ public abstract class ConfigBase { public static final String MONITORSERVICE = "monitorservice"; public static final String DHCP_CONFIG = "dhcpconfig"; public static final String LOAD_BALANCER = "loadbalancer"; + public final static String BGP_PEERS = "bgppeers"; private String type = UNKNOWN; diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/GuestNetwork.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/GuestNetwork.java index bb5e443c2e8..a416b4bc5e4 100644 --- a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/GuestNetwork.java +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/GuestNetwork.java @@ -37,6 +37,7 @@ public class GuestNetwork extends ConfigBase { private String routerIp6; private String routerIp6Gateway; private String routerIp6Cidr; + private boolean isVrGuestGateway; private Integer mtu; @@ -202,4 +203,12 @@ public class GuestNetwork extends ConfigBase { public Integer getMtu() { return mtu; } + + public boolean isVrGuestGateway() { + return isVrGuestGateway; + } + + public void setVrGuestGateway(boolean vrGuestGateway) { + isVrGuestGateway = vrGuestGateway; + } } diff --git a/core/src/main/java/com/cloud/agent/transport/LoggingExclusionStrategy.java b/core/src/main/java/com/cloud/agent/transport/LoggingExclusionStrategy.java index 90e964e7139..2301c1fc205 100644 --- a/core/src/main/java/com/cloud/agent/transport/LoggingExclusionStrategy.java +++ b/core/src/main/java/com/cloud/agent/transport/LoggingExclusionStrategy.java @@ -19,7 +19,8 @@ package com.cloud.agent.transport; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; @@ -29,7 +30,9 @@ import com.cloud.agent.api.LogLevel; import com.cloud.agent.api.LogLevel.Log4jLevel; public class LoggingExclusionStrategy implements ExclusionStrategy { - Logger _logger = null; + protected Logger exclusionLogger = null; + + protected Logger logger = LogManager.getLogger(getClass()); @Override public boolean shouldSkipClass(Class clazz) { @@ -40,20 +43,24 @@ public class LoggingExclusionStrategy implements ExclusionStrategy { LogLevel level = clazz.getAnnotation(LogLevel.class); if (level == null) { log4jLevel = LogLevel.Log4jLevel.Debug; + logger.trace("Class {} does not have any log level annotation, considering level as debug.", clazz); } else { log4jLevel = level.value(); } - return !log4jLevel.enabled(_logger); + return !log4jLevel.enabled(exclusionLogger); } @Override public boolean shouldSkipField(FieldAttributes field) { LogLevel level = field.getAnnotation(LogLevel.class); - return level != null && !level.value().enabled(_logger); + return level != null && !level.value().enabled(exclusionLogger); } public LoggingExclusionStrategy(Logger logger) { - _logger = logger; + exclusionLogger = logger; + } + + public LoggingExclusionStrategy() { } } diff --git a/core/src/main/java/com/cloud/agent/transport/Request.java b/core/src/main/java/com/cloud/agent/transport/Request.java index 241ccd4bbd8..3769dbbd612 100644 --- a/core/src/main/java/com/cloud/agent/transport/Request.java +++ b/core/src/main/java/com/cloud/agent/transport/Request.java @@ -33,8 +33,9 @@ import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Level; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.BadCommand; @@ -75,7 +76,7 @@ import com.google.gson.stream.JsonReader; * */ public class Request { - private static final Logger s_logger = Logger.getLogger(Request.class); + protected static Logger LOGGER = LogManager.getLogger(Request.class); protected static final Gson s_gson = GsonHelper.getGson(); protected static final Gson s_gogger = GsonHelper.getGsonLogger(); @@ -251,10 +252,10 @@ public class Request { jsonReader.setLenient(true); _cmds = s_gson.fromJson(jsonReader, (Type)Command[].class); } catch (JsonParseException e) { - s_logger.error("Caught problem while parsing JSON command " + _content, e); + LOGGER.error("Caught problem while parsing JSON command " + _content, e); _cmds = new Command[] { new BadCommand() }; } catch (RuntimeException e) { - s_logger.error("Caught problem with " + _content, e); + LOGGER.error("Caught problem with " + _content, e); throw e; } } @@ -300,7 +301,7 @@ public class Request { } in.close(); } catch (IOException e) { - s_logger.error("Fail to decompress the request!", e); + LOGGER.error("Fail to decompress the request!", e); } retBuff.flip(); return retBuff; @@ -321,7 +322,7 @@ public class Request { out.finish(); out.close(); } catch (IOException e) { - s_logger.error("Fail to compress the request!", e); + LOGGER.error("Fail to compress the request!", e); } return ByteBuffer.wrap(byteOut.toByteArray()); } @@ -369,24 +370,24 @@ public class Request { } public void logD(String msg, boolean logContent) { - if (s_logger.isDebugEnabled()) { + if (LOGGER.isDebugEnabled()) { String log = log(msg, logContent, Level.DEBUG); if (log != null) { - s_logger.debug(log); + LOGGER.debug(log); } } } public void logT(String msg, boolean logD) { - if (s_logger.isTraceEnabled()) { + if (LOGGER.isTraceEnabled()) { String log = log(msg, true, Level.TRACE); if (log != null) { - s_logger.trace(log); + LOGGER.trace(log); } - } else if (logD && s_logger.isDebugEnabled()) { + } else if (logD && LOGGER.isDebugEnabled()) { String log = log(msg, false, Level.DEBUG); if (log != null) { - s_logger.debug(log); + LOGGER.debug(log); } } } @@ -403,7 +404,7 @@ public class Request { try { _cmds = s_gson.fromJson(_content, this instanceof Response ? Answer[].class : Command[].class); } catch (RuntimeException e) { - s_logger.error("Unable to deserialize from json: " + _content); + LOGGER.error("Unable to deserialize from json: " + _content); throw e; } } @@ -414,7 +415,7 @@ public class Request { for (Command cmd : _cmds) { buff.append(cmd.getClass().getSimpleName()).append("/"); } - s_logger.error("Gson serialization error " + buff.toString(), e); + LOGGER.error("Gson serialization error " + buff.toString(), e); assert false : "More gson errors on " + buff.toString(); return ""; } diff --git a/core/src/main/java/com/cloud/agent/transport/StoragePoolTypeAdaptor.java b/core/src/main/java/com/cloud/agent/transport/StoragePoolTypeAdaptor.java new file mode 100644 index 00000000000..635f6d06cf5 --- /dev/null +++ b/core/src/main/java/com/cloud/agent/transport/StoragePoolTypeAdaptor.java @@ -0,0 +1,53 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.agent.transport; + +import com.cloud.storage.Storage.StoragePoolType; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; + +/** + * {@link StoragePoolType} acts as extendable set of singleton objects and should return same result when used "==" + * or {@link Object#equals(Object)}. + * To support that, need to return existing object for a given name instead of creating new. + */ +public class StoragePoolTypeAdaptor implements JsonDeserializer, JsonSerializer { + @Override + public StoragePoolType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + if (json instanceof JsonPrimitive && ((JsonPrimitive) json).isString()) { + return StoragePoolType.valueOf(json.getAsString()); + } + return null; + } + + @Override + public JsonElement serialize(StoragePoolType src, Type typeOfSrc, JsonSerializationContext context) { + String name = src.name(); + if (name == null) { + return new JsonNull(); + } + return new JsonPrimitive(name); + } +} diff --git a/core/src/main/java/com/cloud/network/HAProxyConfigurator.java b/core/src/main/java/com/cloud/network/HAProxyConfigurator.java index 9d8301f291f..e4b0a7ffff4 100644 --- a/core/src/main/java/com/cloud/network/HAProxyConfigurator.java +++ b/core/src/main/java/com/cloud/network/HAProxyConfigurator.java @@ -28,7 +28,8 @@ import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.to.LoadBalancerTO; @@ -41,7 +42,7 @@ import com.cloud.utils.net.NetUtils; public class HAProxyConfigurator implements LoadBalancerConfigurator { - private static final Logger s_logger = Logger.getLogger(HAProxyConfigurator.class); + protected Logger logger = LogManager.getLogger(getClass()); private static final String blankLine = "\t "; private static String[] globalSection = {"global", "\tlog 127.0.0.1:3914 local0 warning", "\tmaxconn 4096", "\tmaxpipes 1024", "\tchroot /var/lib/haproxy", "\tuser haproxy", "\tgroup haproxy", "\tstats socket /run/haproxy/admin.sock", "\tdaemon"}; @@ -458,7 +459,7 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator { * Not supposed to reach here, validation of methods are * done at the higher layer */ - s_logger.warn("Haproxy stickiness policy for lb rule: " + lbTO.getSrcIp() + ":" + lbTO.getSrcPort() + ": Not Applied, cause:invalid method "); + logger.warn("Haproxy stickiness policy for lb rule: " + lbTO.getSrcIp() + ":" + lbTO.getSrcPort() + ": Not Applied, cause:invalid method "); return null; } } @@ -541,7 +542,7 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator { result.addAll(dstSubRule); } if (stickinessSubRule != null && !destsAvailable) { - s_logger.warn("Haproxy stickiness policy for lb rule: " + lbTO.getSrcIp() + ":" + lbTO.getSrcPort() + ": Not Applied, cause: backends are unavailable"); + logger.warn("Haproxy stickiness policy for lb rule: " + lbTO.getSrcIp() + ":" + lbTO.getSrcPort() + ": Not Applied, cause: backends are unavailable"); } if (publicPort == NetUtils.HTTP_PORT && !keepAliveEnabled || httpbasedStickiness) { sb = new StringBuilder(); @@ -566,7 +567,7 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator { final StringBuilder rule = new StringBuilder("\nlisten ").append(ruleName).append("\n\tbind ").append(statsIp).append(":").append(lbCmd.lbStatsPort); // TODO DH: write test for this in both cases if (!lbCmd.keepAliveEnabled) { - s_logger.info("Haproxy mode http enabled"); + logger.info("Haproxy mode http enabled"); rule.append("\n\tmode http\n\toption httpclose"); } rule.append("\n\tstats enable\n\tstats uri ") @@ -575,8 +576,8 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator { .append(lbCmd.lbStatsAuth); rule.append("\n"); final String result = rule.toString(); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Haproxystats rule: " + result); + if (logger.isDebugEnabled()) { + logger.debug("Haproxystats rule: " + result); } return result; } @@ -590,9 +591,9 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator { // TODO DH: write test for this function final String pipesLine = "\tmaxpipes " + Long.toString(Long.parseLong(lbCmd.maxconn) / 4); gSection.set(3, pipesLine); - if (s_logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { for (final String s : gSection) { - s_logger.debug("global section: " + s); + logger.debug("global section: " + s); } } result.addAll(gSection); @@ -606,9 +607,9 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator { dSection.set(7, "\tno option httpclose"); } - if (s_logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { for (final String s : dSection) { - s_logger.debug("default section: " + s); + logger.debug("default section: " + s); } } result.addAll(dSection); diff --git a/core/src/main/java/com/cloud/network/resource/TrafficSentinelResource.java b/core/src/main/java/com/cloud/network/resource/TrafficSentinelResource.java index c6596b3c630..43fb459978a 100644 --- a/core/src/main/java/com/cloud/network/resource/TrafficSentinelResource.java +++ b/core/src/main/java/com/cloud/network/resource/TrafficSentinelResource.java @@ -35,7 +35,8 @@ import java.util.StringTokenizer; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; @@ -66,7 +67,7 @@ public class TrafficSentinelResource implements ServerResource { private String _inclZones; private String _exclZones; - private static final Logger s_logger = Logger.getLogger(TrafficSentinelResource.class); + protected Logger logger = LogManager.getLogger(getClass()); @Override public boolean configure(String name, Map params) throws ConfigurationException { @@ -242,10 +243,10 @@ public class TrafficSentinelResource implements ServerResource { } } } catch (MalformedURLException e1) { - s_logger.info("Invalid Traffic Sentinel URL", e1); + logger.info("Invalid Traffic Sentinel URL", e1); throw new ExecutionException(e1.getMessage()); } catch (IOException e) { - s_logger.debug("Error in direct network usage accounting", e); + logger.debug("Error in direct network usage accounting", e); throw new ExecutionException(e.getMessage()); } finally { if (os != null) { @@ -256,7 +257,7 @@ public class TrafficSentinelResource implements ServerResource { } } } catch (Exception e) { - s_logger.debug(e); + logger.debug(e); throw new ExecutionException(e.getMessage()); } return answer; diff --git a/core/src/main/java/com/cloud/resource/CommandWrapper.java b/core/src/main/java/com/cloud/resource/CommandWrapper.java index ee6aa161e33..72d1348dfe7 100644 --- a/core/src/main/java/com/cloud/resource/CommandWrapper.java +++ b/core/src/main/java/com/cloud/resource/CommandWrapper.java @@ -19,7 +19,8 @@ package com.cloud.resource; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; @@ -27,7 +28,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; public abstract class CommandWrapper { - protected Logger logger = Logger.getLogger(getClass()); + protected Logger logger = LogManager.getLogger(getClass()); /** * @param T is the command to be used. diff --git a/core/src/main/java/com/cloud/resource/RequestWrapper.java b/core/src/main/java/com/cloud/resource/RequestWrapper.java index e43cf02e13c..54d8b289c8d 100644 --- a/core/src/main/java/com/cloud/resource/RequestWrapper.java +++ b/core/src/main/java/com/cloud/resource/RequestWrapper.java @@ -23,7 +23,8 @@ import java.text.MessageFormat; import java.util.Hashtable; import java.util.Set; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; @@ -39,7 +40,7 @@ public abstract class RequestWrapper { } } - private static final Logger s_logger = Logger.getLogger(RequestWrapper.class); + protected Logger logger = LogManager.getLogger(RequestWrapper.class); @SuppressWarnings("rawtypes") protected Hashtable, Hashtable, CommandWrapper>> resources = new Hashtable, Hashtable, CommandWrapper>>(); @@ -141,9 +142,9 @@ public abstract class RequestWrapper { try { commands.put(annotation.handles(), wrapper.newInstance()); } catch (final InstantiationException e) { - s_logger.warn(MessageFormat.format(errorMessage, e.getLocalizedMessage(), wrapper.toString())); + logger.warn(MessageFormat.format(errorMessage, e.getLocalizedMessage(), wrapper.toString())); } catch (final IllegalAccessException e) { - s_logger.warn(MessageFormat.format(errorMessage, e.getLocalizedMessage(), wrapper.toString())); + logger.warn(MessageFormat.format(errorMessage, e.getLocalizedMessage(), wrapper.toString())); } } diff --git a/core/src/main/java/com/cloud/resource/ServerResource.java b/core/src/main/java/com/cloud/resource/ServerResource.java index 1602a78d9a4..092019e7f21 100644 --- a/core/src/main/java/com/cloud/resource/ServerResource.java +++ b/core/src/main/java/com/cloud/resource/ServerResource.java @@ -78,4 +78,12 @@ public interface ServerResource extends Manager { void setAgentControl(IAgentControl agentControl); + default boolean isExitOnFailures() { + return true; + } + + default boolean isAppendAgentNameToLogs() { + return false; + } + } diff --git a/core/src/main/java/com/cloud/resource/ServerResourceBase.java b/core/src/main/java/com/cloud/resource/ServerResourceBase.java index 18121e21e51..bb44b307047 100644 --- a/core/src/main/java/com/cloud/resource/ServerResourceBase.java +++ b/core/src/main/java/com/cloud/resource/ServerResourceBase.java @@ -37,7 +37,8 @@ import javax.naming.ConfigurationException; import org.apache.cloudstack.storage.command.browser.ListDataStoreObjectsAnswer; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; @@ -47,7 +48,7 @@ import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.Script; public abstract class ServerResourceBase implements ServerResource { - private static final Logger s_logger = Logger.getLogger(ServerResourceBase.class); + protected Logger logger = LogManager.getLogger(getClass()); protected String name; private ArrayList warnings = new ArrayList(); private ArrayList errors = new ArrayList(); @@ -80,7 +81,7 @@ public abstract class ServerResourceBase implements ServerResource { String infos[] = NetUtils.getNetworkParams(privateNic); if (infos == null) { - s_logger.warn("Incorrect details for private Nic during initialization of ServerResourceBase"); + logger.warn("Incorrect details for private Nic during initialization of ServerResourceBase"); return false; } params.put("host.ip", infos[0]); @@ -106,7 +107,7 @@ public abstract class ServerResourceBase implements ServerResource { } protected void tryToAutoDiscoverResourcePrivateNetworkInterface() throws ConfigurationException { - s_logger.info("Trying to autodiscover this resource's private network interface."); + logger.info("Trying to autodiscover this resource's private network interface."); List nics; try { @@ -118,11 +119,11 @@ public abstract class ServerResourceBase implements ServerResource { throw new ConfigurationException(String.format("Could not retrieve the environment NICs due to [%s].", e.getMessage())); } - s_logger.debug(String.format("Searching the private NIC along the environment NICs [%s].", Arrays.toString(nics.toArray()))); + logger.debug(String.format("Searching the private NIC along the environment NICs [%s].", Arrays.toString(nics.toArray()))); for (NetworkInterface nic : nics) { if (isValidNicToUseAsPrivateNic(nic)) { - s_logger.info(String.format("Using NIC [%s] as private NIC.", nic)); + logger.info(String.format("Using NIC [%s] as private NIC.", nic)); privateNic = nic; return; } @@ -134,18 +135,18 @@ public abstract class ServerResourceBase implements ServerResource { protected boolean isValidNicToUseAsPrivateNic(NetworkInterface nic) { String nicName = nic.getName(); - s_logger.debug(String.format("Verifying if NIC [%s] can be used as private NIC.", nic)); + logger.debug(String.format("Verifying if NIC [%s] can be used as private NIC.", nic)); String[] nicNameStartsToAvoid = {"vnif", "vnbr", "peth", "vif", "virbr"}; if (nic.isVirtual() || StringUtils.startsWithAny(nicName, nicNameStartsToAvoid) || nicName.contains(":")) { - s_logger.debug(String.format("Not using NIC [%s] because it is either virtual, starts with %s, or contains \":\"" + + logger.debug(String.format("Not using NIC [%s] because it is either virtual, starts with %s, or contains \":\"" + " in its name.", Arrays.toString(nicNameStartsToAvoid), nic)); return false; } String[] info = NetUtils.getNicParams(nicName); if (info == null || info[0] == null) { - s_logger.debug(String.format("Not using NIC [%s] because it does not have a valid IP to use as the private IP.", nic)); + logger.debug(String.format("Not using NIC [%s] because it does not have a valid IP to use as the private IP.", nic)); return false; } @@ -190,8 +191,8 @@ public abstract class ServerResourceBase implements ServerResource { if (privateNic != null) { info = NetUtils.getNetworkParams(privateNic); if (info != null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Parameters for private nic: " + info[0] + " - " + info[1] + "-" + info[2]); + if (logger.isDebugEnabled()) { + logger.debug("Parameters for private nic: " + info[0] + " - " + info[1] + "-" + info[2]); } cmd.setPrivateIpAddress(info[0]); cmd.setPrivateMacAddress(info[1]); @@ -200,16 +201,16 @@ public abstract class ServerResourceBase implements ServerResource { } if (storageNic != null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Storage has its now nic: " + storageNic.getName()); + if (logger.isDebugEnabled()) { + logger.debug("Storage has its now nic: " + storageNic.getName()); } info = NetUtils.getNetworkParams(storageNic); } // NOTE: In case you're wondering, this is not here by mistake. if (info != null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Parameters for storage nic: " + info[0] + " - " + info[1] + "-" + info[2]); + if (logger.isDebugEnabled()) { + logger.debug("Parameters for storage nic: " + info[0] + " - " + info[1] + "-" + info[2]); } cmd.setStorageIpAddress(info[0]); cmd.setStorageMacAddress(info[1]); @@ -219,8 +220,8 @@ public abstract class ServerResourceBase implements ServerResource { if (publicNic != null) { info = NetUtils.getNetworkParams(publicNic); if (info != null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Parameters for public nic: " + info[0] + " - " + info[1] + "-" + info[2]); + if (logger.isDebugEnabled()) { + logger.debug("Parameters for public nic: " + info[0] + " - " + info[1] + "-" + info[2]); } cmd.setPublicIpAddress(info[0]); cmd.setPublicMacAddress(info[1]); @@ -231,8 +232,8 @@ public abstract class ServerResourceBase implements ServerResource { if (storageNic2 != null) { info = NetUtils.getNetworkParams(storageNic2); if (info != null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Parameters for storage nic 2: " + info[0] + " - " + info[1] + "-" + info[2]); + if (logger.isDebugEnabled()) { + logger.debug("Parameters for storage nic 2: " + info[0] + " - " + info[1] + "-" + info[2]); } cmd.setStorageIpAddressDeux(info[0]); cmd.setStorageMacAddressDeux(info[1]); diff --git a/core/src/main/java/com/cloud/serializer/GsonHelper.java b/core/src/main/java/com/cloud/serializer/GsonHelper.java index 7c33ef0e5d5..2d2cecf2618 100644 --- a/core/src/main/java/com/cloud/serializer/GsonHelper.java +++ b/core/src/main/java/com/cloud/serializer/GsonHelper.java @@ -21,7 +21,10 @@ package com.cloud.serializer; import java.util.List; -import org.apache.log4j.Logger; +import com.cloud.hypervisor.Hypervisor; +import org.apache.cloudstack.transport.HypervisorTypeAdaptor; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -37,10 +40,12 @@ import com.cloud.agent.transport.InterfaceTypeAdaptor; import com.cloud.agent.transport.LoggingExclusionStrategy; import com.cloud.agent.transport.Request.NwGroupsCommandTypeAdaptor; import com.cloud.agent.transport.Request.PortConfigListTypeAdaptor; +import com.cloud.agent.transport.StoragePoolTypeAdaptor; +import com.cloud.storage.Storage; import com.cloud.utils.Pair; public class GsonHelper { - private static final Logger s_logger = Logger.getLogger(GsonHelper.class); + protected static Logger LOGGER = LogManager.getLogger(GsonHelper.class); protected static final Gson s_gson; protected static final Gson s_gogger; @@ -48,13 +53,13 @@ public class GsonHelper { static { GsonBuilder gsonBuilder = new GsonBuilder(); s_gson = setDefaultGsonConfig(gsonBuilder); - GsonBuilder loggerBuilder = new GsonBuilder(); - loggerBuilder.disableHtmlEscaping(); - loggerBuilder.setExclusionStrategies(new LoggingExclusionStrategy(s_logger)); - loggerBuilder.serializeSpecialFloatingPointValues(); - // maybe add loggerBuilder.serializeNulls(); as well? - s_gogger = setDefaultGsonConfig(loggerBuilder); - s_logger.info("Default Builder inited."); + GsonBuilder LOGGERBuilder = new GsonBuilder(); + LOGGERBuilder.disableHtmlEscaping(); + LOGGERBuilder.setExclusionStrategies(new LoggingExclusionStrategy(LOGGER)); + LOGGERBuilder.serializeSpecialFloatingPointValues(); + // maybe add LOGGERBuilder.serializeNulls(); as well? + s_gogger = setDefaultGsonConfig(LOGGERBuilder); + LOGGER.info("Default Builder inited."); } static Gson setDefaultGsonConfig(GsonBuilder builder) { @@ -71,6 +76,8 @@ public class GsonHelper { }.getType(), new PortConfigListTypeAdaptor()); builder.registerTypeAdapter(new TypeToken>() { }.getType(), new NwGroupsCommandTypeAdaptor()); + builder.registerTypeAdapter(Storage.StoragePoolType.class, new StoragePoolTypeAdaptor()); + builder.registerTypeAdapter(Hypervisor.HypervisorType.class, new HypervisorTypeAdaptor()); Gson gson = builder.create(); dsAdaptor.initGson(gson); dtAdaptor.initGson(gson); @@ -88,6 +95,6 @@ public class GsonHelper { } public final static Logger getLogger() { - return s_logger; + return LOGGER; } } diff --git a/core/src/main/java/com/cloud/storage/JavaStorageLayer.java b/core/src/main/java/com/cloud/storage/JavaStorageLayer.java index d4c2639d478..0e51ef7eb20 100644 --- a/core/src/main/java/com/cloud/storage/JavaStorageLayer.java +++ b/core/src/main/java/com/cloud/storage/JavaStorageLayer.java @@ -34,10 +34,11 @@ import java.util.Set; import java.util.UUID; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; public class JavaStorageLayer implements StorageLayer { - private static final Logger s_logger = Logger.getLogger(JavaStorageLayer.class); + protected Logger logger = LogManager.getLogger(getClass()); private static final String STD_TMP_DIR_PATH = "/tmp"; String _name; boolean _makeWorldWriteable = true; @@ -198,9 +199,9 @@ public class JavaStorageLayer implements StorageLayer { if (dir.exists()) { if (isWorldReadable(dir)) { if (STD_TMP_DIR_PATH.equals(dir.getAbsolutePath())) { - s_logger.warn(String.format("The temp dir is %s", STD_TMP_DIR_PATH)); + logger.warn(String.format("The temp dir is %s", STD_TMP_DIR_PATH)); } else { - s_logger.warn("The temp dir " + dir.getAbsolutePath() + " is World Readable"); + logger.warn("The temp dir " + dir.getAbsolutePath() + " is World Readable"); } } String uniqDirName = dir.getAbsolutePath() + File.separator + UUID.randomUUID().toString(); diff --git a/core/src/main/java/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java b/core/src/main/java/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java index 75d5f49d4c6..7d8225462ca 100644 --- a/core/src/main/java/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java +++ b/core/src/main/java/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java @@ -35,7 +35,6 @@ import org.apache.cloudstack.storage.command.SnapshotAndCopyCommand; import org.apache.cloudstack.storage.command.StorageSubSystemCommand; import org.apache.cloudstack.storage.command.SyncVolumePathCommand; import org.apache.cloudstack.storage.to.VolumeObjectTO; -import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; @@ -47,9 +46,11 @@ import com.cloud.serializer.GsonHelper; import com.cloud.storage.DataStoreRole; import com.cloud.storage.Volume; import com.google.gson.Gson; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class StorageSubsystemCommandHandlerBase implements StorageSubsystemCommandHandler { - private static final Logger s_logger = Logger.getLogger(StorageSubsystemCommandHandlerBase.class); + protected Logger logger = LogManager.getLogger(getClass()); protected static final Gson s_gogger = GsonHelper.getGsonLogger(); protected StorageProcessor processor; @@ -141,7 +142,7 @@ public class StorageSubsystemCommandHandlerBase implements StorageSubsystemComma } return new CreateObjectAnswer("not supported type"); } catch (Exception e) { - s_logger.debug("Failed to create object: " + data.getObjectType() + ": " + e.toString()); + logger.debug("Failed to create object: " + data.getObjectType() + ": " + e.toString()); return new CreateObjectAnswer(e.toString()); } } @@ -184,9 +185,9 @@ public class StorageSubsystemCommandHandlerBase implements StorageSubsystemComma private void logCommand(Command cmd) { try { - s_logger.debug(String.format("Executing command %s: [%s].", cmd.getClass().getSimpleName(), s_gogger.toJson(cmd))); + logger.debug(String.format("Executing command %s: [%s].", cmd.getClass().getSimpleName(), s_gogger.toJson(cmd))); } catch (Exception e) { - s_logger.debug(String.format("Executing command %s.", cmd.getClass().getSimpleName())); + logger.debug(String.format("Executing command %s.", cmd.getClass().getSimpleName())); } } } diff --git a/core/src/main/java/com/cloud/storage/template/FtpTemplateUploader.java b/core/src/main/java/com/cloud/storage/template/FtpTemplateUploader.java index eb0c4f84601..14bf6fe1b74 100644 --- a/core/src/main/java/com/cloud/storage/template/FtpTemplateUploader.java +++ b/core/src/main/java/com/cloud/storage/template/FtpTemplateUploader.java @@ -29,11 +29,12 @@ import java.net.URL; import java.net.URLConnection; import java.util.Date; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; public class FtpTemplateUploader implements TemplateUploader { - public static final Logger s_logger = Logger.getLogger(FtpTemplateUploader.class.getName()); + protected Logger logger = LogManager.getLogger(getClass()); public TemplateUploader.Status status = TemplateUploader.Status.NOT_STARTED; public String errorString = ""; public long totalBytes = 0; @@ -110,11 +111,11 @@ public class FtpTemplateUploader implements TemplateUploader { } catch (MalformedURLException e) { status = TemplateUploader.Status.UNRECOVERABLE_ERROR; errorString = e.getMessage(); - s_logger.error(errorString); + logger.error(errorString); } catch (IOException e) { status = TemplateUploader.Status.UNRECOVERABLE_ERROR; errorString = e.getMessage(); - s_logger.error(errorString); + logger.error(errorString); } finally { try { if (inputStream != null) { @@ -124,7 +125,7 @@ public class FtpTemplateUploader implements TemplateUploader { outputStream.close(); } } catch (IOException ioe) { - s_logger.error(" Caught exception while closing the resources"); + logger.error(" Caught exception while closing the resources"); } if (callback != null) { callback.uploadComplete(status); @@ -139,7 +140,7 @@ public class FtpTemplateUploader implements TemplateUploader { try { upload(completionCallback); } catch (Throwable t) { - s_logger.warn("Caught exception during upload " + t.getMessage(), t); + logger.warn("Caught exception during upload " + t.getMessage(), t); errorString = "Failed to install: " + t.getMessage(); status = TemplateUploader.Status.UNRECOVERABLE_ERROR; } @@ -207,7 +208,7 @@ public class FtpTemplateUploader implements TemplateUploader { inputStream.close(); } } catch (IOException e) { - s_logger.error(" Caught exception while closing the resources"); + logger.error(" Caught exception while closing the resources"); } status = TemplateUploader.Status.ABORTED; return true; diff --git a/core/src/main/java/com/cloud/storage/template/HttpTemplateDownloader.java b/core/src/main/java/com/cloud/storage/template/HttpTemplateDownloader.java index 7ad8070b6e5..4c056f256cf 100755 --- a/core/src/main/java/com/cloud/storage/template/HttpTemplateDownloader.java +++ b/core/src/main/java/com/cloud/storage/template/HttpTemplateDownloader.java @@ -27,6 +27,7 @@ import java.io.InputStream; import java.io.RandomAccessFile; import java.net.URI; import java.net.URISyntaxException; +import java.util.Arrays; import java.util.Date; import java.util.List; @@ -46,7 +47,6 @@ import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; -import org.apache.log4j.Logger; import com.cloud.storage.StorageLayer; import com.cloud.utils.Pair; @@ -59,7 +59,6 @@ import com.cloud.utils.net.Proxy; * */ public class HttpTemplateDownloader extends ManagedContextRunnable implements TemplateDownloader { - public static final Logger s_logger = Logger.getLogger(HttpTemplateDownloader.class.getName()); private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); private static final int CHUNK_SIZE = 1024 * 1024; //1M @@ -82,6 +81,18 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te private ResourceType resourceType = ResourceType.TEMPLATE; private final HttpMethodRetryHandler myretryhandler; private boolean followRedirects = false; + private boolean isChunkedTransfer; + + protected static final List CUSTOM_HEADERS_FOR_CHUNKED_TRANSFER_SIZE = Arrays.asList( + "x-goog-stored-content-length", + "x-goog-meta-size", + "x-amz-meta-size", + "x-amz-meta-content-length", + "x-object-meta-size", + "x-original-content-length", + "x-oss-meta-content-length", + "x-file-size"); + private static final long MIN_FORMAT_VERIFICATION_SIZE = 1024 * 1024; public HttpTemplateDownloader(StorageLayer storageLayer, String downloadUrl, String toDir, DownloadCompleteCallback callback, long maxTemplateSizeInBytes, String user, String password, Proxy proxy, ResourceType resourceType) { @@ -104,9 +115,9 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te } catch (Exception ex) { errorString = "Unable to start download -- check url? "; status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; - s_logger.warn("Exception in constructor -- " + ex.toString()); + logger.warn("Exception in constructor -- " + ex.toString()); } catch (Throwable th) { - s_logger.warn("throwable caught ", th); + logger.warn("throwable caught ", th); } } @@ -129,7 +140,7 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te } catch (IOException ex) { errorString = "Unable to start download -- check url? "; status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; - s_logger.warn("Exception in constructor -- " + ex.toString()); + logger.warn("Exception in constructor -- " + ex.toString()); } } @@ -140,9 +151,9 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(user, password); client.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds); - s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second()); + logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second()); } else { - s_logger.info("No credentials configured for host=" + hostAndPort.first() + ":" + hostAndPort.second()); + logger.info("No credentials configured for host=" + hostAndPort.first() + ":" + hostAndPort.second()); } } catch (IllegalArgumentException iae) { errorString = iae.getMessage(); @@ -207,13 +218,11 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te RandomAccessFile out = new RandomAccessFile(file, "rw"); ) { out.seek(localFileSize); - - s_logger.info("Starting download from " + downloadUrl + " to " + toFile + " remoteSize=" + toHumanReadableSize(remoteSize) + " , max size=" + toHumanReadableSize(maxTemplateSizeInBytes)); - - if (copyBytes(file, in, out)) return 0; - + logger.info("Starting download from {} to {} remoteSize={} , max size={}",downloadUrl, toFile, + toHumanReadableSize(remoteSize), toHumanReadableSize(maxTemplateSizeInBytes)); + boolean eof = copyBytes(file, in, out); Date finish = new Date(); - checkDowloadCompletion(); + checkDownloadCompletion(eof); downloadTime += finish.getTime() - start.getTime(); } finally { /* in.close() and out.close() */ } return totalBytes; @@ -239,28 +248,32 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te } private boolean copyBytes(File file, InputStream in, RandomAccessFile out) throws IOException { - int bytes; - byte[] block = new byte[CHUNK_SIZE]; + byte[] buffer = new byte[CHUNK_SIZE]; long offset = 0; - boolean done = false; VerifyFormat verifyFormat = new VerifyFormat(file); status = Status.IN_PROGRESS; - while (!done && status != Status.ABORTED && offset <= remoteSize) { - if ((bytes = in.read(block, 0, CHUNK_SIZE)) > -1) { - offset = writeBlock(bytes, out, block, offset); - if (!ResourceType.SNAPSHOT.equals(resourceType) && - !verifyFormat.isVerifiedFormat() && - (offset >= 1048576 || offset >= remoteSize)) { //let's check format after we get 1MB or full file - verifyFormat.invoke(); - } - } else { - done = true; + while (status != Status.ABORTED) { + int bytesRead = in.read(buffer, 0, CHUNK_SIZE); + if (bytesRead == -1) { + logger.debug("Reached EOF on input stream"); + break; + } + offset = writeBlock(bytesRead, out, buffer, offset); + if (!ResourceType.SNAPSHOT.equals(resourceType) + && !verifyFormat.isVerifiedFormat() + && (offset >= MIN_FORMAT_VERIFICATION_SIZE || offset >= remoteSize)) { + verifyFormat.invoke(); + } + if (offset >= remoteSize) { + logger.debug("Reached expected remote size limit: {} bytes", remoteSize); + break; } } out.getFD().sync(); - return false; + return !Status.ABORTED.equals(status); } + private long writeBlock(int bytes, RandomAccessFile out, byte[] block, long offset) throws IOException { out.write(block, 0, bytes); offset += bytes; @@ -269,18 +282,20 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te return offset; } - private void checkDowloadCompletion() { + private void checkDownloadCompletion(boolean eof) { String downloaded = "(incomplete download)"; - if (totalBytes >= remoteSize) { + if (eof && ((totalBytes >= remoteSize) || (isChunkedTransfer && remoteSize == maxTemplateSizeInBytes))) { status = Status.DOWNLOAD_FINISHED; - downloaded = "(download complete remote=" + toHumanReadableSize(remoteSize) + " bytes)"; + downloaded = "(download complete remote=" + + (remoteSize == maxTemplateSizeInBytes ? toHumanReadableSize(remoteSize) : "unknown") + + " bytes)"; } errorString = "Downloaded " + toHumanReadableSize(totalBytes) + " bytes " + downloaded; } private boolean canHandleDownloadSize() { if (remoteSize > maxTemplateSizeInBytes) { - s_logger.info("Remote size is too large: " + toHumanReadableSize(remoteSize) + " , max=" + toHumanReadableSize(maxTemplateSizeInBytes)); + logger.info("Remote size is too large: " + toHumanReadableSize(remoteSize) + " , max=" + toHumanReadableSize(maxTemplateSizeInBytes)); status = Status.UNRECOVERABLE_ERROR; errorString = "Download file size is too large"; return false; @@ -295,18 +310,42 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te } } + protected long getRemoteSizeForChunkedTransfer() { + for (String headerKey : CUSTOM_HEADERS_FOR_CHUNKED_TRANSFER_SIZE) { + Header header = request.getResponseHeader(headerKey); + if (header == null) { + continue; + } + try { + return Long.parseLong(header.getValue()); + } catch (NumberFormatException ignored) {} + } + Header contentRangeHeader = request.getResponseHeader("Content-Range"); + if (contentRangeHeader != null) { + String contentRange = contentRangeHeader.getValue(); + if (contentRange != null && contentRange.contains("/")) { + String totalSize = contentRange.substring(contentRange.indexOf('/') + 1).trim(); + return Long.parseLong(totalSize); + } + } + return 0; + } + private boolean tryAndGetRemoteSize() { Header contentLengthHeader = request.getResponseHeader("content-length"); - boolean chunked = false; + isChunkedTransfer = false; long reportedRemoteSize = 0; if (contentLengthHeader == null) { Header chunkedHeader = request.getResponseHeader("Transfer-Encoding"); - if (chunkedHeader == null || !"chunked".equalsIgnoreCase(chunkedHeader.getValue())) { + if (chunkedHeader != null && "chunked".equalsIgnoreCase(chunkedHeader.getValue())) { + isChunkedTransfer = true; + reportedRemoteSize = getRemoteSizeForChunkedTransfer(); + logger.debug("{} is using chunked transfer encoding, possible remote size: {}", downloadUrl, + reportedRemoteSize); + } else { status = Status.UNRECOVERABLE_ERROR; errorString = " Failed to receive length of download "; return false; - } else if ("chunked".equalsIgnoreCase(chunkedHeader.getValue())) { - chunked = true; } } else { reportedRemoteSize = Long.parseLong(contentLengthHeader.getValue()); @@ -318,9 +357,11 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te return false; } } - if (remoteSize == 0) { remoteSize = reportedRemoteSize; + if (remoteSize != 0) { + logger.debug("Remote size for {} found to be {}", downloadUrl, toHumanReadableSize(remoteSize)); + } } return true; } @@ -343,7 +384,7 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te && !followRedirects) { errorString = String.format("Failed to download %s due to redirection, response code: %d", downloadUrl, responseCode); - s_logger.error(errorString); + logger.error(errorString); } return true; //FIXME: retry? } @@ -355,7 +396,7 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te long localFileSize = 0; if (file.exists() && resume) { localFileSize = file.length(); - s_logger.info("Resuming download to file (current size)=" + toHumanReadableSize(localFileSize)); + logger.info("Resuming download to file (current size)=" + toHumanReadableSize(localFileSize)); } return localFileSize; } @@ -439,7 +480,7 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te try { download(resume, completionCallback); } catch (Throwable t) { - s_logger.warn("Caught exception during download " + t.getMessage(), t); + logger.warn("Caught exception during download " + t.getMessage(), t); errorString = "Failed to install: " + t.getMessage(); status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; } @@ -527,20 +568,20 @@ public class HttpTemplateDownloader extends ManagedContextRunnable implements Te URI str = new URI(downloadUrl); uripath = str.getPath(); } catch (URISyntaxException e) { - s_logger.warn("Invalid download url: " + downloadUrl + ", This should not happen since we have validated the url before!!"); + logger.warn("Invalid download url: " + downloadUrl + ", This should not happen since we have validated the url before!!"); } String unsupportedFormat = ImageStoreUtil.checkTemplateFormat(file.getAbsolutePath(), uripath); if (unsupportedFormat == null || !unsupportedFormat.isEmpty()) { try { request.abort(); } catch (Exception ex) { - s_logger.debug("Error on http connection : " + ex.getMessage()); + logger.debug("Error on http connection : " + ex.getMessage()); } status = Status.UNRECOVERABLE_ERROR; errorString = "Template content is unsupported, or mismatch between selected format and template content. Found : " + unsupportedFormat; throw new CloudRuntimeException(errorString); } else { - s_logger.debug("Verified format of downloading file " + file.getAbsolutePath() + " is supported"); + logger.debug("Verified format of downloading file " + file.getAbsolutePath() + " is supported"); verifiedFormat = true; } return this; diff --git a/core/src/main/java/com/cloud/storage/template/IsoProcessor.java b/core/src/main/java/com/cloud/storage/template/IsoProcessor.java index 4cd2f1a2a02..6ab42effb52 100644 --- a/core/src/main/java/com/cloud/storage/template/IsoProcessor.java +++ b/core/src/main/java/com/cloud/storage/template/IsoProcessor.java @@ -24,14 +24,12 @@ import java.util.Map; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageLayer; import com.cloud.utils.component.AdapterBase; public class IsoProcessor extends AdapterBase implements Processor { - private static final Logger s_logger = Logger.getLogger(IsoProcessor.class); StorageLayer _storage; @@ -43,14 +41,14 @@ public class IsoProcessor extends AdapterBase implements Processor { @Override public FormatInfo process(String templatePath, ImageFormat format, String templateName, long processTimeout) { if (format != null) { - s_logger.debug("We don't handle conversion from " + format + " to ISO."); + logger.debug("We don't handle conversion from " + format + " to ISO."); return null; } String isoPath = templatePath + File.separator + templateName + "." + ImageFormat.ISO.getFileExtension(); if (!_storage.exists(isoPath)) { - s_logger.debug("Unable to find the iso file: " + isoPath); + logger.debug("Unable to find the iso file: " + isoPath); return null; } diff --git a/core/src/main/java/com/cloud/storage/template/LocalTemplateDownloader.java b/core/src/main/java/com/cloud/storage/template/LocalTemplateDownloader.java index 564eba3d5ee..e4044412c52 100644 --- a/core/src/main/java/com/cloud/storage/template/LocalTemplateDownloader.java +++ b/core/src/main/java/com/cloud/storage/template/LocalTemplateDownloader.java @@ -29,12 +29,10 @@ import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; -import org.apache.log4j.Logger; import com.cloud.storage.StorageLayer; public class LocalTemplateDownloader extends TemplateDownloaderBase implements TemplateDownloader { - public static final Logger s_logger = Logger.getLogger(LocalTemplateDownloader.class); public LocalTemplateDownloader(StorageLayer storageLayer, String downloadUrl, String toDir, long maxTemplateSizeInBytes, DownloadCompleteCallback callback) { super(storageLayer, downloadUrl, toDir, maxTemplateSizeInBytes, callback); @@ -55,7 +53,7 @@ public class LocalTemplateDownloader extends TemplateDownloaderBase implements T try { src = new File(new URI(_downloadUrl)); } catch (URISyntaxException e1) { - s_logger.warn("Invalid URI " + _downloadUrl); + logger.warn("Invalid URI " + _downloadUrl); _status = Status.UNRECOVERABLE_ERROR; return 0; } @@ -77,7 +75,7 @@ public class LocalTemplateDownloader extends TemplateDownloaderBase implements T try { fis = new FileInputStream(src); } catch (FileNotFoundException e) { - s_logger.warn("Unable to find " + _downloadUrl); + logger.warn("Unable to find " + _downloadUrl); _errorString = "Unable to find " + _downloadUrl; return -1; } @@ -85,7 +83,7 @@ public class LocalTemplateDownloader extends TemplateDownloaderBase implements T try { fos = new FileOutputStream(dst); } catch (FileNotFoundException e) { - s_logger.warn("Unable to find " + _toFile); + logger.warn("Unable to find " + _toFile); return -1; } foc = fos.getChannel(); @@ -102,7 +100,7 @@ public class LocalTemplateDownloader extends TemplateDownloaderBase implements T buffer.clear(); } } catch (IOException e) { - s_logger.warn("Unable to download", e); + logger.warn("Unable to download", e); } String downloaded = "(incomplete download)"; @@ -123,7 +121,7 @@ public class LocalTemplateDownloader extends TemplateDownloaderBase implements T try { fic.close(); } catch (IOException e) { - s_logger.info("[ignore] error while closing file input channel."); + logger.info("[ignore] error while closing file input channel."); } } @@ -131,7 +129,7 @@ public class LocalTemplateDownloader extends TemplateDownloaderBase implements T try { foc.close(); } catch (IOException e) { - s_logger.info("[ignore] error while closing file output channel."); + logger.info("[ignore] error while closing file output channel."); } } @@ -139,7 +137,7 @@ public class LocalTemplateDownloader extends TemplateDownloaderBase implements T try { fis.close(); } catch (IOException e) { - s_logger.info("[ignore] error while closing file input stream."); + logger.info("[ignore] error while closing file input stream."); } } @@ -147,7 +145,7 @@ public class LocalTemplateDownloader extends TemplateDownloaderBase implements T try { fos.close(); } catch (IOException e) { - s_logger.info("[ignore] error while closing file output stream."); + logger.info("[ignore] error while closing file output stream."); } } diff --git a/core/src/main/java/com/cloud/storage/template/MetalinkTemplateDownloader.java b/core/src/main/java/com/cloud/storage/template/MetalinkTemplateDownloader.java index a118a9ac40f..2e62809dfed 100644 --- a/core/src/main/java/com/cloud/storage/template/MetalinkTemplateDownloader.java +++ b/core/src/main/java/com/cloud/storage/template/MetalinkTemplateDownloader.java @@ -28,7 +28,6 @@ import org.apache.commons.httpclient.NoHttpResponseException; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.io.IOUtils; -import org.apache.log4j.Logger; import org.springframework.util.CollectionUtils; import java.io.File; @@ -47,7 +46,6 @@ public class MetalinkTemplateDownloader extends TemplateDownloaderBase implement protected GetMethod request; private boolean toFileSet = false; - private static final Logger LOGGER = Logger.getLogger(MetalinkTemplateDownloader.class.getName()); public MetalinkTemplateDownloader(StorageLayer storageLayer, String downloadUrl, String toDir, DownloadCompleteCallback callback, long maxTemplateSize) { super(storageLayer, downloadUrl, toDir, maxTemplateSize, callback); @@ -97,7 +95,7 @@ public class MetalinkTemplateDownloader extends TemplateDownloaderBase implement try { client.executeMethod(request); } catch (IOException e) { - LOGGER.error("Error on HTTP request: " + e.getMessage()); + logger.error("Error on HTTP request: " + e.getMessage()); return false; } return performDownload(); @@ -110,7 +108,7 @@ public class MetalinkTemplateDownloader extends TemplateDownloaderBase implement ) { IOUtils.copy(in, out); } catch (IOException e) { - LOGGER.error("Error downloading template from: " + _downloadUrl + " due to: " + e.getMessage()); + logger.error("Error downloading template from: " + _downloadUrl + " due to: " + e.getMessage()); return false; } return true; @@ -121,13 +119,13 @@ public class MetalinkTemplateDownloader extends TemplateDownloaderBase implement return 0; } - LOGGER.info("Starting metalink download from: " + _downloadUrl); + logger.info("Starting metalink download from: " + _downloadUrl); _start = System.currentTimeMillis(); status = Status.IN_PROGRESS; List metalinkUrls = UriUtils.getMetalinkUrls(_downloadUrl); if (CollectionUtils.isEmpty(metalinkUrls)) { - LOGGER.error("No URLs found for metalink: " + _downloadUrl); + logger.error("No URLs found for metalink: " + _downloadUrl); status = Status.UNRECOVERABLE_ERROR; return 0; } @@ -140,11 +138,11 @@ public class MetalinkTemplateDownloader extends TemplateDownloaderBase implement i++; } if (!downloaded) { - LOGGER.error("Template couldn't be downloaded"); + logger.error("Template couldn't be downloaded"); status = Status.UNRECOVERABLE_ERROR; return 0; } - LOGGER.info("Template downloaded successfully on: " + _toFile); + logger.info("Template downloaded successfully on: " + _toFile); status = Status.DOWNLOAD_FINISHED; _downloadTime = System.currentTimeMillis() - _start; if (_callback != null) { diff --git a/core/src/main/java/com/cloud/storage/template/OVAProcessor.java b/core/src/main/java/com/cloud/storage/template/OVAProcessor.java index 33f7e28ac03..ab3aa0d0e3a 100644 --- a/core/src/main/java/com/cloud/storage/template/OVAProcessor.java +++ b/core/src/main/java/com/cloud/storage/template/OVAProcessor.java @@ -34,7 +34,6 @@ import com.cloud.agent.api.to.deployasis.OVFVirtualHardwareSectionTO; import com.cloud.agent.api.to.deployasis.OVFNetworkTO; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -52,7 +51,6 @@ import com.cloud.utils.script.Script; * processes the content of an OVA for registration of a template */ public class OVAProcessor extends AdapterBase implements Processor { - private static final Logger LOGGER = Logger.getLogger(OVAProcessor.class); StorageLayer _storage; @Override @@ -66,11 +64,11 @@ public class OVAProcessor extends AdapterBase implements Processor { return null; } - LOGGER.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); + logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension(); if (!_storage.exists(templateFilePath)) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Unable to find the vmware template file: " + templateFilePath); + if (logger.isInfoEnabled()) { + logger.info("Unable to find the vmware template file: " + templateFilePath); } return null; } @@ -114,46 +112,46 @@ public class OVAProcessor extends AdapterBase implements Processor { List disks = ovfHelper.getOVFVolumeInfoFromFile(ovfFilePath, doc, null); if (CollectionUtils.isNotEmpty(disks)) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace(String.format("Found %d disks in template %s", disks.size(), ovfFilePath)); + if (logger.isTraceEnabled()) { + logger.trace(String.format("Found %d disks in template %s", disks.size(), ovfFilePath)); } ovfInformationTO.setDisks(disks); } List nets = ovfHelper.getNetPrerequisitesFromDocument(doc); if (CollectionUtils.isNotEmpty(nets)) { - LOGGER.info("Found " + nets.size() + " prerequisite networks"); + logger.info("Found " + nets.size() + " prerequisite networks"); ovfInformationTO.setNetworks(nets); - } else if (LOGGER.isTraceEnabled()) { - LOGGER.trace(String.format("no net prerequisites found in template %s", ovfFilePath)); + } else if (logger.isTraceEnabled()) { + logger.trace(String.format("no net prerequisites found in template %s", ovfFilePath)); } List ovfProperties = ovfHelper.getConfigurableOVFPropertiesFromDocument(doc); if (CollectionUtils.isNotEmpty(ovfProperties)) { - LOGGER.info("Found " + ovfProperties.size() + " configurable OVF properties"); + logger.info("Found " + ovfProperties.size() + " configurable OVF properties"); ovfInformationTO.setProperties(ovfProperties); - } else if (LOGGER.isTraceEnabled()) { - LOGGER.trace(String.format("no ovf properties found in template %s", ovfFilePath)); + } else if (logger.isTraceEnabled()) { + logger.trace(String.format("no ovf properties found in template %s", ovfFilePath)); } OVFVirtualHardwareSectionTO hardwareSection = ovfHelper.getVirtualHardwareSectionFromDocument(doc); List configurations = hardwareSection.getConfigurations(); if (CollectionUtils.isNotEmpty(configurations)) { - LOGGER.info("Found " + configurations.size() + " deployment option configurations"); + logger.info("Found " + configurations.size() + " deployment option configurations"); } List hardwareItems = hardwareSection.getCommonHardwareItems(); if (CollectionUtils.isNotEmpty(hardwareItems)) { - LOGGER.info("Found " + hardwareItems.size() + " virtual hardware items"); + logger.info("Found " + hardwareItems.size() + " virtual hardware items"); } if (StringUtils.isNotBlank(hardwareSection.getMinimiumHardwareVersion())) { - LOGGER.info("Found minimum hardware version " + hardwareSection.getMinimiumHardwareVersion()); + logger.info("Found minimum hardware version " + hardwareSection.getMinimiumHardwareVersion()); } ovfInformationTO.setHardwareSection(hardwareSection); List eulaSections = ovfHelper.getEulaSectionsFromDocument(doc); if (CollectionUtils.isNotEmpty(eulaSections)) { - LOGGER.info("Found " + eulaSections.size() + " license agreements"); + logger.info("Found " + eulaSections.size() + " license agreements"); ovfInformationTO.setEulaSections(eulaSections); } Pair guestOsPair = ovfHelper.getOperatingSystemInfoFromDocument(doc); if (guestOsPair != null) { - LOGGER.info("Found guest OS information: " + guestOsPair.first() + " - " + guestOsPair.second()); + logger.info("Found guest OS information: " + guestOsPair.first() + " - " + guestOsPair.second()); ovfInformationTO.setGuestOsInfo(guestOsPair); } return ovfInformationTO; @@ -163,33 +161,33 @@ public class OVAProcessor extends AdapterBase implements Processor { Script command; String result; - command = new Script("chmod", 0, LOGGER); + command = new Script("chmod", 0, logger); command.add("-R"); command.add("666", templatePath); result = command.execute(); if (result != null) { - LOGGER.warn("Unable to set permissions for files in " + templatePath + " due to " + result); + logger.warn("Unable to set permissions for files in " + templatePath + " due to " + result); } - command = new Script("chmod", 0, LOGGER); + command = new Script("chmod", 0, logger); command.add("777", templatePath); result = command.execute(); if (result != null) { - LOGGER.warn("Unable to set permissions for " + templatePath + " due to " + result); + logger.warn("Unable to set permissions for " + templatePath + " due to " + result); } } private String unpackOva(String templatePath, String templateName, long processTimeout) throws InternalErrorException { - LOGGER.info("Template processing - untar OVA package. templatePath: " + templatePath + ", templateName: " + templateName); + logger.info("Template processing - untar OVA package. templatePath: " + templatePath + ", templateName: " + templateName); String templateFileFullPath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension(); File templateFile = new File(templateFileFullPath); - Script command = new Script("tar", processTimeout, LOGGER); + Script command = new Script("tar", processTimeout, logger); command.add("--no-same-owner"); command.add("--no-same-permissions"); command.add("-xf", templateFileFullPath); command.setWorkDir(templateFile.getParent()); String result = command.execute(); if (result != null) { - LOGGER.info("failed to untar OVA package due to " + result + ". templatePath: " + templatePath + ", templateName: " + templateName); + logger.info("failed to untar OVA package due to " + result + ". templatePath: " + templatePath + ", templateName: " + templateName); throw new InternalErrorException("failed to untar OVA package"); } return templateFileFullPath; @@ -197,13 +195,13 @@ public class OVAProcessor extends AdapterBase implements Processor { private boolean conversionChecks(ImageFormat format) { if (format != null) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info("We currently don't handle conversion from " + format + " to OVA."); + if (logger.isInfoEnabled()) { + logger.info("We currently don't handle conversion from " + format + " to OVA."); } return false; } - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("We are handling format " + format + "."); + if (logger.isTraceEnabled()) { + logger.trace("We are handling format " + format + "."); } return true; } @@ -214,7 +212,7 @@ public class OVAProcessor extends AdapterBase implements Processor { long size = getTemplateVirtualSize(file.getParent(), file.getName()); return size; } catch (Exception e) { - LOGGER.info("[ignored]" + logger.info("[ignored]" + "failed to get virtual template size for ova: " + e.getLocalizedMessage()); } return file.length(); @@ -234,7 +232,7 @@ public class OVAProcessor extends AdapterBase implements Processor { OVFHelper ovfHelper = new OVFHelper(); if (ovfFileName == null) { String msg = "Unable to locate OVF file in template package directory: " + templatePath; - LOGGER.error(msg); + logger.error(msg); throw new InternalErrorException(msg); } try { @@ -248,7 +246,7 @@ public class OVAProcessor extends AdapterBase implements Processor { diskSize = Long.parseLong(diskSizeValue); } catch (NumberFormatException e) { // ASSUMEably the diskSize contains a property for replacement - LOGGER.warn(String.format("the disksize for disk %s is not a valid number: %s", disk.getAttribute("diskId"), diskSizeValue)); + logger.warn(String.format("the disksize for disk %s is not a valid number: %s", disk.getAttribute("diskId"), diskSizeValue)); // TODO parse the property to get any value can not be done at registration time // and will have to be done at deploytime, so for orchestration purposes // we now assume, a value of one @@ -260,7 +258,7 @@ public class OVAProcessor extends AdapterBase implements Processor { return virtualSize; } catch (InternalErrorException | NumberFormatException e) { String msg = "getTemplateVirtualSize: Unable to parse OVF XML document " + templatePath + " to get the virtual disk " + templateName + " size due to " + e; - LOGGER.error(msg); + logger.error(msg); throw new InternalErrorException(msg); } } diff --git a/core/src/main/java/com/cloud/storage/template/QCOW2Processor.java b/core/src/main/java/com/cloud/storage/template/QCOW2Processor.java index 56ae078dc51..df1722a0201 100644 --- a/core/src/main/java/com/cloud/storage/template/QCOW2Processor.java +++ b/core/src/main/java/com/cloud/storage/template/QCOW2Processor.java @@ -27,7 +27,6 @@ import java.util.Map; import javax.naming.ConfigurationException; import com.cloud.exception.InternalErrorException; -import org.apache.log4j.Logger; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageLayer; @@ -35,7 +34,6 @@ import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.AdapterBase; public class QCOW2Processor extends AdapterBase implements Processor { - private static final Logger s_logger = Logger.getLogger(QCOW2Processor.class); private static final int VIRTUALSIZE_HEADER_LOCATION = 24; private StorageLayer _storage; @@ -48,14 +46,14 @@ public class QCOW2Processor extends AdapterBase implements Processor { @Override public FormatInfo process(String templatePath, ImageFormat format, String templateName, long processTimeout) throws InternalErrorException { if (format != null) { - s_logger.debug("We currently don't handle conversion from " + format + " to QCOW2."); + logger.debug("We currently don't handle conversion from " + format + " to QCOW2."); return null; } String qcow2Path = templatePath + File.separator + templateName + "." + ImageFormat.QCOW2.getFileExtension(); if (!_storage.exists(qcow2Path)) { - s_logger.debug("Unable to find the qcow2 file: " + qcow2Path); + logger.debug("Unable to find the qcow2 file: " + qcow2Path); return null; } @@ -70,7 +68,7 @@ public class QCOW2Processor extends AdapterBase implements Processor { try { info.virtualSize = getTemplateVirtualSize(qcow2File); } catch (IOException e) { - s_logger.error("Unable to get virtual size from " + qcow2File.getName()); + logger.error("Unable to get virtual size from " + qcow2File.getName()); throw new InternalErrorException("unable to get virtual size from qcow2 file"); } @@ -83,7 +81,7 @@ public class QCOW2Processor extends AdapterBase implements Processor { long size = getTemplateVirtualSize(file); return size; } catch (Exception e) { - s_logger.info("[ignored]" + "failed to get template virtual size for QCOW2: " + e.getLocalizedMessage()); + logger.info("[ignored]" + "failed to get template virtual size for QCOW2: " + e.getLocalizedMessage()); } return file.length(); } diff --git a/core/src/main/java/com/cloud/storage/template/RawImageProcessor.java b/core/src/main/java/com/cloud/storage/template/RawImageProcessor.java index 5fbc626f271..d6c1f7a808f 100644 --- a/core/src/main/java/com/cloud/storage/template/RawImageProcessor.java +++ b/core/src/main/java/com/cloud/storage/template/RawImageProcessor.java @@ -24,7 +24,6 @@ import java.util.Map; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; import com.cloud.exception.InternalErrorException; import com.cloud.storage.Storage.ImageFormat; @@ -32,7 +31,6 @@ import com.cloud.storage.StorageLayer; import com.cloud.utils.component.AdapterBase; public class RawImageProcessor extends AdapterBase implements Processor { - private static final Logger s_logger = Logger.getLogger(RawImageProcessor.class); StorageLayer _storage; @Override @@ -53,13 +51,13 @@ public class RawImageProcessor extends AdapterBase implements Processor { @Override public FormatInfo process(String templatePath, ImageFormat format, String templateName, long processTimeout) throws InternalErrorException { if (format != null) { - s_logger.debug("We currently don't handle conversion from " + format + " to raw image."); + logger.debug("We currently don't handle conversion from " + format + " to raw image."); return null; } String imgPath = templatePath + File.separator + templateName + "." + ImageFormat.RAW.getFileExtension(); if (!_storage.exists(imgPath)) { - s_logger.debug("Unable to find raw image:" + imgPath); + logger.debug("Unable to find raw image:" + imgPath); return null; } FormatInfo info = new FormatInfo(); @@ -67,7 +65,7 @@ public class RawImageProcessor extends AdapterBase implements Processor { info.filename = templateName + "." + ImageFormat.RAW.getFileExtension(); info.size = _storage.getSize(imgPath); info.virtualSize = info.size; - s_logger.debug("Process raw image " + info.filename + " successfully"); + logger.debug("Process raw image " + info.filename + " successfully"); return info; } diff --git a/core/src/main/java/com/cloud/storage/template/S3TemplateDownloader.java b/core/src/main/java/com/cloud/storage/template/S3TemplateDownloader.java index a259e79fa42..c24a4cc221f 100644 --- a/core/src/main/java/com/cloud/storage/template/S3TemplateDownloader.java +++ b/core/src/main/java/com/cloud/storage/template/S3TemplateDownloader.java @@ -39,7 +39,6 @@ import org.apache.commons.httpclient.URIException; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import java.io.BufferedInputStream; import java.io.IOException; @@ -58,7 +57,6 @@ import static java.util.Arrays.asList; * Execution of the instance is started when runInContext() is called. */ public class S3TemplateDownloader extends ManagedContextRunnable implements TemplateDownloader { - private static final Logger LOGGER = Logger.getLogger(S3TemplateDownloader.class.getName()); private final String downloadUrl; private final String s3Key; @@ -112,7 +110,7 @@ public class S3TemplateDownloader extends ManagedContextRunnable implements Temp public long download(boolean resume, DownloadCompleteCallback callback) { if (!status.equals(Status.NOT_STARTED)) { // Only start downloading if we haven't started yet. - LOGGER.debug("Template download is already started, not starting again. Template: " + downloadUrl); + logger.debug("Template download is already started, not starting again. Template: " + downloadUrl); return 0; } @@ -120,7 +118,7 @@ public class S3TemplateDownloader extends ManagedContextRunnable implements Temp int responseCode; if ((responseCode = HTTPUtils.executeMethod(httpClient, getMethod)) == -1) { errorString = "Exception while executing HttpMethod " + getMethod.getName() + " on URL " + downloadUrl; - LOGGER.warn(errorString); + logger.warn(errorString); status = Status.UNRECOVERABLE_ERROR; return 0; @@ -130,7 +128,7 @@ public class S3TemplateDownloader extends ManagedContextRunnable implements Temp HttpStatus.SC_MOVED_TEMPORARILY).contains(responseCode) && !followRedirects; if (!HTTPUtils.verifyResponseCode(responseCode) || failedDueToRedirection) { errorString = "Response code for GetMethod of " + downloadUrl + " is incorrect, responseCode: " + responseCode; - LOGGER.warn(errorString); + logger.warn(errorString); status = Status.UNRECOVERABLE_ERROR; return 0; } @@ -142,7 +140,7 @@ public class S3TemplateDownloader extends ManagedContextRunnable implements Temp // Check the contentLengthHeader and transferEncodingHeader. if (contentLengthHeader == null) { errorString = "The ContentLengthHeader of " + downloadUrl + " isn't supplied"; - LOGGER.warn(errorString); + logger.warn(errorString); status = Status.UNRECOVERABLE_ERROR; return 0; @@ -153,7 +151,7 @@ public class S3TemplateDownloader extends ManagedContextRunnable implements Temp if (remoteSize > maxTemplateSizeInByte) { errorString = "Remote size is too large for template " + downloadUrl + " remote size is " + remoteSize + " max allowed is " + maxTemplateSizeInByte; - LOGGER.warn(errorString); + logger.warn(errorString); status = Status.UNRECOVERABLE_ERROR; return 0; @@ -165,13 +163,13 @@ public class S3TemplateDownloader extends ManagedContextRunnable implements Temp inputStream = new BufferedInputStream(getMethod.getResponseBodyAsStream()); } catch (IOException e) { errorString = "Exception occurred while opening InputStream for template " + downloadUrl; - LOGGER.warn(errorString); + logger.warn(errorString); status = Status.UNRECOVERABLE_ERROR; return 0; } - LOGGER.info("Starting download from " + downloadUrl + " to S3 bucket " + s3TO.getBucketName() + " and size " + toHumanReadableSize(remoteSize) + " bytes"); + logger.info("Starting download from " + downloadUrl + " to S3 bucket " + s3TO.getBucketName() + " and size " + toHumanReadableSize(remoteSize) + " bytes"); // Time the upload starts. final Date start = new Date(); @@ -200,7 +198,7 @@ public class S3TemplateDownloader extends ManagedContextRunnable implements Temp // Record the amount of bytes transferred. totalBytes += progressEvent.getBytesTransferred(); - LOGGER.trace("Template download from " + downloadUrl + " to S3 bucket " + s3TO.getBucketName() + " transferred " + toHumanReadableSize(totalBytes) + " in " + ((new Date().getTime() - start.getTime()) / 1000) + " seconds"); + logger.trace("Template download from " + downloadUrl + " to S3 bucket " + s3TO.getBucketName() + " transferred " + toHumanReadableSize(totalBytes) + " in " + ((new Date().getTime() - start.getTime()) / 1000) + " seconds"); if (progressEvent.getEventType() == ProgressEventType.TRANSFER_STARTED_EVENT) { status = Status.IN_PROGRESS; @@ -219,15 +217,15 @@ public class S3TemplateDownloader extends ManagedContextRunnable implements Temp upload.waitForCompletion(); } catch (InterruptedException e) { // Interruption while waiting for the upload to complete. - LOGGER.warn("Interruption occurred while waiting for upload of " + downloadUrl + " to complete"); + logger.warn("Interruption occurred while waiting for upload of " + downloadUrl + " to complete"); } downloadTime = new Date().getTime() - start.getTime(); if (status == Status.DOWNLOAD_FINISHED) { - LOGGER.info("Template download from " + downloadUrl + " to S3 bucket " + s3TO.getBucketName() + " transferred " + toHumanReadableSize(totalBytes) + " in " + (downloadTime / 1000) + " seconds, completed successfully!"); + logger.info("Template download from " + downloadUrl + " to S3 bucket " + s3TO.getBucketName() + " transferred " + toHumanReadableSize(totalBytes) + " in " + (downloadTime / 1000) + " seconds, completed successfully!"); } else { - LOGGER.warn("Template download from " + downloadUrl + " to S3 bucket " + s3TO.getBucketName() + " transferred " + toHumanReadableSize(totalBytes) + " in " + (downloadTime / 1000) + " seconds, completed with status " + status.toString()); + logger.warn("Template download from " + downloadUrl + " to S3 bucket " + s3TO.getBucketName() + " transferred " + toHumanReadableSize(totalBytes) + " in " + (downloadTime / 1000) + " seconds, completed with status " + status.toString()); } // Close input stream @@ -281,7 +279,7 @@ public class S3TemplateDownloader extends ManagedContextRunnable implements Temp } public void cleanupAfterError() { - LOGGER.warn("Cleanup after error, trying to remove object: " + s3Key); + logger.warn("Cleanup after error, trying to remove object: " + s3Key); S3Utils.deleteObject(s3TO, s3TO.getBucketName(), s3Key); } diff --git a/core/src/main/java/com/cloud/storage/template/ScpTemplateDownloader.java b/core/src/main/java/com/cloud/storage/template/ScpTemplateDownloader.java index 912809ca722..44379efcd55 100644 --- a/core/src/main/java/com/cloud/storage/template/ScpTemplateDownloader.java +++ b/core/src/main/java/com/cloud/storage/template/ScpTemplateDownloader.java @@ -23,7 +23,6 @@ import java.io.File; import java.net.URI; import java.net.URISyntaxException; -import org.apache.log4j.Logger; import com.trilead.ssh2.SCPClient; @@ -31,7 +30,6 @@ import com.cloud.storage.StorageLayer; import com.cloud.utils.exception.CloudRuntimeException; public class ScpTemplateDownloader extends TemplateDownloaderBase implements TemplateDownloader { - private static final Logger s_logger = Logger.getLogger(ScpTemplateDownloader.class); public ScpTemplateDownloader(StorageLayer storageLayer, String downloadUrl, String toDir, long maxTemplateSizeInBytes, DownloadCompleteCallback callback) { super(storageLayer, downloadUrl, toDir, maxTemplateSizeInBytes, callback); @@ -40,7 +38,7 @@ public class ScpTemplateDownloader extends TemplateDownloaderBase implements Tem try { uri = new URI(_downloadUrl); } catch (URISyntaxException e) { - s_logger.warn("URI syntax error: " + _downloadUrl); + logger.warn("URI syntax error: " + _downloadUrl); _status = Status.UNRECOVERABLE_ERROR; return; } @@ -108,7 +106,7 @@ public class ScpTemplateDownloader extends TemplateDownloaderBase implements Tem if (!file.exists()) { _status = Status.UNRECOVERABLE_ERROR; - s_logger.debug("unable to scp the file " + _downloadUrl); + logger.debug("unable to scp the file " + _downloadUrl); return 0; } @@ -123,7 +121,7 @@ public class ScpTemplateDownloader extends TemplateDownloaderBase implements Tem return _totalBytes; } catch (Exception e) { - s_logger.warn("Unable to download " + _downloadUrl, e); + logger.warn("Unable to download " + _downloadUrl, e); _status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; _errorString = e.getMessage(); return 0; diff --git a/core/src/main/java/com/cloud/storage/template/SimpleHttpMultiFileDownloader.java b/core/src/main/java/com/cloud/storage/template/SimpleHttpMultiFileDownloader.java index 56cf76fb9f6..8719947cb4f 100644 --- a/core/src/main/java/com/cloud/storage/template/SimpleHttpMultiFileDownloader.java +++ b/core/src/main/java/com/cloud/storage/template/SimpleHttpMultiFileDownloader.java @@ -42,12 +42,10 @@ import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.storage.StorageLayer; public class SimpleHttpMultiFileDownloader extends ManagedContextRunnable implements TemplateDownloader { - public static final Logger s_logger = Logger.getLogger(SimpleHttpMultiFileDownloader.class.getName()); private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); private static final int CHUNK_SIZE = 1024 * 1024; //1M @@ -110,7 +108,7 @@ public class SimpleHttpMultiFileDownloader extends ManagedContextRunnable implem } catch (IOException ex) { errorString = "Unable to start download -- check url? "; currentStatus = TemplateDownloader.Status.UNRECOVERABLE_ERROR; - s_logger.warn("Exception in constructor -- " + ex.toString()); + logger.warn("Exception in constructor -- " + ex.toString()); } } @@ -153,7 +151,7 @@ public class SimpleHttpMultiFileDownloader extends ManagedContextRunnable implem } totalRemoteSize += Long.parseLong(contentLengthHeader.getValue()); } catch (IOException e) { - s_logger.warn(String.format("Cannot reach URL: %s while trying to get remote sizes due to: %s", downloadUrl, e.getMessage()), e); + logger.warn(String.format("Cannot reach URL: %s while trying to get remote sizes due to: %s", downloadUrl, e.getMessage()), e); } finally { headMethod.releaseConnection(); } @@ -161,7 +159,7 @@ public class SimpleHttpMultiFileDownloader extends ManagedContextRunnable implem } private long downloadFile(String downloadUrl) { - s_logger.debug("Starting download for " + downloadUrl); + logger.debug("Starting download for " + downloadUrl); currentTotalBytes = 0; currentRemoteSize = 0; File file = null; @@ -180,7 +178,7 @@ public class SimpleHttpMultiFileDownloader extends ManagedContextRunnable implem RandomAccessFile out = new RandomAccessFile(file, "rw"); ) { out.seek(localFileSize); - s_logger.info("Starting download from " + downloadUrl + " to " + currentToFile + " remoteSize=" + toHumanReadableSize(currentRemoteSize) + " , max size=" + toHumanReadableSize(maxTemplateSizeInBytes)); + logger.info("Starting download from " + downloadUrl + " to " + currentToFile + " remoteSize=" + toHumanReadableSize(currentRemoteSize) + " , max size=" + toHumanReadableSize(maxTemplateSizeInBytes)); if (copyBytes(file, in, out)) return 0; checkDownloadCompletion(); } @@ -209,11 +207,11 @@ public class SimpleHttpMultiFileDownloader extends ManagedContextRunnable implem public long download(boolean resume, DownloadCompleteCallback callback) { if (skipDownloadOnStatus()) return 0; if (resume) { - s_logger.error("Resume not allowed for this downloader"); + logger.error("Resume not allowed for this downloader"); status = Status.UNRECOVERABLE_ERROR; return 0; } - s_logger.debug("Starting downloads"); + logger.debug("Starting downloads"); status = Status.IN_PROGRESS; Date start = new Date(); tryAndGetTotalRemoteSize(); @@ -272,7 +270,7 @@ public class SimpleHttpMultiFileDownloader extends ManagedContextRunnable implem private boolean canHandleDownloadSize() { if (currentRemoteSize > maxTemplateSizeInBytes) { - s_logger.info("Remote size is too large: " + toHumanReadableSize(currentRemoteSize) + " , max=" + toHumanReadableSize(maxTemplateSizeInBytes)); + logger.info("Remote size is too large: " + toHumanReadableSize(currentRemoteSize) + " , max=" + toHumanReadableSize(maxTemplateSizeInBytes)); currentStatus = Status.UNRECOVERABLE_ERROR; errorString = "Download file size is too large"; return false; @@ -337,7 +335,7 @@ public class SimpleHttpMultiFileDownloader extends ManagedContextRunnable implem && !followRedirects) { errorString = String.format("Failed to download %s due to redirection, response code: %d", downloadUrl, responseCode); - s_logger.error(errorString); + logger.error(errorString); } return true; //FIXME: retry? } @@ -349,7 +347,7 @@ public class SimpleHttpMultiFileDownloader extends ManagedContextRunnable implem long localFileSize = 0; if (file.exists() && resume) { localFileSize = file.length(); - s_logger.info("Resuming download to file (current size)=" + toHumanReadableSize(localFileSize)); + logger.info("Resuming download to file (current size)=" + toHumanReadableSize(localFileSize)); } return localFileSize; } @@ -433,7 +431,7 @@ public class SimpleHttpMultiFileDownloader extends ManagedContextRunnable implem try { download(resume, completionCallback); } catch (Throwable t) { - s_logger.warn("Caught exception during download " + t.getMessage(), t); + logger.warn("Caught exception during download " + t.getMessage(), t); errorString = "Failed to install: " + t.getMessage(); currentStatus = TemplateDownloader.Status.UNRECOVERABLE_ERROR; } diff --git a/core/src/main/java/com/cloud/storage/template/TARProcessor.java b/core/src/main/java/com/cloud/storage/template/TARProcessor.java index 51aeb234c50..70b59336323 100644 --- a/core/src/main/java/com/cloud/storage/template/TARProcessor.java +++ b/core/src/main/java/com/cloud/storage/template/TARProcessor.java @@ -22,14 +22,12 @@ package com.cloud.storage.template; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageLayer; import com.cloud.utils.component.AdapterBase; -import org.apache.log4j.Logger; import javax.naming.ConfigurationException; import java.io.File; import java.util.Map; public class TARProcessor extends AdapterBase implements Processor { - private static final Logger s_logger = Logger.getLogger(TARProcessor.class); private StorageLayer _storage; @@ -41,14 +39,14 @@ public class TARProcessor extends AdapterBase implements Processor { @Override public FormatInfo process(String templatePath, ImageFormat format, String templateName, long processTimeout) { if (format != null) { - s_logger.debug("We currently don't handle conversion from " + format + " to TAR."); + logger.debug("We currently don't handle conversion from " + format + " to TAR."); return null; } String tarPath = templatePath + File.separator + templateName + "." + ImageFormat.TAR.getFileExtension(); if (!_storage.exists(tarPath)) { - s_logger.debug("Unable to find the tar file: " + tarPath); + logger.debug("Unable to find the tar file: " + tarPath); return null; } diff --git a/core/src/main/java/com/cloud/storage/template/TemplateDownloaderBase.java b/core/src/main/java/com/cloud/storage/template/TemplateDownloaderBase.java index 66058bbf82e..f1cb21a1815 100644 --- a/core/src/main/java/com/cloud/storage/template/TemplateDownloaderBase.java +++ b/core/src/main/java/com/cloud/storage/template/TemplateDownloaderBase.java @@ -21,14 +21,12 @@ package com.cloud.storage.template; import java.io.File; -import org.apache.log4j.Logger; import org.apache.cloudstack.managed.context.ManagedContextRunnable; import com.cloud.storage.StorageLayer; public abstract class TemplateDownloaderBase extends ManagedContextRunnable implements TemplateDownloader { - private static final Logger s_logger = Logger.getLogger(TemplateDownloaderBase.class); protected String _downloadUrl; protected String _toFile; @@ -134,7 +132,7 @@ public abstract class TemplateDownloaderBase extends ManagedContextRunnable impl try { download(_resume, _callback); } catch (Exception e) { - s_logger.warn("Unable to complete download due to ", e); + logger.warn("Unable to complete download due to ", e); _errorString = "Failed to install: " + e.getMessage(); _status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; } diff --git a/core/src/main/java/com/cloud/storage/template/TemplateLocation.java b/core/src/main/java/com/cloud/storage/template/TemplateLocation.java index 6ff53a0410a..563c642f292 100644 --- a/core/src/main/java/com/cloud/storage/template/TemplateLocation.java +++ b/core/src/main/java/com/cloud/storage/template/TemplateLocation.java @@ -31,15 +31,16 @@ import java.util.Iterator; import java.util.Properties; import org.apache.cloudstack.storage.command.DownloadCommand.ResourceType; -import org.apache.log4j.Logger; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageLayer; import com.cloud.storage.template.Processor.FormatInfo; import com.cloud.utils.NumbersUtil; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class TemplateLocation { - private static final Logger s_logger = Logger.getLogger(TemplateLocation.class); + protected Logger logger = LogManager.getLogger(getClass()); public final static String Filename = "template.properties"; StorageLayer _storage; @@ -90,8 +91,8 @@ public class TemplateLocation { if (!isRemoved) { purged = false; } - if (s_logger.isDebugEnabled()) { - s_logger.debug((isRemoved ? "Removed " : "Unable to remove") + file); + if (logger.isDebugEnabled()) { + logger.debug((isRemoved ? "Removed " : "Unable to remove") + file); } } @@ -102,27 +103,27 @@ public class TemplateLocation { try (FileInputStream strm = new FileInputStream(_file);) { _props.load(strm); } catch (IOException e) { - s_logger.warn("Unable to load the template properties for '" + _file + "': ", e); + logger.warn("Unable to load the template properties for '" + _file + "': ", e); } for (ImageFormat format : ImageFormat.values()) { String currentExtension = format.getFileExtension(); String ext = _props.getProperty(currentExtension); if (ext != null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("File extension '" + currentExtension + "' was found in '" + _file + "'."); + if (logger.isDebugEnabled()) { + logger.debug("File extension '" + currentExtension + "' was found in '" + _file + "'."); } FormatInfo info = new FormatInfo(); info.format = format; info.filename = _props.getProperty(currentExtension + ".filename"); if (info.filename == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Property '" + currentExtension + ".filename' was not found in '" + _file + "'. Current format is ignored."); + if (logger.isDebugEnabled()) { + logger.debug("Property '" + currentExtension + ".filename' was not found in '" + _file + "'. Current format is ignored."); } continue; } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Property '" + currentExtension + ".filename' was found in '" + _file + "'. Current format will be parsed."); + if (logger.isDebugEnabled()) { + logger.debug("Property '" + currentExtension + ".filename' was found in '" + _file + "'. Current format will be parsed."); } info.size = NumbersUtil.parseLong(_props.getProperty(currentExtension + ".size"), -1); _props.setProperty("physicalSize", Long.toString(info.size)); @@ -131,18 +132,18 @@ public class TemplateLocation { if (!checkFormatValidity(info)) { _isCorrupted = true; - s_logger.warn("Cleaning up inconsistent information for " + format); + logger.warn("Cleaning up inconsistent information for " + format); } } else { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Format extension '" + currentExtension + "' wasn't found in '" + _file + "'."); + if (logger.isDebugEnabled()) { + logger.debug("Format extension '" + currentExtension + "' wasn't found in '" + _file + "'."); } } } if (_props.getProperty("uniquename") == null || _props.getProperty("virtualsize") == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Property 'uniquename' or 'virtualsize' weren't found in '" + _file + "'. Loading failed."); + if (logger.isDebugEnabled()) { + logger.debug("Property 'uniquename' or 'virtualsize' weren't found in '" + _file + "'. Loading failed."); } return false; } @@ -160,7 +161,7 @@ public class TemplateLocation { try (FileOutputStream strm = new FileOutputStream(_file);) { _props.store(strm, ""); } catch (IOException e) { - s_logger.warn("Unable to save the template properties ", e); + logger.warn("Unable to save the template properties ", e); return false; } return true; @@ -204,9 +205,9 @@ public class TemplateLocation { deleteFormat(newInfo.format); if (!checkFormatValidity(newInfo)) { - s_logger.warn("Format is invalid"); - s_logger.debug("Format: " + newInfo.format + " size: " + toHumanReadableSize(newInfo.size) + " virtualsize: " + toHumanReadableSize(newInfo.virtualSize) + " filename: " + newInfo.filename); - s_logger.debug("format, filename cannot be null and size, virtual size should be > 0 "); + logger.warn("Format is invalid"); + logger.debug("Format: " + newInfo.format + " size: " + toHumanReadableSize(newInfo.size) + " virtualsize: " + toHumanReadableSize(newInfo.virtualSize) + " filename: " + newInfo.filename); + logger.debug("format, filename cannot be null and size, virtual size should be > 0 "); return false; } diff --git a/core/src/main/java/com/cloud/storage/template/VhdProcessor.java b/core/src/main/java/com/cloud/storage/template/VhdProcessor.java index baea7bf0db5..9f18d782b42 100644 --- a/core/src/main/java/com/cloud/storage/template/VhdProcessor.java +++ b/core/src/main/java/com/cloud/storage/template/VhdProcessor.java @@ -27,7 +27,6 @@ import com.cloud.utils.component.AdapterBase; import org.apache.commons.compress.compressors.CompressorException; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; -import org.apache.log4j.Logger; import javax.naming.ConfigurationException; import java.io.BufferedInputStream; @@ -46,7 +45,6 @@ import java.util.Map; */ public class VhdProcessor extends AdapterBase implements Processor { - private static final Logger s_logger = Logger.getLogger(VhdProcessor.class); StorageLayer _storage; private int vhdFooterSize = 512; private int vhdCookieOffset = 8; @@ -64,13 +62,13 @@ public class VhdProcessor extends AdapterBase implements Processor { @Override public FormatInfo process(String templatePath, ImageFormat format, String templateName, long processTimeout) throws InternalErrorException { if (format != null) { - s_logger.debug("We currently don't handle conversion from " + format + " to VHD."); + logger.debug("We currently don't handle conversion from " + format + " to VHD."); return null; } String vhdPath = templatePath + File.separator + templateName + "." + ImageFormat.VHD.getFileExtension(); if (!_storage.exists(vhdPath)) { - s_logger.debug("Unable to find the vhd file: " + vhdPath); + logger.debug("Unable to find the vhd file: " + vhdPath); return null; } @@ -84,7 +82,7 @@ public class VhdProcessor extends AdapterBase implements Processor { try { info.virtualSize = getTemplateVirtualSize(vhdFile); } catch (IOException e) { - s_logger.error("Unable to get the virtual size for " + vhdPath); + logger.error("Unable to get the virtual size for " + vhdPath); throw new InternalErrorException("unable to get virtual size from vhd file"); } @@ -97,7 +95,7 @@ public class VhdProcessor extends AdapterBase implements Processor { long size = getTemplateVirtualSize(file); return size; } catch (Exception e) { - s_logger.info("[ignored]" + "failed to get template virtual size for VHD: " + e.getLocalizedMessage()); + logger.info("[ignored]" + "failed to get template virtual size for VHD: " + e.getLocalizedMessage()); } return file.length(); } @@ -117,7 +115,7 @@ public class VhdProcessor extends AdapterBase implements Processor { try { strm = new CompressorStreamFactory().createCompressorInputStream(fileStream); } catch (CompressorException e) { - s_logger.info("error opening compressed VHD file " + file.getName()); + logger.info("error opening compressed VHD file " + file.getName()); return file.length(); } } try { @@ -146,7 +144,7 @@ public class VhdProcessor extends AdapterBase implements Processor { throw new IOException("Unexpected end-of-file"); } } catch (IOException e) { - s_logger.warn("Error reading virtual size from VHD file " + e.getMessage() + " VHD: " + file.getName()); + logger.warn("Error reading virtual size from VHD file " + e.getMessage() + " VHD: " + file.getName()); return file.length(); } finally { if (strm != null) { @@ -180,11 +178,11 @@ public class VhdProcessor extends AdapterBase implements Processor { cin = new CompressorStreamFactory().createCompressorInputStream(bin); } catch (CompressorException e) { - s_logger.warn(e.getMessage()); + logger.warn(e.getMessage()); return false; } catch (FileNotFoundException e) { - s_logger.warn(e.getMessage()); + logger.warn(e.getMessage()); return false; } finally { if (cin != null) diff --git a/core/src/main/java/com/cloud/storage/template/VmdkProcessor.java b/core/src/main/java/com/cloud/storage/template/VmdkProcessor.java index 927515f7544..4f53c556667 100644 --- a/core/src/main/java/com/cloud/storage/template/VmdkProcessor.java +++ b/core/src/main/java/com/cloud/storage/template/VmdkProcessor.java @@ -30,7 +30,6 @@ import java.util.regex.Pattern; import javax.naming.ConfigurationException; -import org.apache.log4j.Logger; import com.cloud.exception.InternalErrorException; import com.cloud.storage.Storage.ImageFormat; @@ -40,7 +39,6 @@ import com.cloud.utils.component.AdapterBase; import static com.cloud.utils.NumbersUtil.toHumanReadableSize; public class VmdkProcessor extends AdapterBase implements Processor { - private static final Logger s_logger = Logger.getLogger(VmdkProcessor.class); StorageLayer _storage; @@ -52,17 +50,17 @@ public class VmdkProcessor extends AdapterBase implements Processor { @Override public FormatInfo process(String templatePath, ImageFormat format, String templateName, long processTimeout) throws InternalErrorException { if (format != null) { - if (s_logger.isInfoEnabled()) { - s_logger.info("We currently don't handle conversion from " + format + " to VMDK."); + if (logger.isInfoEnabled()) { + logger.info("We currently don't handle conversion from " + format + " to VMDK."); } return null; } - s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); + logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.VMDK.getFileExtension(); if (!_storage.exists(templateFilePath)) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Unable to find the vmware template file: " + templateFilePath); + if (logger.isInfoEnabled()) { + logger.info("Unable to find the vmware template file: " + templateFilePath); } return null; } @@ -82,7 +80,7 @@ public class VmdkProcessor extends AdapterBase implements Processor { long size = getTemplateVirtualSize(file.getParent(), file.getName()); return size; } catch (Exception e) { - s_logger.info("[ignored]" + logger.info("[ignored]" + "failed to get template virtual size for vmdk: " + e.getLocalizedMessage()); } return file.length(); @@ -108,15 +106,15 @@ public class VmdkProcessor extends AdapterBase implements Processor { } } catch(FileNotFoundException ex) { String msg = "Unable to open file '" + templateFileFullPath + "' " + ex.toString(); - s_logger.error(msg); + logger.error(msg); throw new InternalErrorException(msg); } catch(IOException ex) { String msg = "Unable read open file '" + templateFileFullPath + "' " + ex.toString(); - s_logger.error(msg); + logger.error(msg); throw new InternalErrorException(msg); } - s_logger.debug("vmdk file had size=" + toHumanReadableSize(virtualSize)); + logger.debug("vmdk file had size=" + toHumanReadableSize(virtualSize)); return virtualSize; } diff --git a/core/src/main/java/org/apache/cloudstack/backup/BackupAnswer.java b/core/src/main/java/org/apache/cloudstack/backup/BackupAnswer.java new file mode 100644 index 00000000000..09f9c562150 --- /dev/null +++ b/core/src/main/java/org/apache/cloudstack/backup/BackupAnswer.java @@ -0,0 +1,59 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +// + +package org.apache.cloudstack.backup; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; + +import java.util.Map; + +public class BackupAnswer extends Answer { + private Long size; + private Long virtualSize; + private Map volumes; + + public BackupAnswer(final Command command, final boolean success, final String details) { + super(command, success, details); + } + + public Long getSize() { + return size; + } + + public void setSize(Long size) { + this.size = size; + } + + public Long getVirtualSize() { + return virtualSize; + } + + public void setVirtualSize(Long virtualSize) { + this.virtualSize = virtualSize; + } + + public Map getVolumes() { + return volumes; + } + + public void setVolumes(Map volumes) { + this.volumes = volumes; + } +} diff --git a/core/src/main/java/org/apache/cloudstack/backup/DeleteBackupCommand.java b/core/src/main/java/org/apache/cloudstack/backup/DeleteBackupCommand.java new file mode 100644 index 00000000000..16c611af998 --- /dev/null +++ b/core/src/main/java/org/apache/cloudstack/backup/DeleteBackupCommand.java @@ -0,0 +1,76 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +// + +package org.apache.cloudstack.backup; + +import com.cloud.agent.api.Command; +import com.cloud.agent.api.LogLevel; + +public class DeleteBackupCommand extends Command { + private String backupPath; + private String backupRepoType; + private String backupRepoAddress; + @LogLevel(LogLevel.Log4jLevel.Off) + private String mountOptions; + + public DeleteBackupCommand(String backupPath, String backupRepoType, String backupRepoAddress, String mountOptions) { + super(); + this.backupPath = backupPath; + this.backupRepoType = backupRepoType; + this.backupRepoAddress = backupRepoAddress; + this.mountOptions = mountOptions; + } + + public String getBackupPath() { + return backupPath; + } + + public void setBackupPath(String backupPath) { + this.backupPath = backupPath; + } + + public String getBackupRepoType() { + return backupRepoType; + } + + public void setBackupRepoType(String backupRepoType) { + this.backupRepoType = backupRepoType; + } + + public String getBackupRepoAddress() { + return backupRepoAddress; + } + + public void setBackupRepoAddress(String backupRepoAddress) { + this.backupRepoAddress = backupRepoAddress; + } + + public String getMountOptions() { + return mountOptions == null ? "" : mountOptions; + } + + public void setMountOptions(String mountOptions) { + this.mountOptions = mountOptions; + } + + @Override + public boolean executeInSequence() { + return true; + } +} diff --git a/core/src/main/java/org/apache/cloudstack/backup/RestoreBackupCommand.java b/core/src/main/java/org/apache/cloudstack/backup/RestoreBackupCommand.java new file mode 100644 index 00000000000..7228e35147a --- /dev/null +++ b/core/src/main/java/org/apache/cloudstack/backup/RestoreBackupCommand.java @@ -0,0 +1,130 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +// + +package org.apache.cloudstack.backup; + +import com.cloud.agent.api.Command; +import com.cloud.agent.api.LogLevel; +import com.cloud.vm.VirtualMachine; + +import java.util.List; + +public class RestoreBackupCommand extends Command { + private String vmName; + private String backupPath; + private String backupRepoType; + private String backupRepoAddress; + private List volumePaths; + private String diskType; + private Boolean vmExists; + private String restoreVolumeUUID; + private VirtualMachine.State vmState; + + protected RestoreBackupCommand() { + super(); + } + + public String getVmName() { + return vmName; + } + + public void setVmName(String vmName) { + this.vmName = vmName; + } + + public String getBackupPath() { + return backupPath; + } + + public void setBackupPath(String backupPath) { + this.backupPath = backupPath; + } + + public String getBackupRepoType() { + return backupRepoType; + } + + public void setBackupRepoType(String backupRepoType) { + this.backupRepoType = backupRepoType; + } + + public String getBackupRepoAddress() { + return backupRepoAddress; + } + + public void setBackupRepoAddress(String backupRepoAddress) { + this.backupRepoAddress = backupRepoAddress; + } + + public List getVolumePaths() { + return volumePaths; + } + + public void setVolumePaths(List volumePaths) { + this.volumePaths = volumePaths; + } + + public Boolean isVmExists() { + return vmExists; + } + + public void setVmExists(Boolean vmExists) { + this.vmExists = vmExists; + } + + public String getDiskType() { + return diskType; + } + + public void setDiskType(String diskType) { + this.diskType = diskType; + } + + public String getMountOptions() { + return mountOptions; + } + + public void setMountOptions(String mountOptions) { + this.mountOptions = mountOptions; + } + + public String getRestoreVolumeUUID() { + return restoreVolumeUUID; + } + + public void setRestoreVolumeUUID(String restoreVolumeUUID) { + this.restoreVolumeUUID = restoreVolumeUUID; + } + + public VirtualMachine.State getVmState() { + return vmState; + } + + public void setVmState(VirtualMachine.State vmState) { + this.vmState = vmState; + } + + @LogLevel(LogLevel.Log4jLevel.Off) + private String mountOptions; + @Override + + public boolean executeInSequence() { + return true; + } +} diff --git a/core/src/main/java/org/apache/cloudstack/backup/TakeBackupCommand.java b/core/src/main/java/org/apache/cloudstack/backup/TakeBackupCommand.java new file mode 100644 index 00000000000..93855ea1721 --- /dev/null +++ b/core/src/main/java/org/apache/cloudstack/backup/TakeBackupCommand.java @@ -0,0 +1,94 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +// + +package org.apache.cloudstack.backup; + +import com.cloud.agent.api.Command; +import com.cloud.agent.api.LogLevel; + +import java.util.List; + +public class TakeBackupCommand extends Command { + private String vmName; + private String backupPath; + private String backupRepoType; + private String backupRepoAddress; + private List volumePaths; + @LogLevel(LogLevel.Log4jLevel.Off) + private String mountOptions; + + public TakeBackupCommand(String vmName, String backupPath) { + super(); + this.vmName = vmName; + this.backupPath = backupPath; + } + + public String getVmName() { + return vmName; + } + + public void setVmName(String vmName) { + this.vmName = vmName; + } + + public String getBackupPath() { + return backupPath; + } + + public void setBackupPath(String backupPath) { + this.backupPath = backupPath; + } + + public String getBackupRepoType() { + return backupRepoType; + } + + public void setBackupRepoType(String backupRepoType) { + this.backupRepoType = backupRepoType; + } + + public String getBackupRepoAddress() { + return backupRepoAddress; + } + + public void setBackupRepoAddress(String backupRepoAddress) { + this.backupRepoAddress = backupRepoAddress; + } + + public String getMountOptions() { + return mountOptions; + } + + public void setMountOptions(String mountOptions) { + this.mountOptions = mountOptions; + } + + public List getVolumePaths() { + return volumePaths; + } + + public void setVolumePaths(List volumePaths) { + this.volumePaths = volumePaths; + } + + @Override + public boolean executeInSequence() { + return true; + } +} diff --git a/core/src/main/java/org/apache/cloudstack/diagnostics/DiagnosticsAnswer.java b/core/src/main/java/org/apache/cloudstack/diagnostics/DiagnosticsAnswer.java index 7390e4fcdd2..6421f45ed0a 100644 --- a/core/src/main/java/org/apache/cloudstack/diagnostics/DiagnosticsAnswer.java +++ b/core/src/main/java/org/apache/cloudstack/diagnostics/DiagnosticsAnswer.java @@ -21,13 +21,11 @@ import com.cloud.agent.api.Answer; import com.cloud.utils.exception.CloudRuntimeException; import org.apache.commons.lang3.StringUtils; import org.apache.cloudstack.api.ApiConstants; -import org.apache.log4j.Logger; import java.util.HashMap; import java.util.Map; public class DiagnosticsAnswer extends Answer { - public static final Logger LOGGER = Logger.getLogger(DiagnosticsAnswer.class); public DiagnosticsAnswer(DiagnosticsCommand cmd, boolean result, String details) { super(cmd, result, details); diff --git a/core/src/main/java/org/apache/cloudstack/direct/download/DirectDownloadHelper.java b/core/src/main/java/org/apache/cloudstack/direct/download/DirectDownloadHelper.java index a00274e259e..0e0e2f0b57b 100644 --- a/core/src/main/java/org/apache/cloudstack/direct/download/DirectDownloadHelper.java +++ b/core/src/main/java/org/apache/cloudstack/direct/download/DirectDownloadHelper.java @@ -24,11 +24,12 @@ import org.apache.cloudstack.agent.directdownload.HttpDirectDownloadCommand; import org.apache.cloudstack.agent.directdownload.HttpsDirectDownloadCommand; import org.apache.cloudstack.agent.directdownload.MetalinkDirectDownloadCommand; import org.apache.cloudstack.agent.directdownload.NfsDirectDownloadCommand; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class DirectDownloadHelper { - public static final Logger LOGGER = Logger.getLogger(DirectDownloadHelper.class.getName()); + protected static Logger LOGGER = LogManager.getLogger(DirectDownloadHelper.class); /** * Get direct template downloader from direct download command and destination pool diff --git a/core/src/main/java/org/apache/cloudstack/direct/download/DirectTemplateDownloaderImpl.java b/core/src/main/java/org/apache/cloudstack/direct/download/DirectTemplateDownloaderImpl.java index 9431b8209b3..d22c803818b 100644 --- a/core/src/main/java/org/apache/cloudstack/direct/download/DirectTemplateDownloaderImpl.java +++ b/core/src/main/java/org/apache/cloudstack/direct/download/DirectTemplateDownloaderImpl.java @@ -22,7 +22,8 @@ import com.cloud.utils.UriUtils; import com.cloud.utils.exception.CloudRuntimeException; import org.apache.cloudstack.utils.security.DigestHelper; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import java.io.File; import java.io.FileInputStream; @@ -44,7 +45,7 @@ public abstract class DirectTemplateDownloaderImpl implements DirectTemplateDown protected String temporaryDownloadPath; private boolean followRedirects; - public static final Logger s_logger = Logger.getLogger(DirectTemplateDownloaderImpl.class.getName()); + protected Logger logger = LogManager.getLogger(getClass()); protected DirectTemplateDownloaderImpl(final String url, final String destPoolPath, final Long templateId, final String checksum, final String temporaryDownloadPath, @@ -146,16 +147,16 @@ public abstract class DirectTemplateDownloaderImpl implements DirectTemplateDown try { while (!valid && retry > 0) { retry--; - s_logger.info("Performing checksum validation for downloaded template " + templateId + " using " + checksum + ", retries left: " + retry); + logger.info("Performing checksum validation for downloaded template " + templateId + " using " + checksum + ", retries left: " + retry); valid = DigestHelper.check(checksum, new FileInputStream(downloadedFilePath)); if (!valid && retry > 0) { - s_logger.info("Checksum validation failed, re-downloading template"); + logger.info("Checksum validation failed, re-downloading template"); redownload = true; resetDownloadFile(); downloadTemplate(); } } - s_logger.info("Checksum validation for template " + templateId + ": " + (valid ? "succeeded" : "failed")); + logger.info("Checksum validation for template " + templateId + ": " + (valid ? "succeeded" : "failed")); return valid; } catch (IOException e) { throw new CloudRuntimeException("could not check sum for file: " + downloadedFilePath, e); @@ -163,7 +164,7 @@ public abstract class DirectTemplateDownloaderImpl implements DirectTemplateDown throw new CloudRuntimeException("Unknown checksum algorithm: " + checksum, e); } } - s_logger.info("No checksum provided, skipping checksum validation"); + logger.info("No checksum provided, skipping checksum validation"); return true; } @@ -172,14 +173,14 @@ public abstract class DirectTemplateDownloaderImpl implements DirectTemplateDown */ private void resetDownloadFile() { File f = new File(getDownloadedFilePath()); - s_logger.info("Resetting download file: " + getDownloadedFilePath() + ", in order to re-download and persist template " + templateId + " on it"); + logger.info("Resetting download file: " + getDownloadedFilePath() + ", in order to re-download and persist template " + templateId + " on it"); try { if (f.exists()) { f.delete(); } f.createNewFile(); } catch (IOException e) { - s_logger.error("Error creating file to download on: " + getDownloadedFilePath() + " due to: " + e.getMessage()); + logger.error("Error creating file to download on: " + getDownloadedFilePath() + " due to: " + e.getMessage()); throw new CloudRuntimeException("Failed to create download file for direct download"); } } diff --git a/core/src/main/java/org/apache/cloudstack/direct/download/HttpDirectTemplateDownloader.java b/core/src/main/java/org/apache/cloudstack/direct/download/HttpDirectTemplateDownloader.java index 068f6b08418..8c4147fad60 100644 --- a/core/src/main/java/org/apache/cloudstack/direct/download/HttpDirectTemplateDownloader.java +++ b/core/src/main/java/org/apache/cloudstack/direct/download/HttpDirectTemplateDownloader.java @@ -40,13 +40,11 @@ import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.io.IOUtils; -import org.apache.log4j.Logger; public class HttpDirectTemplateDownloader extends DirectTemplateDownloaderImpl { protected HttpClient client; private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); - public static final Logger s_logger = Logger.getLogger(HttpDirectTemplateDownloader.class.getName()); protected GetMethod request; protected Map reqHeaders = new HashMap<>(); @@ -84,7 +82,7 @@ public class HttpDirectTemplateDownloader extends DirectTemplateDownloaderImpl { try { int status = client.executeMethod(request); if (status != HttpStatus.SC_OK) { - s_logger.warn("Not able to download template, status code: " + status); + logger.warn("Not able to download template, status code: " + status); return new Pair<>(false, null); } return performDownload(); @@ -96,14 +94,14 @@ public class HttpDirectTemplateDownloader extends DirectTemplateDownloaderImpl { } protected Pair performDownload() { - s_logger.info("Downloading template " + getTemplateId() + " from " + getUrl() + " to: " + getDownloadedFilePath()); + logger.info("Downloading template " + getTemplateId() + " from " + getUrl() + " to: " + getDownloadedFilePath()); try ( InputStream in = request.getResponseBodyAsStream(); OutputStream out = new FileOutputStream(getDownloadedFilePath()) ) { IOUtils.copy(in, out); } catch (IOException e) { - s_logger.error("Error downloading template " + getTemplateId() + " due to: " + e.getMessage()); + logger.error("Error downloading template " + getTemplateId() + " due to: " + e.getMessage()); return new Pair<>(false, null); } return new Pair<>(true, getDownloadedFilePath()); @@ -116,12 +114,12 @@ public class HttpDirectTemplateDownloader extends DirectTemplateDownloaderImpl { try { int responseCode = client.executeMethod(httpHead); if (responseCode != HttpStatus.SC_OK) { - s_logger.error(String.format("HTTP HEAD request to URL: %s failed, response code: %d", url, responseCode)); + logger.error(String.format("HTTP HEAD request to URL: %s failed, response code: %d", url, responseCode)); return false; } return true; } catch (IOException e) { - s_logger.error(String.format("Cannot reach URL: %s due to: %s", url, e.getMessage()), e); + logger.error(String.format("Cannot reach URL: %s due to: %s", url, e.getMessage()), e); return false; } finally { httpHead.releaseConnection(); @@ -145,7 +143,7 @@ public class HttpDirectTemplateDownloader extends DirectTemplateDownloaderImpl { try { status = client.executeMethod(getMethod); } catch (IOException e) { - s_logger.error("Error retrieving urls form metalink: " + metalinkUrl); + logger.error("Error retrieving urls form metalink: " + metalinkUrl); getMethod.releaseConnection(); return null; } @@ -155,7 +153,7 @@ public class HttpDirectTemplateDownloader extends DirectTemplateDownloaderImpl { addMetalinkUrlsToListFromInputStream(is, urls); } } catch (IOException e) { - s_logger.warn(e.getMessage()); + logger.warn(e.getMessage()); } finally { getMethod.releaseConnection(); } @@ -171,7 +169,7 @@ public class HttpDirectTemplateDownloader extends DirectTemplateDownloaderImpl { return generateChecksumListFromInputStream(is); } } catch (IOException e) { - s_logger.error(String.format("Error obtaining metalink checksums on URL %s: %s", metalinkUrl, e.getMessage()), e); + logger.error(String.format("Error obtaining metalink checksums on URL %s: %s", metalinkUrl, e.getMessage()), e); } finally { getMethod.releaseConnection(); } diff --git a/core/src/main/java/org/apache/cloudstack/direct/download/HttpsDirectTemplateDownloader.java b/core/src/main/java/org/apache/cloudstack/direct/download/HttpsDirectTemplateDownloader.java index e3c74213d74..338eb773257 100644 --- a/core/src/main/java/org/apache/cloudstack/direct/download/HttpsDirectTemplateDownloader.java +++ b/core/src/main/java/org/apache/cloudstack/direct/download/HttpsDirectTemplateDownloader.java @@ -124,7 +124,7 @@ public class HttpsDirectTemplateDownloader extends DirectTemplateDownloaderImpl .loadTrustMaterial(defaultKeystore, null) .build(); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | KeyManagementException e) { - s_logger.error(String.format("Failure getting SSL context for HTTPS downloader, using default SSL context: %s", e.getMessage()), e); + logger.error(String.format("Failure getting SSL context for HTTPS downloader, using default SSL context: %s", e.getMessage()), e); try { return SSLContext.getDefault(); } catch (NoSuchAlgorithmException ex) { @@ -149,7 +149,7 @@ public class HttpsDirectTemplateDownloader extends DirectTemplateDownloaderImpl * Consume response and persist it on getDownloadedFilePath() file */ protected Pair consumeResponse(CloseableHttpResponse response) { - s_logger.info("Downloading template " + getTemplateId() + " from " + getUrl() + " to: " + getDownloadedFilePath()); + logger.info("Downloading template " + getTemplateId() + " from " + getUrl() + " to: " + getDownloadedFilePath()); if (response.getStatusLine().getStatusCode() != 200) { throw new CloudRuntimeException("Error on HTTPS response"); } @@ -159,7 +159,7 @@ public class HttpsDirectTemplateDownloader extends DirectTemplateDownloaderImpl OutputStream out = new FileOutputStream(getDownloadedFilePath()); IOUtils.copy(in, out); } catch (Exception e) { - s_logger.error("Error parsing response for template " + getTemplateId() + " due to: " + e.getMessage()); + logger.error("Error parsing response for template " + getTemplateId() + " due to: " + e.getMessage()); return new Pair<>(false, null); } return new Pair<>(true, getDownloadedFilePath()); @@ -172,12 +172,12 @@ public class HttpsDirectTemplateDownloader extends DirectTemplateDownloaderImpl CloseableHttpResponse response = httpsClient.execute(httpHead); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != HttpStatus.SC_OK) { - s_logger.error(String.format("HTTP HEAD request to URL: %s failed, response code: %d", url, responseCode)); + logger.error(String.format("HTTP HEAD request to URL: %s failed, response code: %d", url, responseCode)); return false; } return true; } catch (IOException e) { - s_logger.error(String.format("Cannot reach URL: %s due to: %s", url, e.getMessage()), e); + logger.error(String.format("Cannot reach URL: %s due to: %s", url, e.getMessage()), e); return false; } finally { httpHead.releaseConnection(); @@ -222,11 +222,11 @@ public class HttpsDirectTemplateDownloader extends DirectTemplateDownloaderImpl response = httpsClient.execute(getMethod); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String msg = String.format("Cannot access metalink content on URL %s", metalinkUrl); - s_logger.error(msg); + logger.error(msg); throw new IOException(msg); } } catch (IOException e) { - s_logger.error(String.format("Error retrieving urls form metalink URL %s: %s", metalinkUrl, e.getMessage()), e); + logger.error(String.format("Error retrieving urls form metalink URL %s: %s", metalinkUrl, e.getMessage()), e); getMethod.releaseConnection(); return null; } @@ -236,7 +236,7 @@ public class HttpsDirectTemplateDownloader extends DirectTemplateDownloaderImpl ByteArrayInputStream inputStream = new ByteArrayInputStream(responseStr.getBytes(StandardCharsets.UTF_8)); addMetalinkUrlsToListFromInputStream(inputStream, urls); } catch (IOException e) { - s_logger.warn(e.getMessage(), e); + logger.warn(e.getMessage(), e); } finally { getMethod.releaseConnection(); } @@ -253,7 +253,7 @@ public class HttpsDirectTemplateDownloader extends DirectTemplateDownloaderImpl return generateChecksumListFromInputStream(is); } } catch (IOException e) { - s_logger.error(String.format("Error obtaining metalink checksums on URL %s: %s", metalinkUrl, e.getMessage()), e); + logger.error(String.format("Error obtaining metalink checksums on URL %s: %s", metalinkUrl, e.getMessage()), e); } finally { getMethod.releaseConnection(); } diff --git a/core/src/main/java/org/apache/cloudstack/direct/download/MetalinkDirectTemplateDownloader.java b/core/src/main/java/org/apache/cloudstack/direct/download/MetalinkDirectTemplateDownloader.java index 86b97880a85..5335da99150 100644 --- a/core/src/main/java/org/apache/cloudstack/direct/download/MetalinkDirectTemplateDownloader.java +++ b/core/src/main/java/org/apache/cloudstack/direct/download/MetalinkDirectTemplateDownloader.java @@ -23,7 +23,6 @@ import com.cloud.utils.exception.CloudRuntimeException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import java.io.File; import java.util.List; @@ -39,8 +38,6 @@ public class MetalinkDirectTemplateDownloader extends DirectTemplateDownloaderIm private Integer connectTimeout; private Integer soTimeout; - private static final Logger s_logger = Logger.getLogger(MetalinkDirectTemplateDownloader.class.getName()); - protected DirectTemplateDownloader createDownloaderForMetalinks(String url, Long templateId, String destPoolPath, String checksum, Map headers, Integer connectTimeout, Integer soTimeout, Integer connectionRequestTimeout, String temporaryDownloadPath) { @@ -54,7 +51,7 @@ public class MetalinkDirectTemplateDownloader extends DirectTemplateDownloaderIm } else if (url.toLowerCase().startsWith("nfs:")) { return new NfsDirectTemplateDownloader(url); } else { - s_logger.error(String.format("Cannot find a suitable downloader to handle the metalink URL %s", url)); + logger.error(String.format("Cannot find a suitable downloader to handle the metalink URL %s", url)); return null; } } @@ -75,10 +72,10 @@ public class MetalinkDirectTemplateDownloader extends DirectTemplateDownloaderIm metalinkUrls = downloader.getMetalinkUrls(url); metalinkChecksums = downloader.getMetalinkChecksums(url); if (CollectionUtils.isEmpty(metalinkUrls)) { - s_logger.error(String.format("No urls found on metalink file: %s. Not possible to download template %s ", url, templateId)); + logger.error(String.format("No urls found on metalink file: %s. Not possible to download template %s ", url, templateId)); } else { setUrl(metalinkUrls.get(0)); - s_logger.info("Metalink downloader created, metalink url: " + url + " parsed - " + + logger.info("Metalink downloader created, metalink url: " + url + " parsed - " + metalinkUrls.size() + " urls and " + (CollectionUtils.isNotEmpty(metalinkChecksums) ? metalinkChecksums.size() : "0") + " checksums found"); } @@ -96,7 +93,7 @@ public class MetalinkDirectTemplateDownloader extends DirectTemplateDownloaderIm if (!isRedownload()) { setUrl(metalinkUrls.get(i)); } - s_logger.info("Trying to download template from url: " + getUrl()); + logger.info("Trying to download template from url: " + getUrl()); DirectTemplateDownloader urlDownloader = createDownloaderForMetalinks(getUrl(), getTemplateId(), getDestPoolPath(), getChecksum(), headers, connectTimeout, soTimeout, null, temporaryDownloadPath); try { @@ -109,10 +106,10 @@ public class MetalinkDirectTemplateDownloader extends DirectTemplateDownloaderIm Pair downloadResult = urlDownloader.downloadTemplate(); downloaded = downloadResult.first(); if (downloaded) { - s_logger.info("Successfully downloaded template from url: " + getUrl()); + logger.info("Successfully downloaded template from url: " + getUrl()); } } catch (Exception e) { - s_logger.error(String.format("Error downloading template: %s from URL: %s due to: %s", getTemplateId(), getUrl(), e.getMessage()), e); + logger.error(String.format("Error downloading template: %s from URL: %s due to: %s", getTemplateId(), getUrl(), e.getMessage()), e); } i++; } @@ -125,7 +122,7 @@ public class MetalinkDirectTemplateDownloader extends DirectTemplateDownloaderIm if (StringUtils.isBlank(getChecksum()) && CollectionUtils.isNotEmpty(metalinkChecksums)) { String chk = metalinkChecksums.get(random.nextInt(metalinkChecksums.size())); setChecksum(chk); - s_logger.info("Checksum not provided but " + metalinkChecksums.size() + " found on metalink file, performing checksum using one of them: " + chk); + logger.info("Checksum not provided but " + metalinkChecksums.size() + " found on metalink file, performing checksum using one of them: " + chk); } return super.validateChecksum(); } @@ -133,7 +130,7 @@ public class MetalinkDirectTemplateDownloader extends DirectTemplateDownloaderIm @Override public boolean checkUrl(String metalinkUrl) { if (!downloader.checkUrl(metalinkUrl)) { - s_logger.error(String.format("Metalink URL check failed for: %s", metalinkUrl)); + logger.error(String.format("Metalink URL check failed for: %s", metalinkUrl)); return false; } diff --git a/core/src/main/java/org/apache/cloudstack/direct/download/NfsDirectTemplateDownloader.java b/core/src/main/java/org/apache/cloudstack/direct/download/NfsDirectTemplateDownloader.java index e5ff533cc97..21184ef07fe 100644 --- a/core/src/main/java/org/apache/cloudstack/direct/download/NfsDirectTemplateDownloader.java +++ b/core/src/main/java/org/apache/cloudstack/direct/download/NfsDirectTemplateDownloader.java @@ -81,7 +81,7 @@ public class NfsDirectTemplateDownloader extends DirectTemplateDownloaderImpl { parseUrl(); return true; } catch (CloudRuntimeException e) { - s_logger.error(String.format("Cannot check URL %s is reachable due to: %s", url, e.getMessage()), e); + logger.error(String.format("Cannot check URL %s is reachable due to: %s", url, e.getMessage()), e); return false; } } diff --git a/core/src/main/java/org/apache/cloudstack/storage/to/ImageStoreTO.java b/core/src/main/java/org/apache/cloudstack/storage/to/ImageStoreTO.java index 046a2ab9410..4bf29205673 100644 --- a/core/src/main/java/org/apache/cloudstack/storage/to/ImageStoreTO.java +++ b/core/src/main/java/org/apache/cloudstack/storage/to/ImageStoreTO.java @@ -23,6 +23,7 @@ import org.apache.cloudstack.storage.image.datastore.ImageStoreInfo; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.storage.DataStoreRole; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public class ImageStoreTO implements DataStoreTO { private String type; @@ -78,15 +79,9 @@ public class ImageStoreTO implements DataStoreTO { @Override public String toString() { - return new StringBuilder("ImageStoreTO[type=").append(type) - .append("|provider=") - .append(providerName) - .append("|role=") - .append(role) - .append("|uri=") - .append(uri) - .append("]") - .toString(); + return String.format("ImageStoreTO %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "uuid", "type", "providerName", "role", "uri")); } @Override diff --git a/core/src/main/java/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java b/core/src/main/java/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java index a6a74176c13..2c758fa5087 100644 --- a/core/src/main/java/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java +++ b/core/src/main/java/org/apache/cloudstack/storage/to/PrimaryDataStoreTO.java @@ -26,6 +26,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.storage.DataStoreRole; import com.cloud.storage.Storage.StoragePoolType; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public class PrimaryDataStoreTO implements DataStoreTO { public static final String MANAGED = PrimaryDataStore.MANAGED; @@ -145,15 +146,9 @@ public class PrimaryDataStoreTO implements DataStoreTO { @Override public String toString() { - return new StringBuilder("PrimaryDataStoreTO[uuid=").append(uuid) - .append("|name=") - .append(name) - .append("|id=") - .append(id) - .append("|pooltype=") - .append(poolType) - .append("]") - .toString(); + return String.format("PrimaryDataStoreTO %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "poolType")); } public Boolean isFullCloneFlag() { diff --git a/core/src/main/java/org/apache/cloudstack/storage/to/TemplateObjectTO.java b/core/src/main/java/org/apache/cloudstack/storage/to/TemplateObjectTO.java index eafe8f83269..dc68b31a3fd 100644 --- a/core/src/main/java/org/apache/cloudstack/storage/to/TemplateObjectTO.java +++ b/core/src/main/java/org/apache/cloudstack/storage/to/TemplateObjectTO.java @@ -27,6 +27,7 @@ import com.cloud.agent.api.to.DataTO; import com.cloud.hypervisor.Hypervisor; import com.cloud.storage.Storage.ImageFormat; import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public class TemplateObjectTO extends DownloadableObjectTO implements DataTO { private String path; @@ -264,6 +265,8 @@ public class TemplateObjectTO extends DownloadableObjectTO implements DataTO { @Override public String toString() { - return new StringBuilder("TemplateTO[id=").append(id).append("|origUrl=").append(origUrl).append("|name").append(name).append("]").toString(); + return String.format("TemplateTO %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "origUrl")); } } diff --git a/core/src/main/java/org/apache/cloudstack/storage/to/VolumeObjectTO.java b/core/src/main/java/org/apache/cloudstack/storage/to/VolumeObjectTO.java index 6514038ac62..4d1d0bf9097 100644 --- a/core/src/main/java/org/apache/cloudstack/storage/to/VolumeObjectTO.java +++ b/core/src/main/java/org/apache/cloudstack/storage/to/VolumeObjectTO.java @@ -30,6 +30,7 @@ import com.cloud.offering.DiskOffering.DiskCacheMode; import com.cloud.storage.MigrationOptions; import com.cloud.storage.Storage; import com.cloud.storage.Volume; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import java.util.Arrays; @@ -258,7 +259,9 @@ public class VolumeObjectTO extends DownloadableObjectTO implements DataTO { @Override public String toString() { - return new StringBuilder("volumeTO[uuid=").append(uuid).append("|path=").append(path).append("|datastore=").append(dataStore).append("]").toString(); + return String.format("volumeTO %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "path", "dataStore")); } public void setBytesReadRate(Long bytesReadRate) { diff --git a/core/src/main/java/org/apache/cloudstack/transport/HypervisorTypeAdaptor.java b/core/src/main/java/org/apache/cloudstack/transport/HypervisorTypeAdaptor.java new file mode 100644 index 00000000000..bc4d3c3a6e3 --- /dev/null +++ b/core/src/main/java/org/apache/cloudstack/transport/HypervisorTypeAdaptor.java @@ -0,0 +1,53 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.transport; + +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; + +/** + * {@link HypervisorType} acts as extendable set of singleton objects and should return same result when used "==" + * or {@link Object#equals(Object)}. + * To support that, need to return existing object for a given name instead of creating new. + */ +public class HypervisorTypeAdaptor implements JsonDeserializer, JsonSerializer { + @Override + public HypervisorType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + if (json instanceof JsonPrimitive && ((JsonPrimitive) json).isString()) { + return HypervisorType.valueOf(json.getAsString()); + } + return null; + } + + @Override + public JsonElement serialize(HypervisorType src, Type typeOfSrc, JsonSerializationContext context) { + String name = src.name(); + if (name == null) { + return new JsonNull(); + } + return new JsonPrimitive(name); + } +} diff --git a/core/src/main/resources/META-INF/cloudstack/allocator/spring-core-allocator-context.xml b/core/src/main/resources/META-INF/cloudstack/allocator/spring-core-allocator-context.xml index a0d1b4cfd43..9f04a7fb618 100644 --- a/core/src/main/resources/META-INF/cloudstack/allocator/spring-core-allocator-context.xml +++ b/core/src/main/resources/META-INF/cloudstack/allocator/spring-core-allocator-context.xml @@ -27,7 +27,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" - > + > diff --git a/core/src/main/resources/META-INF/cloudstack/allocator/spring-core-lifecycle-allocator-context-inheritable.xml b/core/src/main/resources/META-INF/cloudstack/allocator/spring-core-lifecycle-allocator-context-inheritable.xml index ec3bb63aeb6..6d05f858303 100644 --- a/core/src/main/resources/META-INF/cloudstack/allocator/spring-core-lifecycle-allocator-context-inheritable.xml +++ b/core/src/main/resources/META-INF/cloudstack/allocator/spring-core-lifecycle-allocator-context-inheritable.xml @@ -27,7 +27,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" - > + > diff --git a/core/src/main/resources/META-INF/cloudstack/api/spring-core-lifecycle-api-context-inheritable.xml b/core/src/main/resources/META-INF/cloudstack/api/spring-core-lifecycle-api-context-inheritable.xml index 91a35f18a89..995ed30eb5e 100644 --- a/core/src/main/resources/META-INF/cloudstack/api/spring-core-lifecycle-api-context-inheritable.xml +++ b/core/src/main/resources/META-INF/cloudstack/api/spring-core-lifecycle-api-context-inheritable.xml @@ -62,12 +62,12 @@ - + - + diff --git a/core/src/main/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml b/core/src/main/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml index dbca5deb739..01c568d7891 100644 --- a/core/src/main/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml +++ b/core/src/main/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml @@ -262,7 +262,7 @@ - + @@ -276,11 +276,11 @@ class="org.apache.cloudstack.spring.lifecycle.registry.ExtensionRegistry"> - + - + @@ -288,10 +288,10 @@ + class="org.apache.cloudstack.spring.lifecycle.registry.ExtensionRegistry"> - + @@ -350,4 +350,20 @@ + + + + + + + + + + + + + + + diff --git a/packaging/centos8/cloud.limits b/core/src/main/resources/META-INF/cloudstack/event/module.properties similarity index 94% rename from packaging/centos8/cloud.limits rename to core/src/main/resources/META-INF/cloudstack/event/module.properties index 7debeb29018..ab1f88e9844 100644 --- a/packaging/centos8/cloud.limits +++ b/core/src/main/resources/META-INF/cloudstack/event/module.properties @@ -1,3 +1,4 @@ +# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information @@ -14,6 +15,7 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +# -cloud hard nofile 4096 -cloud soft nofile 4096 +name=event +parent=core diff --git a/core/src/main/resources/META-INF/cloudstack/event/spring-core-lifecycle-event-context-inheritable.xml b/core/src/main/resources/META-INF/cloudstack/event/spring-core-lifecycle-event-context-inheritable.xml new file mode 100644 index 00000000000..63d11c65bac --- /dev/null +++ b/core/src/main/resources/META-INF/cloudstack/event/spring-core-lifecycle-event-context-inheritable.xml @@ -0,0 +1,31 @@ + + + + + + + + diff --git a/core/src/main/resources/META-INF/cloudstack/network/spring-core-lifecycle-network-context-inheritable.xml b/core/src/main/resources/META-INF/cloudstack/network/spring-core-lifecycle-network-context-inheritable.xml index 8dbaf610581..e5c232267ae 100644 --- a/core/src/main/resources/META-INF/cloudstack/network/spring-core-lifecycle-network-context-inheritable.xml +++ b/core/src/main/resources/META-INF/cloudstack/network/spring-core-lifecycle-network-context-inheritable.xml @@ -92,7 +92,7 @@ - + + + + + + diff --git a/core/src/main/resources/META-INF/cloudstack/storage/spring-lifecycle-storage-context-inheritable.xml b/core/src/main/resources/META-INF/cloudstack/storage/spring-lifecycle-storage-context-inheritable.xml index 2771dfe415f..a1c9055fd70 100644 --- a/core/src/main/resources/META-INF/cloudstack/storage/spring-lifecycle-storage-context-inheritable.xml +++ b/core/src/main/resources/META-INF/cloudstack/storage/spring-lifecycle-storage-context-inheritable.xml @@ -52,7 +52,7 @@ - + - - + + + + + diff --git a/core/src/main/resources/META-INF/cloudstack/system/spring-core-system-context-inheritable.xml b/core/src/main/resources/META-INF/cloudstack/system/spring-core-system-context-inheritable.xml index 4a59e95de35..89442fc12b4 100644 --- a/core/src/main/resources/META-INF/cloudstack/system/spring-core-system-context-inheritable.xml +++ b/core/src/main/resources/META-INF/cloudstack/system/spring-core-system-context-inheritable.xml @@ -27,7 +27,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" - > + > @@ -44,8 +44,8 @@ - - diff --git a/core/src/test/java/com/cloud/agent/api/GetStorageStatsAnswerTest.java b/core/src/test/java/com/cloud/agent/api/GetStorageStatsAnswerTest.java new file mode 100644 index 00000000000..44af83ada2d --- /dev/null +++ b/core/src/test/java/com/cloud/agent/api/GetStorageStatsAnswerTest.java @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.agent.api; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class GetStorageStatsAnswerTest { + + @Test + public void testDefaultConstructor() { + GetStorageStatsAnswer answer = new GetStorageStatsAnswer(); + + Assert.assertEquals(0, answer.getByteUsed()); + Assert.assertEquals(0, answer.getCapacityBytes()); + Assert.assertNull(answer.getCapacityIops()); + Assert.assertNull(answer.getUsedIops()); + } + + @Test + public void testConstructorWithCapacityAndUsedBytes() { + GetStorageStatsCommand mockCmd = new GetStorageStatsCommand(); + long capacityBytes = 1024L; + long usedBytes = 512L; + + GetStorageStatsAnswer answer = new GetStorageStatsAnswer(mockCmd, capacityBytes, usedBytes); + + Assert.assertEquals(capacityBytes, answer.getCapacityBytes()); + Assert.assertEquals(usedBytes, answer.getByteUsed()); + Assert.assertNull(answer.getCapacityIops()); + Assert.assertNull(answer.getUsedIops()); + } + + @Test + public void testConstructorWithIops() { + GetStorageStatsCommand mockCmd = new GetStorageStatsCommand(); + long capacityBytes = 2048L; + long usedBytes = 1024L; + Long capacityIops = 1000L; + Long usedIops = 500L; + + GetStorageStatsAnswer answer = new GetStorageStatsAnswer(mockCmd, capacityBytes, usedBytes, capacityIops, usedIops); + + Assert.assertEquals(capacityBytes, answer.getCapacityBytes()); + Assert.assertEquals(usedBytes, answer.getByteUsed()); + Assert.assertEquals(capacityIops, answer.getCapacityIops()); + Assert.assertEquals(usedIops, answer.getUsedIops()); + } + + @Test + public void testErrorConstructor() { + GetStorageStatsCommand mockCmd = new GetStorageStatsCommand(); + String errorDetails = "An error occurred"; + + GetStorageStatsAnswer answer = new GetStorageStatsAnswer(mockCmd, errorDetails); + + Assert.assertFalse(answer.getResult()); + Assert.assertEquals(errorDetails, answer.getDetails()); + Assert.assertEquals(0, answer.getCapacityBytes()); + Assert.assertEquals(0, answer.getByteUsed()); + Assert.assertNull(answer.getCapacityIops()); + Assert.assertNull(answer.getUsedIops()); + } +} diff --git a/core/src/test/java/com/cloud/agent/api/SecurityGroupRulesCmdTest.java b/core/src/test/java/com/cloud/agent/api/SecurityGroupRulesCmdTest.java index 50c82a76455..1ce3cfb06b9 100644 --- a/core/src/test/java/com/cloud/agent/api/SecurityGroupRulesCmdTest.java +++ b/core/src/test/java/com/cloud/agent/api/SecurityGroupRulesCmdTest.java @@ -27,7 +27,7 @@ import java.util.Vector; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto; diff --git a/core/src/test/java/com/cloud/agent/api/routing/SetBgpPeersAnswerTest.java b/core/src/test/java/com/cloud/agent/api/routing/SetBgpPeersAnswerTest.java new file mode 100644 index 00000000000..4cd15e4465a --- /dev/null +++ b/core/src/test/java/com/cloud/agent/api/routing/SetBgpPeersAnswerTest.java @@ -0,0 +1,54 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.agent.api.routing; + +import org.apache.cloudstack.network.BgpPeerTO; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.List; + +public class SetBgpPeersAnswerTest { + + @Test + public void testSetBgpPeersAnswer() { + + String good = "good"; + String[] results = new String[1]; + results[0] = good; + + BgpPeerTO bgpPeerTO = Mockito.mock(BgpPeerTO.class); + List bgpPeerTOs = new ArrayList<>(); + bgpPeerTOs.add(bgpPeerTO); + SetBgpPeersCommand command = new SetBgpPeersCommand(bgpPeerTOs); + + SetBgpPeersAnswer answer = new SetBgpPeersAnswer(command, true, results); + + Assert.assertNotNull(answer.getResults()); + Assert.assertEquals(1, answer.getResults().length); + Assert.assertEquals(good, answer.getResults()[0]); + } + + @Test + public void testSetBgpPeersAnswer2() { + SetBgpPeersAnswer answer = new SetBgpPeersAnswer(); + + Assert.assertNull(answer.getResults()); + } +} diff --git a/core/src/test/java/com/cloud/agent/api/routing/SetBgpPeersCommandTest.java b/core/src/test/java/com/cloud/agent/api/routing/SetBgpPeersCommandTest.java new file mode 100644 index 00000000000..882c3b9da30 --- /dev/null +++ b/core/src/test/java/com/cloud/agent/api/routing/SetBgpPeersCommandTest.java @@ -0,0 +1,47 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.agent.api.routing; + +import org.apache.cloudstack.network.BgpPeerTO; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.List; + +public class SetBgpPeersCommandTest { + + @Test + public void testSetBgpPeersCommand1() { + SetBgpPeersCommand command = new SetBgpPeersCommand(); + Assert.assertNull(command.getBpgPeers()); + } + + @Test + public void testSetBgpPeersCommand2() { + BgpPeerTO bgpPeerTO = Mockito.mock(BgpPeerTO.class); + + List bgpPeerTOs = new ArrayList<>(); + bgpPeerTOs.add(bgpPeerTO); + + SetBgpPeersCommand command = new SetBgpPeersCommand(bgpPeerTOs); + Assert.assertNotNull(command.getBpgPeers()); + Assert.assertEquals(1, command.getBpgPeers().length); + Assert.assertEquals(bgpPeerTO, command.getBpgPeers()[0]); + } +} diff --git a/core/src/test/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersConfigItemTest.java b/core/src/test/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersConfigItemTest.java new file mode 100644 index 00000000000..5f177c88abf --- /dev/null +++ b/core/src/test/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersConfigItemTest.java @@ -0,0 +1,56 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.agent.resource.virtualnetwork.facade; + +import com.cloud.agent.api.routing.SetBgpPeersCommand; +import com.cloud.agent.resource.virtualnetwork.ConfigItem; +import com.cloud.agent.resource.virtualnetwork.FileConfigItem; +import com.cloud.agent.resource.virtualnetwork.ScriptConfigItem; +import com.cloud.agent.resource.virtualnetwork.VRScripts; + +import org.apache.cloudstack.network.BgpPeerTO; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.List; + +public class SetBgpPeersConfigItemTest { + + + @Test + public void testSetBgpPeersConfigItem() { + BgpPeerTO bgpPeerTO = Mockito.mock(BgpPeerTO.class); + List bgpPeerTOs = new ArrayList<>(); + bgpPeerTOs.add(bgpPeerTO); + SetBgpPeersCommand command = new SetBgpPeersCommand(bgpPeerTOs); + + SetBgpPeersConfigItem setBgpPeersConfigItem = new SetBgpPeersConfigItem(); + + List configItems = setBgpPeersConfigItem.generateConfig(command); + Assert.assertNotNull(configItems); + + Assert.assertEquals(2, configItems.size()); + Assert.assertTrue(configItems.get(0) instanceof FileConfigItem); + Assert.assertTrue(configItems.get(1) instanceof ScriptConfigItem); + + Assert.assertEquals(VRScripts.CONFIG_PERSIST_LOCATION, ((FileConfigItem) configItems.get(0)).getFilePath()); + Assert.assertTrue((((FileConfigItem) configItems.get(0)).getFileName().startsWith(VRScripts.BGP_PEERS_CONFIG))); + Assert.assertEquals(VRScripts.UPDATE_CONFIG, ((ScriptConfigItem) configItems.get(1)).getScript()); + } +} diff --git a/core/src/test/java/com/cloud/agent/resource/virtualnetwork/model/BgpPeersTest.java b/core/src/test/java/com/cloud/agent/resource/virtualnetwork/model/BgpPeersTest.java new file mode 100644 index 00000000000..eba423e55ed --- /dev/null +++ b/core/src/test/java/com/cloud/agent/resource/virtualnetwork/model/BgpPeersTest.java @@ -0,0 +1,56 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.agent.resource.virtualnetwork.model; + +import org.apache.cloudstack.network.BgpPeerTO; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.List; + +public class BgpPeersTest { + + @Test + public void testBgpPeers() { + BgpPeerTO bgpPeerTO = Mockito.mock(BgpPeerTO.class); + List bgpPeerTOs = new ArrayList<>(); + bgpPeerTOs.add(bgpPeerTO); + + BgpPeers bgpPeers = new BgpPeers(bgpPeerTOs); + Assert.assertEquals(ConfigBase.BGP_PEERS, bgpPeers.getType()); + Assert.assertNotNull(bgpPeers.getPeers()); + Assert.assertEquals(1, bgpPeers.getPeers().size()); + Assert.assertEquals(bgpPeerTO, bgpPeers.getPeers().get(0)); + } + + @Test + public void testBgpPeers2() { + BgpPeers bgpPeers = new BgpPeers(); + Assert.assertEquals(ConfigBase.BGP_PEERS, bgpPeers.getType()); + + BgpPeerTO bgpPeerTO = Mockito.mock(BgpPeerTO.class); + List bgpPeerTOs = new ArrayList<>(); + bgpPeerTOs.add(bgpPeerTO); + bgpPeers.setPeers(bgpPeerTOs); + + Assert.assertNotNull(bgpPeers.getPeers()); + Assert.assertEquals(1, bgpPeers.getPeers().size()); + Assert.assertEquals(bgpPeerTO, bgpPeers.getPeers().get(0)); + } +} diff --git a/core/src/test/java/com/cloud/agent/transport/LoggingExclusionStrategyTest.java b/core/src/test/java/com/cloud/agent/transport/LoggingExclusionStrategyTest.java new file mode 100644 index 00000000000..e02fe4516ab --- /dev/null +++ b/core/src/test/java/com/cloud/agent/transport/LoggingExclusionStrategyTest.java @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.agent.transport; + +import com.cloud.agent.api.BadCommand; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.GetStorageStatsCommand; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.Logger; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.ArrayList; +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) +public class LoggingExclusionStrategyTest { + + @Mock + Logger loggerMock; + @Spy + @InjectMocks + LoggingExclusionStrategy loggingExclusionStrategySpy; + + @Test + public void shouldSkipClassTestArrayClazz() { + List array = new ArrayList<>(); + + boolean result = loggingExclusionStrategySpy.shouldSkipClass(array.getClass()); + + Assert.assertFalse(result); + } + + @Test + public void shouldSkipClassTestNotSubclassOfCommand() { + Integer integer = 1; + + boolean result = loggingExclusionStrategySpy.shouldSkipClass(integer.getClass()); + + Assert.assertFalse(result); + } + + @Test + public void shouldSkipClassTestNullClassAnnotation() { + Command cmd = new BadCommand(); + Mockito.doReturn(true).when(loggerMock).isEnabled(Level.DEBUG); + + boolean result = loggingExclusionStrategySpy.shouldSkipClass(cmd.getClass()); + + Assert.assertFalse(result); + } + + @Test + public void shouldSkipClassTestWithClassAnnotation() { + Command cmd = new GetStorageStatsCommand(); + Mockito.doReturn(true).when(loggerMock).isEnabled(Level.TRACE); + + boolean result = loggingExclusionStrategySpy.shouldSkipClass(cmd.getClass()); + + Assert.assertFalse(result); + } + +} diff --git a/core/src/test/java/com/cloud/agent/transport/RequestTest.java b/core/src/test/java/com/cloud/agent/transport/RequestTest.java index 21766ba038f..0fe42c7cede 100644 --- a/core/src/test/java/com/cloud/agent/transport/RequestTest.java +++ b/core/src/test/java/com/cloud/agent/transport/RequestTest.java @@ -22,8 +22,8 @@ package com.cloud.agent.transport; import java.nio.ByteBuffer; import junit.framework.TestCase; -import org.apache.log4j.Level; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.junit.Assert; import org.mockito.Mockito; @@ -43,7 +43,6 @@ import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.transport.Request.Version; import com.cloud.exception.UnsupportedVersionException; import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.serializer.GsonHelper; import com.cloud.storage.DataStoreRole; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.TemplateType; @@ -58,47 +57,22 @@ import com.cloud.template.VirtualMachineTemplate; */ public class RequestTest extends TestCase { - private static final Logger s_logger = Logger.getLogger(RequestTest.class); + protected Logger logger = LogManager.getLogger(getClass()); public void testSerDeser() { - s_logger.info("Testing serializing and deserializing works as expected"); + logger.info("Testing serializing and deserializing works as expected"); - s_logger.info("UpdateHostPasswordCommand should have two parameters that doesn't show in logging"); + logger.info("UpdateHostPasswordCommand should have two parameters that doesn't show in logging"); UpdateHostPasswordCommand cmd1 = new UpdateHostPasswordCommand("abc", "def"); - s_logger.info("SecStorageFirewallCfgCommand has a context map that shouldn't show up in debug level"); + logger.info("SecStorageFirewallCfgCommand has a context map that shouldn't show up in debug level"); SecStorageFirewallCfgCommand cmd2 = new SecStorageFirewallCfgCommand(); - s_logger.info("GetHostStatsCommand should not show up at all in debug level"); + logger.info("GetHostStatsCommand should not show up at all in debug level"); GetHostStatsCommand cmd3 = new GetHostStatsCommand("hostguid", "hostname", 101); cmd2.addPortConfig("abc", "24", true, "eth0"); cmd2.addPortConfig("127.0.0.1", "44", false, "eth1"); Request sreq = new Request(2, 3, new Command[] {cmd1, cmd2, cmd3}, true, true); sreq.setSequence(892403717); - Logger logger = Logger.getLogger(GsonHelper.class); - Level level = logger.getLevel(); - - logger.setLevel(Level.DEBUG); - String log = sreq.log("Debug", true, Level.DEBUG); - assert (log.contains(UpdateHostPasswordCommand.class.getSimpleName())); - assert (log.contains(SecStorageFirewallCfgCommand.class.getSimpleName())); - assert (!log.contains(GetHostStatsCommand.class.getSimpleName())); - assert (!log.contains("username")); - assert (!log.contains("password")); - - logger.setLevel(Level.TRACE); - log = sreq.log("Trace", true, Level.TRACE); - assert (log.contains(UpdateHostPasswordCommand.class.getSimpleName())); - assert (log.contains(SecStorageFirewallCfgCommand.class.getSimpleName())); - assert (log.contains(GetHostStatsCommand.class.getSimpleName())); - assert (!log.contains("username")); - assert (!log.contains("password")); - - logger.setLevel(Level.INFO); - log = sreq.log("Info", true, Level.INFO); - assert (log == null); - - logger.setLevel(level); - byte[] bytes = sreq.getBytes(); assert Request.getSequence(bytes) == 892403717; @@ -109,9 +83,9 @@ public class RequestTest extends TestCase { try { creq = Request.parse(bytes); } catch (ClassNotFoundException e) { - s_logger.error("Unable to parse bytes: ", e); + logger.error("Unable to parse bytes: ", e); } catch (UnsupportedVersionException e) { - s_logger.error("Unable to parse bytes: ", e); + logger.error("Unable to parse bytes: ", e); } assert creq != null : "Couldn't get the request back"; @@ -127,9 +101,9 @@ public class RequestTest extends TestCase { try { sresp = Response.parse(bytes); } catch (ClassNotFoundException e) { - s_logger.error("Unable to parse bytes: ", e); + logger.error("Unable to parse bytes: ", e); } catch (UnsupportedVersionException e) { - s_logger.error("Unable to parse bytes: ", e); + logger.error("Unable to parse bytes: ", e); } assert sresp != null : "Couldn't get the response back"; @@ -138,7 +112,7 @@ public class RequestTest extends TestCase { } public void testSerDeserTO() { - s_logger.info("Testing serializing and deserializing interface TO works as expected"); + logger.info("Testing serializing and deserializing interface TO works as expected"); NfsTO nfs = new NfsTO("nfs://192.168.56.10/opt/storage/secondary", DataStoreRole.Image); // SecStorageSetupCommand cmd = new SecStorageSetupCommand(nfs, "nfs://192.168.56.10/opt/storage/secondary", null); @@ -156,9 +130,9 @@ public class RequestTest extends TestCase { try { creq = Request.parse(bytes); } catch (ClassNotFoundException e) { - s_logger.error("Unable to parse bytes: ", e); + logger.error("Unable to parse bytes: ", e); } catch (UnsupportedVersionException e) { - s_logger.error("Unable to parse bytes: ", e); + logger.error("Unable to parse bytes: ", e); } assert creq != null : "Couldn't get the request back"; @@ -168,7 +142,7 @@ public class RequestTest extends TestCase { } public void testDownload() { - s_logger.info("Testing Download answer"); + logger.info("Testing Download answer"); VirtualMachineTemplate template = Mockito.mock(VirtualMachineTemplate.class); Mockito.when(template.getId()).thenReturn(1L); Mockito.when(template.getFormat()).thenReturn(ImageFormat.QCOW2); @@ -193,7 +167,7 @@ public class RequestTest extends TestCase { } public void testCompress() { - s_logger.info("testCompress"); + logger.info("testCompress"); int len = 800000; ByteBuffer inputBuffer = ByteBuffer.allocate(len); for (int i = 0; i < len; i++) { @@ -202,7 +176,7 @@ public class RequestTest extends TestCase { inputBuffer.limit(len); ByteBuffer compressedBuffer = ByteBuffer.allocate(len); compressedBuffer = Request.doCompress(inputBuffer, len); - s_logger.info("compressed length: " + compressedBuffer.limit()); + logger.info("compressed length: " + compressedBuffer.limit()); ByteBuffer decompressedBuffer = ByteBuffer.allocate(len); decompressedBuffer = Request.doDecompress(compressedBuffer, len); for (int i = 0; i < len; i++) { @@ -212,29 +186,6 @@ public class RequestTest extends TestCase { } } - public void testLogging() { - s_logger.info("Testing Logging"); - GetHostStatsCommand cmd3 = new GetHostStatsCommand("hostguid", "hostname", 101); - Request sreq = new Request(2, 3, new Command[] {cmd3}, true, true); - sreq.setSequence(1); - Logger logger = Logger.getLogger(GsonHelper.class); - Level level = logger.getLevel(); - - logger.setLevel(Level.DEBUG); - String log = sreq.log("Debug", true, Level.DEBUG); - assert (log == null); - - log = sreq.log("Debug", false, Level.DEBUG); - assert (log != null); - - logger.setLevel(Level.TRACE); - log = sreq.log("Trace", true, Level.TRACE); - assert (log.contains(GetHostStatsCommand.class.getSimpleName())); - s_logger.debug(log); - - logger.setLevel(level); - } - protected void compareRequest(Request req1, Request req2) { assert req1.getSequence() == req2.getSequence(); assert req1.getAgentId() == req2.getAgentId(); @@ -253,24 +204,24 @@ public class RequestTest extends TestCase { } public void testGoodCommand() { - s_logger.info("Testing good Command"); + logger.info("Testing good Command"); String content = "[{\"com.cloud.agent.api.GetVolumeStatsCommand\":{\"volumeUuids\":[\"dcc860ac-4a20-498f-9cb3-bab4d57aa676\"]," - + "\"poolType\":\"NetworkFilesystem\",\"poolUuid\":\"e007c270-2b1b-3ce9-ae92-a98b94eef7eb\",\"contextMap\":{},\"wait\":5}}]"; + + "\"poolType\":{\"name\":\"NetworkFilesystem\"},\"poolUuid\":\"e007c270-2b1b-3ce9-ae92-a98b94eef7eb\",\"contextMap\":{},\"wait\":5}}]"; Request sreq = new Request(Version.v2, 1L, 2L, 3L, 1L, (short)1, content); sreq.setSequence(1); Command cmds[] = sreq.getCommands(); - s_logger.debug("Command class = " + cmds[0].getClass().getSimpleName()); + logger.debug("Command class = " + cmds[0].getClass().getSimpleName()); assert cmds[0].getClass().equals(GetVolumeStatsCommand.class); } public void testBadCommand() { - s_logger.info("Testing Bad Command"); + logger.info("Testing Bad Command"); String content = "[{\"com.cloud.agent.api.SomeJunkCommand\":{\"volumeUuids\":[\"dcc860ac-4a20-498f-9cb3-bab4d57aa676\"]," - + "\"poolType\":\"NetworkFilesystem\",\"poolUuid\":\"e007c270-2b1b-3ce9-ae92-a98b94eef7eb\",\"contextMap\":{},\"wait\":5}}]"; + + "\"poolType\":{\"name\":\"NetworkFilesystem\"},\"poolUuid\":\"e007c270-2b1b-3ce9-ae92-a98b94eef7eb\",\"contextMap\":{},\"wait\":5}}]"; Request sreq = new Request(Version.v2, 1L, 2L, 3L, 1L, (short)1, content); sreq.setSequence(1); Command cmds[] = sreq.getCommands(); - s_logger.debug("Command class = " + cmds[0].getClass().getSimpleName()); + logger.debug("Command class = " + cmds[0].getClass().getSimpleName()); assert cmds[0].getClass().equals(BadCommand.class); } diff --git a/core/src/test/java/com/cloud/serializer/GsonHelperTest.java b/core/src/test/java/com/cloud/serializer/GsonHelperTest.java new file mode 100644 index 00000000000..e8b0b373060 --- /dev/null +++ b/core/src/test/java/com/cloud/serializer/GsonHelperTest.java @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package com.cloud.serializer; + +import com.cloud.agent.api.to.NfsTO; +import com.cloud.storage.DataStoreRole; +import com.google.gson.Gson; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Test cases to verify working order of GsonHelper.java + * with regards to a concrete implementation of the DataStoreTO + * interface + */ +public class GsonHelperTest { + + private Gson gson; + private Gson gsonLogger; + private NfsTO nfsTO; + + @Before + public void setUp() { + gson = GsonHelper.getGson(); + gsonLogger = GsonHelper.getGsonLogger(); + nfsTO = new NfsTO("http://example.com", DataStoreRole.Primary); + } + + @Test + public void testGsonSerialization() { + String json = gson.toJson(nfsTO); + assertNotNull(json); + assertTrue(json.contains("\"_url\":\"http://example.com\"")); + assertTrue(json.contains("\"_role\":\"Primary\"")); + } + + @Test + public void testGsonDeserialization() { + String json = "{\"_url\":\"http://example.com\",\"_role\":\"Primary\"}"; + NfsTO deserializedNfsTO = gson.fromJson(json, NfsTO.class); + assertNotNull(deserializedNfsTO); + assertEquals("http://example.com", deserializedNfsTO.getUrl()); + assertEquals(DataStoreRole.Primary, deserializedNfsTO.getRole()); + } + + @Test + public void testGsonLoggerSerialization() { + String json = gsonLogger.toJson(nfsTO); + assertNotNull(json); + assertTrue(json.contains("\"_url\":\"http://example.com\"")); + assertTrue(json.contains("\"_role\":\"Primary\"")); + } + + @Test + public void testGsonLoggerDeserialization() { + String json ="{\"_url\":\"http://example.com\",\"_role\":\"Primary\"}"; + NfsTO deserializedNfsTO = gsonLogger.fromJson(json, NfsTO.class); + assertNotNull(deserializedNfsTO); + assertEquals("http://example.com", deserializedNfsTO.getUrl()); + assertEquals(DataStoreRole.Primary, deserializedNfsTO.getRole()); + } +} diff --git a/core/src/test/java/com/cloud/storage/template/OVAProcessorTest.java b/core/src/test/java/com/cloud/storage/template/OVAProcessorTest.java index 8ab54644718..8674a8df286 100644 --- a/core/src/test/java/com/cloud/storage/template/OVAProcessorTest.java +++ b/core/src/test/java/com/cloud/storage/template/OVAProcessorTest.java @@ -131,5 +131,25 @@ public class OVAProcessorTest { Assert.assertEquals(virtualSize, processor.getVirtualSize(mockFile)); Mockito.verify(mockFile, Mockito.times(0)).length(); } + @Test + public void testProcessWithLargeFileSize() throws Exception { + String templatePath = "/tmp"; + String templateName = "large_template"; + long virtualSize = 10_000_000_000L; + long actualSize = 5_000_000_000L; + Mockito.when(mockStorageLayer.exists(Mockito.anyString())).thenReturn(true); + Mockito.when(mockStorageLayer.getSize(Mockito.anyString())).thenReturn(actualSize); + Mockito.doReturn(virtualSize).when(processor).getTemplateVirtualSize(Mockito.anyString(), Mockito.anyString()); + + try (MockedConstruction + @@ -87,25 +96,29 @@ execute - - def csVersion = pom.properties['cs.version'] - def patch = pom.properties['patch.version'] - def templateList = [] - templateList.add("systemvmtemplate-${csVersion}.${patch}-kvm") - templateList.add("systemvmtemplate-${csVersion}.${patch}-vmware") - templateList.add("systemvmtemplate-${csVersion}.${patch}-xen") - templateList.add("systemvmtemplate-${csVersion}.${patch}-ovm") - templateList.add("systemvmtemplate-${csVersion}.${patch}-hyperv") - File file = new File("./engine/schema/dist/systemvm-templates/md5sum.txt") - def lines = file.readLines() - for (template in templateList) { - def data = lines.findAll { it.contains(template) } - if (data != null) { - def hypervisor = template.tokenize('-')[-1] - pom.properties["$hypervisor" + ".checksum"] = data[0].tokenize(' ')[0] + + + @@ -133,7 +146,7 @@ org.codehaus.mojo exec-maven-plugin - 1.2.1 + ${cs.exec-maven-plugin.version} systemvm-template-metadata @@ -152,6 +165,15 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + true + + + @@ -181,7 +203,7 @@ true - ${project.systemvm.template.location}/${cs.version}/systemvmtemplate-${cs.version}.${patch.version}-kvm.qcow2.bz2 + ${project.systemvm.template.location}/${cs.version}/systemvmtemplate-${cs.version}.${patch.version}-x86_64-kvm.qcow2.bz2 ${basedir}/dist/systemvm-templates/ ${kvm.checksum} @@ -217,7 +239,7 @@ true - ${project.systemvm.template.location}/${cs.version}/systemvmtemplate-${cs.version}.${patch.version}-vmware.ova + ${project.systemvm.template.location}/${cs.version}/systemvmtemplate-${cs.version}.${patch.version}-x86_64-vmware.ova ${basedir}/dist/systemvm-templates/ ${vmware.checksum} @@ -253,7 +275,7 @@ true - ${project.systemvm.template.location}/${cs.version}/systemvmtemplate-${cs.version}.${patch.version}-xen.vhd.bz2 + ${project.systemvm.template.location}/${cs.version}/systemvmtemplate-${cs.version}.${patch.version}-x86_64-xen.vhd.bz2 ${basedir}/dist/systemvm-templates/ ${xen.checksum} @@ -289,7 +311,7 @@ true - ${project.systemvm.template.location}/${cs.version}/systemvmtemplate-${cs.version}.${patch.version}-ovm.raw.bz2 + ${project.systemvm.template.location}/${cs.version}/systemvmtemplate-${cs.version}.${patch.version}-x86_64-ovm.raw.bz2 ${basedir}/dist/systemvm-templates/ ${ovm.checksum} @@ -325,7 +347,7 @@ true - ${project.systemvm.template.location}/${cs.version}/systemvmtemplate-${cs.version}.${patch.version}-hyperv.vhd.zip + ${project.systemvm.template.location}/${cs.version}/systemvmtemplate-${cs.version}.${patch.version}-x86_64-hyperv.vhd.zip ${basedir}/dist/systemvm-templates/ ${hyperv.checksum} diff --git a/engine/schema/src/main/java/com/cloud/capacity/CapacityVO.java b/engine/schema/src/main/java/com/cloud/capacity/CapacityVO.java index 29b58ddccd4..cd62935f17e 100644 --- a/engine/schema/src/main/java/com/cloud/capacity/CapacityVO.java +++ b/engine/schema/src/main/java/com/cloud/capacity/CapacityVO.java @@ -80,6 +80,9 @@ public class CapacityVO implements Capacity { @Transient private Long allocatedCapacity; + @Transient + private String tag; + public CapacityVO() { } @@ -221,6 +224,15 @@ public class CapacityVO implements Capacity { this.allocatedCapacity = allocatedCapacity; } + @Override + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } + @Override public String getUuid() { return null; //To change body of implemented methods use File | Settings | File Templates. diff --git a/engine/schema/src/main/java/com/cloud/capacity/dao/CapacityDao.java b/engine/schema/src/main/java/com/cloud/capacity/dao/CapacityDao.java index 459a63a7ba1..1bb79ce417a 100644 --- a/engine/schema/src/main/java/com/cloud/capacity/dao/CapacityDao.java +++ b/engine/schema/src/main/java/com/cloud/capacity/dao/CapacityDao.java @@ -28,6 +28,8 @@ import com.cloud.utils.db.GenericDao; public interface CapacityDao extends GenericDao { CapacityVO findByHostIdType(Long hostId, short capacityType); + List listByHostIdTypes(Long hostId, List capacityTypes); + List listClustersInZoneOrPodByHostCapacities(long id, long vmId, int requiredCpu, long requiredRam, short capacityTypeForOrdering, boolean isZone); List listHostsWithEnoughCapacity(int requiredCpu, long requiredRam, Long clusterId, String hostType); @@ -44,6 +46,8 @@ public interface CapacityDao extends GenericDao { List findCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId); + List findFilteredCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId, List hostIds, List poolIds); + List listPodsByHostCapacities(long zoneId, int requiredCpu, long requiredRam, short capacityType); Pair, Map> orderPodsByAggregateCapacity(long zoneId, short capacityType); @@ -51,7 +55,8 @@ public interface CapacityDao extends GenericDao { List findCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId, String resourceState); - List listCapacitiesGroupedByLevelAndType(Integer capacityType, Long zoneId, Long podId, Long clusterId, int level, Long limit); + List listCapacitiesGroupedByLevelAndType(Integer capacityType, Long zoneId, Long podId, + Long clusterId, int level, List hostIds, List poolIds, Long limit); void updateCapacityState(Long dcId, Long podId, Long clusterId, Long hostId, String capacityState, short[] capacityType); diff --git a/engine/schema/src/main/java/com/cloud/capacity/dao/CapacityDaoImpl.java b/engine/schema/src/main/java/com/cloud/capacity/dao/CapacityDaoImpl.java index 302ffd8e760..5e7eee4566c 100644 --- a/engine/schema/src/main/java/com/cloud/capacity/dao/CapacityDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/capacity/dao/CapacityDaoImpl.java @@ -26,12 +26,11 @@ import java.util.Map; import javax.inject.Inject; -import org.apache.log4j.Logger; -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Component; - import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; @@ -51,7 +50,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class CapacityDaoImpl extends GenericDaoBase implements CapacityDao { - private static final Logger s_logger = Logger.getLogger(CapacityDaoImpl.class); private static final String ADD_ALLOCATED_SQL = "UPDATE `cloud`.`op_host_capacity` SET used_capacity = used_capacity + ? WHERE host_id = ? AND capacity_type = ?"; private static final String SUBTRACT_ALLOCATED_SQL = @@ -341,7 +339,8 @@ public class CapacityDaoImpl extends GenericDaoBase implements } @Override - public List listCapacitiesGroupedByLevelAndType(Integer capacityType, Long zoneId, Long podId, Long clusterId, int level, Long limit) { + public List listCapacitiesGroupedByLevelAndType(Integer capacityType, Long zoneId, Long podId, + Long clusterId, int level, List hostIds, List poolIds, Long limit) { StringBuilder finalQuery = new StringBuilder(); TransactionLegacy txn = TransactionLegacy.currentTxn(); @@ -380,6 +379,18 @@ public class CapacityDaoImpl extends GenericDaoBase implements finalQuery.append(" AND capacity_type = ?"); resourceIdList.add(capacityType.longValue()); } + if (CollectionUtils.isNotEmpty(hostIds)) { + finalQuery.append(String.format(" AND capacity.host_id IN (%s)", StringUtils.join(hostIds, ","))); + if (capacityType == null) { + finalQuery.append(String.format(" AND capacity_type NOT IN (%s)", StringUtils.join(Capacity.STORAGE_CAPACITY_TYPES, ","))); + } + } + if (CollectionUtils.isNotEmpty(poolIds)) { + finalQuery.append(String.format(" AND capacity.host_id IN (%s)", StringUtils.join(poolIds, ","))); + if (capacityType == null) { + finalQuery.append(String.format(" AND capacity_type IN (%s)", StringUtils.join(Capacity.STORAGE_CAPACITY_TYPES, ","))); + } + } switch (level) { case 1: // List all the capacities grouped by zone, capacity Type @@ -463,8 +474,37 @@ public class CapacityDaoImpl extends GenericDaoBase implements } } + protected String getHostAndPoolConditionForFilteredCapacity(Integer capacityType, List hostIds, List poolIds) { + StringBuilder sql = new StringBuilder(); + if (CollectionUtils.isEmpty(hostIds) && CollectionUtils.isEmpty(poolIds)) { + return ""; + } + sql.append(" AND ("); + boolean hostConditionAdded = false; + if (CollectionUtils.isNotEmpty(hostIds) && (capacityType == null || !Capacity.STORAGE_CAPACITY_TYPES.contains(capacityType.shortValue()))) { + sql.append(String.format("(capacity.host_id IN (%s)", StringUtils.join(hostIds, ","))); + if (capacityType == null) { + sql.append(String.format(" AND capacity_type NOT IN (%s)", StringUtils.join(Capacity.STORAGE_CAPACITY_TYPES, ","))); + } + sql.append(")"); + hostConditionAdded = true; + } + if (CollectionUtils.isNotEmpty(poolIds) && (capacityType == null || Capacity.STORAGE_CAPACITY_TYPES.contains(capacityType.shortValue()))) { + if (hostConditionAdded) { + sql.append(" OR "); + } + sql.append(String.format("(capacity.host_id IN (%s)", StringUtils.join(poolIds, ","))); + if (capacityType == null || Capacity.STORAGE_CAPACITY_TYPES.contains(capacityType.shortValue())) { + sql.append(String.format(" AND capacity_type IN (%s)", StringUtils.join(Capacity.STORAGE_CAPACITY_TYPES, ","))); + } + sql.append(")"); + } + sql.append(")"); + return sql.toString(); + } + @Override - public List findCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId) { + public List findFilteredCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId, List hostIds, List poolIds) { TransactionLegacy txn = TransactionLegacy.currentTxn(); PreparedStatement pstmt = null; @@ -518,6 +558,8 @@ public class CapacityDaoImpl extends GenericDaoBase implements resourceIdList.add(capacityType.longValue()); } + sql.append(getHostAndPoolConditionForFilteredCapacity(capacityType, hostIds, poolIds)); + if (podId == null && clusterId == null) { sql.append(" GROUP BY capacity_type, data_center_id"); } else { @@ -593,6 +635,11 @@ public class CapacityDaoImpl extends GenericDaoBase implements } } + @Override + public List findCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId) { + return findFilteredCapacityBy(capacityType, zoneId, podId, clusterId, null, null); + } + public void updateAllocated(Long hostId, long allocatedAmount, short capacityType, boolean add) { TransactionLegacy txn = TransactionLegacy.currentTxn(); PreparedStatement pstmt = null; @@ -612,7 +659,7 @@ public class CapacityDaoImpl extends GenericDaoBase implements txn.commit(); } catch (Exception e) { txn.rollback(); - s_logger.warn("Exception updating capacity for host: " + hostId, e); + logger.warn("Exception updating capacity for host: " + hostId, e); } } @@ -624,6 +671,18 @@ public class CapacityDaoImpl extends GenericDaoBase implements return findOneBy(sc); } + @Override + public List listByHostIdTypes(Long hostId, List capacityTypes) { + SearchBuilder sb = createSearchBuilder(); + sb.and("hostId", sb.entity().getHostOrPoolId(), SearchCriteria.Op.EQ); + sb.and("type", sb.entity().getCapacityType(), SearchCriteria.Op.IN); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("hostId", hostId); + sc.setParameters("type", capacityTypes.toArray()); + return listBy(sc); + } + @Override public List listClustersInZoneOrPodByHostCapacities(long id, long vmId, int requiredCpu, long requiredRam, short capacityTypeForOrdering, boolean isZone) { TransactionLegacy txn = TransactionLegacy.currentTxn(); @@ -704,6 +763,7 @@ public class CapacityDaoImpl extends GenericDaoBase implements public Long clusterId; public Long podId; public Long dcId; + public String tag; public SummedCapacity() { } @@ -792,6 +852,14 @@ public class CapacityDaoImpl extends GenericDaoBase implements public void setAllocatedCapacity(Long sumAllocated) { this.sumAllocated = sumAllocated; } + + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } } @Override @@ -1126,7 +1194,7 @@ public class CapacityDaoImpl extends GenericDaoBase implements pstmt.executeUpdate(); } catch (Exception e) { - s_logger.warn("Error updating CapacityVO", e); + logger.warn("Error updating CapacityVO", e); } } @@ -1146,7 +1214,7 @@ public class CapacityDaoImpl extends GenericDaoBase implements return rs.getFloat(1); } } catch (Exception e) { - s_logger.warn("Error checking cluster threshold", e); + logger.warn("Error checking cluster threshold", e); } return 0; } diff --git a/engine/schema/src/main/java/com/cloud/certificate/dao/CertificateDaoImpl.java b/engine/schema/src/main/java/com/cloud/certificate/dao/CertificateDaoImpl.java index 9544804284e..99ba36f22b9 100644 --- a/engine/schema/src/main/java/com/cloud/certificate/dao/CertificateDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/certificate/dao/CertificateDaoImpl.java @@ -17,7 +17,6 @@ package com.cloud.certificate.dao; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.certificate.CertificateVO; @@ -28,7 +27,6 @@ import com.cloud.utils.db.GenericDaoBase; @DB public class CertificateDaoImpl extends GenericDaoBase implements CertificateDao { - private static final Logger s_logger = Logger.getLogger(CertificateDaoImpl.class); public CertificateDaoImpl() { @@ -42,7 +40,7 @@ public class CertificateDaoImpl extends GenericDaoBase impl update(cert.getId(), cert); return cert.getId(); } catch (Exception e) { - s_logger.warn("Unable to read the certificate: " + e); + logger.warn("Unable to read the certificate: " + e); return new Long(0); } } diff --git a/engine/schema/src/main/java/com/cloud/cluster/agentlb/dao/HostTransferMapDaoImpl.java b/engine/schema/src/main/java/com/cloud/cluster/agentlb/dao/HostTransferMapDaoImpl.java index e1c0dbd9e47..861dbeb1df4 100644 --- a/engine/schema/src/main/java/com/cloud/cluster/agentlb/dao/HostTransferMapDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/cluster/agentlb/dao/HostTransferMapDaoImpl.java @@ -21,7 +21,6 @@ import java.util.List; import javax.annotation.PostConstruct; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.cluster.agentlb.HostTransferMapVO; @@ -34,7 +33,6 @@ import com.cloud.utils.db.SearchCriteria; @Component @DB public class HostTransferMapDaoImpl extends GenericDaoBase implements HostTransferMapDao { - private static final Logger s_logger = Logger.getLogger(HostTransferMapDaoImpl.class); protected SearchBuilder AllFieldsSearch; protected SearchBuilder IntermediateStateSearch; diff --git a/engine/schema/src/main/java/com/cloud/configuration/ResourceCountVO.java b/engine/schema/src/main/java/com/cloud/configuration/ResourceCountVO.java index ae8f3822704..9e39a608f9e 100644 --- a/engine/schema/src/main/java/com/cloud/configuration/ResourceCountVO.java +++ b/engine/schema/src/main/java/com/cloud/configuration/ResourceCountVO.java @@ -47,10 +47,13 @@ public class ResourceCountVO implements ResourceCount { @Column(name = "count") private long count; + @Column(name = "tag") + private String tag; + public ResourceCountVO() { } - public ResourceCountVO(ResourceType type, long count, long ownerId, ResourceOwnerType ownerType) { + public ResourceCountVO(ResourceType type, long count, long ownerId, ResourceOwnerType ownerType, String tag) { this.type = type; this.count = count; @@ -59,6 +62,11 @@ public class ResourceCountVO implements ResourceCount { } else if (ownerType == ResourceOwnerType.Domain) { this.domainId = ownerId; } + this.tag = tag; + } + + public ResourceCountVO(ResourceType type, long count, long ownerId, ResourceOwnerType ownerType) { + this(type, count, ownerId, ownerType, null); } @Override @@ -99,7 +107,7 @@ public class ResourceCountVO implements ResourceCount { @Override public String toString() { - return new StringBuilder("REsourceCount[").append("-") + return new StringBuilder("ResourceCount[").append("-") .append(id) .append("-") .append(type) @@ -107,6 +115,8 @@ public class ResourceCountVO implements ResourceCount { .append(accountId) .append("-") .append(domainId) + .append("-") + .append(tag) .append("]") .toString(); } @@ -136,4 +146,13 @@ public class ResourceCountVO implements ResourceCount { public void setAccountId(Long accountId) { this.accountId = accountId; } + + @Override + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } } diff --git a/engine/schema/src/main/java/com/cloud/configuration/ResourceLimitVO.java b/engine/schema/src/main/java/com/cloud/configuration/ResourceLimitVO.java index 39217091975..1619537ae74 100644 --- a/engine/schema/src/main/java/com/cloud/configuration/ResourceLimitVO.java +++ b/engine/schema/src/main/java/com/cloud/configuration/ResourceLimitVO.java @@ -47,10 +47,13 @@ public class ResourceLimitVO implements ResourceLimit { @Column(name = "max") private Long max; + @Column(name = "tag") + private String tag; + public ResourceLimitVO() { } - public ResourceLimitVO(ResourceCount.ResourceType type, Long max, long ownerId, ResourceOwnerType ownerType) { + public ResourceLimitVO(ResourceCount.ResourceType type, Long max, long ownerId, ResourceOwnerType ownerType, String tag) { this.type = type; this.max = max; @@ -59,6 +62,11 @@ public class ResourceLimitVO implements ResourceLimit { } else if (ownerType == ResourceOwnerType.Domain) { this.domainId = ownerId; } + this.tag = tag; + } + + public ResourceLimitVO(ResourceCount.ResourceType type, Long max, long ownerId, ResourceOwnerType ownerType) { + this(type, max, ownerId, ownerType, null); } @Override @@ -123,4 +131,12 @@ public class ResourceLimitVO implements ResourceLimit { this.accountId = accountId; } + @Override + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } } diff --git a/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceCountDao.java b/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceCountDao.java index 28f2a536071..b978cc04bfa 100644 --- a/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceCountDao.java +++ b/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceCountDao.java @@ -26,18 +26,20 @@ import com.cloud.utils.db.GenericDao; public interface ResourceCountDao extends GenericDao { /** - * @param domainId the id of the domain to get the resource count + * @param ownerId the id of the owner to get the resource count * @param type the type of resource (e.g. user_vm, public_ip, volume) + * @param tag for the type of resource * @return the count of resources in use for the given type and domain */ - long getResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type); + long getResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag); /** - * @param domainId the id of the domain to set the resource count + * @param ownerId the id of the owner to set the resource count * @param type the type of resource (e.g. user_vm, public_ip, volume) - * @param the count of resources in use for the given type and domain + * @param tag the tag for the type of resource + * @param count the count of resources in use for the given type and domain */ - void setResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type, long count); + void setResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag, long count); boolean updateById(long id, boolean increment, long delta); @@ -45,13 +47,18 @@ public interface ResourceCountDao extends GenericDao { List listByOwnerId(long ownerId, ResourceOwnerType ownerType); - ResourceCountVO findByOwnerAndType(long ownerId, ResourceOwnerType ownerType, ResourceType type); + ResourceCountVO findByOwnerAndTypeAndTag(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag); + + List findByOwnersAndTypeAndTag(List ownerIdList, ResourceOwnerType ownerType, + ResourceType type, String tag); List listResourceCountByOwnerType(ResourceOwnerType ownerType); - Set listAllRowsToUpdate(long ownerId, ResourceOwnerType ownerType, ResourceType type); + Set listAllRowsToUpdate(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag); - Set listRowsToUpdateForDomain(long domainId, ResourceType type); + boolean updateCountByDeltaForIds(List ids, boolean increment, long delta); + + Set listRowsToUpdateForDomain(long domainId, ResourceType type, String tag); long removeEntriesByOwner(long ownerId, ResourceOwnerType ownerType); @@ -68,4 +75,8 @@ public interface ResourceCountDao extends GenericDao { * Side note: This method is not using the "resource_count" table. It is executing the actual count instead. */ long countMemoryAllocatedToAccount(long accountId); + + void removeResourceCountsForNonMatchingTags(Long ownerId, ResourceOwnerType ownerType, List types, List tags); + + List lockRows(Set ids); } diff --git a/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceCountDaoImpl.java b/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceCountDaoImpl.java index ca6f13d2d64..65d7fed2d1a 100644 --- a/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceCountDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceCountDaoImpl.java @@ -20,13 +20,18 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.inject.Inject; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import com.cloud.configuration.Resource; @@ -37,6 +42,7 @@ import com.cloud.configuration.ResourceLimit; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.user.AccountVO; +import com.cloud.user.ResourceLimitService; import com.cloud.user.dao.AccountDao; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; @@ -49,24 +55,49 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class ResourceCountDaoImpl extends GenericDaoBase implements ResourceCountDao { private final SearchBuilder TypeSearch; - + private final SearchBuilder TypeNullTagSearch; + private final SearchBuilder NonMatchingTagsSearch; private final SearchBuilder AccountSearch; private final SearchBuilder DomainSearch; + private final SearchBuilder IdsSearch; @Inject private DomainDao _domainDao; @Inject private AccountDao _accountDao; + protected static final String INCREMENT_COUNT_BY_IDS_SQL = "UPDATE `cloud`.`resource_count` SET `count` = `count` + ? WHERE `id` IN (?)"; + protected static final String DECREMENT_COUNT_BY_IDS_SQL = "UPDATE `cloud`.`resource_count` SET `count` = `count` - ? WHERE `id` IN (?)"; + public ResourceCountDaoImpl() { TypeSearch = createSearchBuilder(); TypeSearch.and("type", TypeSearch.entity().getType(), SearchCriteria.Op.EQ); - TypeSearch.and("accountId", TypeSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - TypeSearch.and("domainId", TypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + TypeSearch.and("accountId", TypeSearch.entity().getAccountId(), SearchCriteria.Op.IN); + TypeSearch.and("domainId", TypeSearch.entity().getDomainId(), SearchCriteria.Op.IN); + TypeSearch.and("tag", TypeSearch.entity().getTag(), SearchCriteria.Op.EQ); TypeSearch.done(); + TypeNullTagSearch = createSearchBuilder(); + TypeNullTagSearch.and("type", TypeNullTagSearch.entity().getType(), SearchCriteria.Op.EQ); + TypeNullTagSearch.and("accountId", TypeNullTagSearch.entity().getAccountId(), SearchCriteria.Op.IN); + TypeNullTagSearch.and("domainId", TypeNullTagSearch.entity().getDomainId(), SearchCriteria.Op.IN); + TypeNullTagSearch.and("tag", TypeNullTagSearch.entity().getTag(), SearchCriteria.Op.NULL); + TypeNullTagSearch.done(); + + NonMatchingTagsSearch = createSearchBuilder(); + NonMatchingTagsSearch.and("accountId", NonMatchingTagsSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + NonMatchingTagsSearch.and("domainId", NonMatchingTagsSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + NonMatchingTagsSearch.and("types", NonMatchingTagsSearch.entity().getType(), SearchCriteria.Op.IN); + NonMatchingTagsSearch.and("tagNotNull", NonMatchingTagsSearch.entity().getTag(), SearchCriteria.Op.NNULL); + NonMatchingTagsSearch.and("tags", NonMatchingTagsSearch.entity().getTag(), SearchCriteria.Op.NIN); + NonMatchingTagsSearch.done(); + AccountSearch = createSearchBuilder(); DomainSearch = createSearchBuilder(); + + IdsSearch = createSearchBuilder(); + IdsSearch.and("id", IdsSearch.entity().getId(), SearchCriteria.Op.IN); + IdsSearch.done(); } @PostConstruct @@ -85,24 +116,40 @@ public class ResourceCountDaoImpl extends GenericDaoBase } @Override - public ResourceCountVO findByOwnerAndType(long ownerId, ResourceOwnerType ownerType, ResourceType type) { - SearchCriteria sc = TypeSearch.create(); - sc.setParameters("type", type); - - if (ownerType == ResourceOwnerType.Account) { - sc.setParameters("accountId", ownerId); - return findOneIncludingRemovedBy(sc); - } else if (ownerType == ResourceOwnerType.Domain) { - sc.setParameters("domainId", ownerId); - return findOneIncludingRemovedBy(sc); + public ResourceCountVO findByOwnerAndTypeAndTag(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag) { + List resourceCounts = findByOwnersAndTypeAndTag(List.of(ownerId), ownerType, type, tag); + if (CollectionUtils.isNotEmpty(resourceCounts)) { + return resourceCounts.get(0); } else { return null; } } @Override - public long getResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type) { - ResourceCountVO vo = findByOwnerAndType(ownerId, ownerType, type); + public List findByOwnersAndTypeAndTag(List ownerIdList, ResourceOwnerType ownerType, ResourceType type, String tag) { + if (CollectionUtils.isEmpty(ownerIdList)) { + return new ArrayList<>(); + } + SearchCriteria sc = tag != null ? TypeSearch.create() : TypeNullTagSearch.create(); + sc.setParameters("type", type); + if (tag != null) { + sc.setParameters("tag", tag); + } + + if (ownerType == ResourceOwnerType.Account) { + sc.setParameters("accountId", ownerIdList.toArray()); + return listIncludingRemovedBy(sc); + } else if (ownerType == ResourceOwnerType.Domain) { + sc.setParameters("domainId", ownerIdList.toArray()); + return listIncludingRemovedBy(sc); + } else { + return new ArrayList<>(); + } + } + + @Override + public long getResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag) { + ResourceCountVO vo = findByOwnerAndTypeAndTag(ownerId, ownerType, type, tag); if (vo != null) { return vo.getCount(); } else { @@ -111,8 +158,8 @@ public class ResourceCountDaoImpl extends GenericDaoBase } @Override - public void setResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type, long count) { - ResourceCountVO resourceCountVO = findByOwnerAndType(ownerId, ownerType, type); + public void setResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag, long count) { + ResourceCountVO resourceCountVO = findByOwnerAndTypeAndTag(ownerId, ownerType, type, tag); if (resourceCountVO != null && count != resourceCountVO.getCount()) { resourceCountVO.setCount(count); update(resourceCountVO.getId(), resourceCountVO); @@ -129,38 +176,79 @@ public class ResourceCountDaoImpl extends GenericDaoBase } @Override - public Set listRowsToUpdateForDomain(long domainId, ResourceType type) { + public boolean updateCountByDeltaForIds(List ids, boolean increment, long delta) { + if (CollectionUtils.isEmpty(ids)) { + return false; + } + String updateSql = increment ? INCREMENT_COUNT_BY_IDS_SQL : DECREMENT_COUNT_BY_IDS_SQL; + + String poolIdsInStr = ids.stream().map(String::valueOf).collect(Collectors.joining(",", "(", ")")); + String sql = updateSql.replace("(?)", poolIdsInStr); + + final TransactionLegacy txn = TransactionLegacy.currentTxn(); + try(PreparedStatement pstmt = txn.prepareStatement(sql);) { + pstmt.setLong(1, delta); + pstmt.executeUpdate(); + return true; + } catch (SQLException e) { + throw new CloudRuntimeException(e); + } + } + + @Override + public Set listRowsToUpdateForDomain(long domainId, ResourceType type, String tag) { Set rowIds = new HashSet(); Set domainIdsToUpdate = _domainDao.getDomainParentIds(domainId); for (Long domainIdToUpdate : domainIdsToUpdate) { - ResourceCountVO domainCountRecord = findByOwnerAndType(domainIdToUpdate, ResourceOwnerType.Domain, type); + ResourceCountVO domainCountRecord = findByOwnerAndTypeAndTag(domainIdToUpdate, ResourceOwnerType.Domain, type, tag); if (domainCountRecord != null) { rowIds.add(domainCountRecord.getId()); + } else { + if (StringUtils.isNotEmpty(tag)) { + ResourceCountVO resourceCountVO = createTaggedResourceCount(domainIdToUpdate, ResourceOwnerType.Domain, type, tag); + rowIds.add(resourceCountVO.getId()); + } } } return rowIds; } @Override - public Set listAllRowsToUpdate(long ownerId, ResourceOwnerType ownerType, ResourceType type) { + public Set listAllRowsToUpdate(long ownerId, ResourceOwnerType ownerType, ResourceType type, String tag) { Set rowIds = new HashSet(); if (ownerType == ResourceOwnerType.Account) { //get records for account - ResourceCountVO accountCountRecord = findByOwnerAndType(ownerId, ResourceOwnerType.Account, type); + ResourceCountVO accountCountRecord = findByOwnerAndTypeAndTag(ownerId, ResourceOwnerType.Account, type, tag); if (accountCountRecord != null) { rowIds.add(accountCountRecord.getId()); + } else { + if (StringUtils.isNotEmpty(tag)) { + ResourceCountVO resourceCountVO = createTaggedResourceCount(ownerId, ownerType, type, tag); + rowIds.add(resourceCountVO.getId()); + } } //get records for account's domain and all its parent domains - rowIds.addAll(listRowsToUpdateForDomain(_accountDao.findByIdIncludingRemoved(ownerId).getDomainId(), type)); + rowIds.addAll(listRowsToUpdateForDomain(_accountDao.findByIdIncludingRemoved(ownerId).getDomainId(), type, tag)); } else if (ownerType == ResourceOwnerType.Domain) { - return listRowsToUpdateForDomain(ownerId, type); + rowIds = listRowsToUpdateForDomain(ownerId, type, tag); } return rowIds; } + protected ResourceCountVO createTaggedResourceCount(long ownerId, ResourceLimit.ResourceOwnerType ownerType, ResourceType resourceType, String tag) { + ResourceCountVO taggedResourceCountVO = new ResourceCountVO(resourceType, 0, ownerId, ownerType, tag); + return persist(taggedResourceCountVO); + } + + protected void createTaggedResourceCounts(long ownerId, ResourceLimit.ResourceOwnerType ownerType, ResourceType resourceType, List tags) { + for (String tag : tags) { + createTaggedResourceCount(ownerId, ownerType, resourceType, tag); + } + } + @Override @DB public void createResourceCounts(long ownerId, ResourceLimit.ResourceOwnerType ownerType) { @@ -169,9 +257,23 @@ public class ResourceCountDaoImpl extends GenericDaoBase txn.start(); ResourceType[] resourceTypes = Resource.ResourceType.values(); + List hostTags = new ArrayList<>(); + if (StringUtils.isNotEmpty(ResourceLimitService.ResourceLimitHostTags.value())) { + hostTags = Arrays.asList(ResourceLimitService.ResourceLimitHostTags.value().split(",")); + } + List storageTags = new ArrayList<>(); + if (StringUtils.isNotEmpty(ResourceLimitService.ResourceLimitStorageTags.value())) { + storageTags = Arrays.asList(ResourceLimitService.ResourceLimitStorageTags.value().split(",")); + } for (ResourceType resourceType : resourceTypes) { ResourceCountVO resourceCountVO = new ResourceCountVO(resourceType, 0, ownerId, ownerType); persist(resourceCountVO); + if (ResourceLimitService.HostTagsSupportingTypes.contains(resourceType)) { + createTaggedResourceCounts(ownerId, ownerType, resourceType, hostTags); + } + if (ResourceLimitService.StorageTagsSupportingTypes.contains(resourceType)) { + createTaggedResourceCounts(ownerId, ownerType, resourceType, storageTags); + } } txn.commit(); @@ -266,4 +368,32 @@ public class ResourceCountDaoImpl extends GenericDaoBase } } + @Override + public void removeResourceCountsForNonMatchingTags(Long ownerId, ResourceOwnerType ownerType, List types, List tags) { + SearchCriteria sc = NonMatchingTagsSearch.create(); + if (ObjectUtils.allNotNull(ownerId, ownerType)) { + if (ResourceOwnerType.Account.equals(ownerType)) { + sc.setParameters("accountId", ownerId); + } else { + sc.setParameters("domainId", ownerId); + } + } + if (CollectionUtils.isNotEmpty(types)) { + sc.setParameters("types", types.stream().map(ResourceType::getName).toArray()); + } + if (CollectionUtils.isNotEmpty(tags)) { + sc.setParameters("tags", tags.toArray()); + } + remove(sc); + } + + @Override + public List lockRows(Set ids) { + if (CollectionUtils.isEmpty(ids)) { + return new ArrayList<>(); + } + SearchCriteria sc = IdsSearch.create(); + sc.setParameters("id", ids.toArray()); + return lockRows(sc, null, true); + } } diff --git a/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceLimitDao.java b/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceLimitDao.java index e47b38340c2..7cdc2aacc3b 100644 --- a/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceLimitDao.java +++ b/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceLimitDao.java @@ -18,6 +18,7 @@ package com.cloud.configuration.dao; import java.util.List; +import com.cloud.configuration.Resource; import com.cloud.configuration.Resource.ResourceOwnerType; import com.cloud.configuration.ResourceCount; import com.cloud.configuration.ResourceLimitVO; @@ -31,7 +32,8 @@ public interface ResourceLimitDao extends GenericDao { ResourceCount.ResourceType getLimitType(String type); - ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type); + ResourceLimitVO findByOwnerIdAndTypeAndTag(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type, String tag); long removeEntriesByOwner(Long ownerId, ResourceOwnerType ownerType); + void removeResourceLimitsForNonMatchingTags(Long ownerId, ResourceOwnerType ownerType, List types, List tags); } diff --git a/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceLimitDaoImpl.java b/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceLimitDaoImpl.java index 03c2d2a4624..96523ba9bea 100644 --- a/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceLimitDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/configuration/dao/ResourceLimitDaoImpl.java @@ -20,6 +20,8 @@ import java.util.ArrayList; import java.util.List; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.ObjectUtils; import org.springframework.stereotype.Component; import com.cloud.configuration.Resource; @@ -33,19 +35,36 @@ import com.cloud.utils.db.SearchCriteria; @Component public class ResourceLimitDaoImpl extends GenericDaoBase implements ResourceLimitDao { - private SearchBuilder IdTypeSearch; + private SearchBuilder IdTypeTagSearch; + private SearchBuilder IdTypeNullTagSearch; + private SearchBuilder NonMatchingTagsSearch; public ResourceLimitDaoImpl() { - IdTypeSearch = createSearchBuilder(); - IdTypeSearch.and("type", IdTypeSearch.entity().getType(), SearchCriteria.Op.EQ); - IdTypeSearch.and("domainId", IdTypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ); - IdTypeSearch.and("accountId", IdTypeSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - IdTypeSearch.done(); + IdTypeTagSearch = createSearchBuilder(); + IdTypeTagSearch.and("type", IdTypeTagSearch.entity().getType(), SearchCriteria.Op.EQ); + IdTypeTagSearch.and("domainId", IdTypeTagSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + IdTypeTagSearch.and("accountId", IdTypeTagSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + IdTypeTagSearch.and("tag", IdTypeTagSearch.entity().getTag(), SearchCriteria.Op.EQ); + + IdTypeNullTagSearch = createSearchBuilder(); + IdTypeNullTagSearch.and("type", IdTypeNullTagSearch.entity().getType(), SearchCriteria.Op.EQ); + IdTypeNullTagSearch.and("domainId", IdTypeNullTagSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + IdTypeNullTagSearch.and("accountId", IdTypeNullTagSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + IdTypeNullTagSearch.and("tag", IdTypeNullTagSearch.entity().getTag(), SearchCriteria.Op.NULL); + IdTypeNullTagSearch.done(); + + NonMatchingTagsSearch = createSearchBuilder(); + NonMatchingTagsSearch.and("accountId", NonMatchingTagsSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + NonMatchingTagsSearch.and("domainId", NonMatchingTagsSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + NonMatchingTagsSearch.and("types", NonMatchingTagsSearch.entity().getType(), SearchCriteria.Op.IN); + NonMatchingTagsSearch.and("tagNotNull", NonMatchingTagsSearch.entity().getTag(), SearchCriteria.Op.NNULL); + NonMatchingTagsSearch.and("tags", NonMatchingTagsSearch.entity().getTag(), SearchCriteria.Op.NIN); + NonMatchingTagsSearch.done(); } @Override public List listByOwner(Long ownerId, ResourceOwnerType ownerType) { - SearchCriteria sc = IdTypeSearch.create(); + SearchCriteria sc = IdTypeTagSearch.create(); if (ownerType == ResourceOwnerType.Account) { sc.setParameters("accountId", ownerId); @@ -81,9 +100,12 @@ public class ResourceLimitDaoImpl extends GenericDaoBase } @Override - public ResourceLimitVO findByOwnerIdAndType(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type) { - SearchCriteria sc = IdTypeSearch.create(); + public ResourceLimitVO findByOwnerIdAndTypeAndTag(long ownerId, ResourceOwnerType ownerType, ResourceCount.ResourceType type, String tag) { + SearchCriteria sc = tag != null ? IdTypeTagSearch.create() : IdTypeNullTagSearch.create(); sc.setParameters("type", type); + if (tag != null) { + sc.setParameters("tag", tag); + } if (ownerType == ResourceOwnerType.Account) { sc.setParameters("accountId", ownerId); @@ -98,7 +120,7 @@ public class ResourceLimitDaoImpl extends GenericDaoBase @Override public long removeEntriesByOwner(Long ownerId, ResourceOwnerType ownerType) { - SearchCriteria sc = IdTypeSearch.create(); + SearchCriteria sc = IdTypeTagSearch.create(); if (ownerType == ResourceOwnerType.Account) { sc.setParameters("accountId", ownerId); @@ -109,4 +131,23 @@ public class ResourceLimitDaoImpl extends GenericDaoBase } return 0; } + + @Override + public void removeResourceLimitsForNonMatchingTags(Long ownerId, ResourceOwnerType ownerType, List types, List tags) { + SearchCriteria sc = NonMatchingTagsSearch.create(); + if (ObjectUtils.allNotNull(ownerId, ownerType)) { + if (ResourceOwnerType.Account.equals(ownerType)) { + sc.setParameters("accountId", ownerId); + } else { + sc.setParameters("domainId", ownerId); + } + } + if (CollectionUtils.isNotEmpty(types)) { + sc.setParameters("types", types.stream().map(ResourceType::getName).toArray()); + } + if (CollectionUtils.isNotEmpty(tags)) { + sc.setParameters("tags", tags.toArray()); + } + remove(sc); + } } diff --git a/engine/schema/src/main/java/com/cloud/dc/ASNumberRangeVO.java b/engine/schema/src/main/java/com/cloud/dc/ASNumberRangeVO.java new file mode 100644 index 00000000000..3790213b3ad --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/dc/ASNumberRangeVO.java @@ -0,0 +1,104 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.dc; + +import com.cloud.bgp.ASNumberRange; +import com.cloud.utils.db.GenericDao; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.UUID; + +@Entity +@Table(name = "as_number_range") +public class ASNumberRangeVO implements ASNumberRange { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "uuid") + private String uuid; + + @Column(name = "data_center_id") + private long dataCenterId; + + @Column(name = "start_as_number") + private long startASNumber; + + @Column(name = "end_as_number") + private long endASNumber; + + @Column(name = GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name = GenericDao.CREATED_COLUMN) + private Date created; + + public ASNumberRangeVO() { + this.uuid = UUID.randomUUID().toString(); + this.created = GregorianCalendar.getInstance().getTime(); + } + + public ASNumberRangeVO(long dataCenterId, long startASNumber, long endASNumber) { + this(); + this.dataCenterId = dataCenterId; + this.startASNumber = startASNumber; + this.endASNumber = endASNumber; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getUuid() { + return uuid; + } + + @Override + public long getDataCenterId() { + return dataCenterId; + } + + @Override + public long getStartASNumber() { + return startASNumber; + } + + @Override + public long getEndASNumber() { + return endASNumber; + } + + public Date getRemoved() { + return removed; + } + + @Override + public Date getCreated() { + return created; + } +} diff --git a/engine/schema/src/main/java/com/cloud/dc/ASNumberVO.java b/engine/schema/src/main/java/com/cloud/dc/ASNumberVO.java new file mode 100644 index 00000000000..529d1cfb5fe --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/dc/ASNumberVO.java @@ -0,0 +1,178 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.dc; + +import com.cloud.bgp.ASNumber; +import com.cloud.utils.db.GenericDao; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import java.util.Date; +import java.util.UUID; + +@Entity +@Table(name = "as_number") +public class ASNumberVO implements ASNumber { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "uuid") + private String uuid; + + @Column(name = "account_id") + private Long accountId; + + @Column(name = "domain_id") + private Long domainId; + + @Column(name = "as_number") + private long asNumber; + + @Column(name = "as_number_range_id") + private long asNumberRangeId; + + @Column(name = "data_center_id") + private long dataCenterId; + + @Column(name = "allocated") + @Temporal(value = TemporalType.TIMESTAMP) + private Date allocatedTime; + + @Column(name = "is_allocated") + private boolean allocated; + + @Column(name = "network_id") + private Long networkId; + + @Column(name = "vpc_id") + private Long vpcId; + + @Column(name = GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name = GenericDao.CREATED_COLUMN) + private Date created; + + public ASNumberVO() { + this.uuid = UUID.randomUUID().toString(); + this.created = new Date(); + } + + public ASNumberVO(long asNumber, long asNumberRangeId, long dataCenterId) { + this(); + this.asNumber = asNumber; + this.asNumberRangeId = asNumberRangeId; + this.dataCenterId = dataCenterId; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setAccountId(Long accountId) { + this.accountId = accountId; + } + + @Override + public Long getAccountId() { + return accountId; + } + + public void setDomainId(Long domainId) { + this.domainId = domainId; + } + + @Override + public Long getDomainId() { + return domainId; + } + + @Override + public long getAsNumber() { + return asNumber; + } + + @Override + public long getAsNumberRangeId() { + return asNumberRangeId; + } + + @Override + public long getDataCenterId() { + return dataCenterId; + } + + public void setAllocatedTime(Date date) { + this.allocatedTime = date; + } + + @Override + public Date getAllocatedTime() { + return allocatedTime; + } + + public void setAllocated(boolean allocated) { + this.allocated = allocated; + } + + @Override + public boolean isAllocated() { + return allocated; + } + + public void setNetworkId(Long networkId) { + this.networkId = networkId; + } + + @Override + public Long getNetworkId() { + return networkId; + } + + @Override + public Date getRemoved() { + return removed; + } + + @Override + public Date getCreated() { + return created; + } + + public Long getVpcId() { + return vpcId; + } + + public void setVpcId(Long vpcId) { + this.vpcId = vpcId; + } +} diff --git a/engine/schema/src/main/java/com/cloud/dc/ClusterDetailsDao.java b/engine/schema/src/main/java/com/cloud/dc/ClusterDetailsDao.java index b54cc8b3c21..27cea8d5c2d 100644 --- a/engine/schema/src/main/java/com/cloud/dc/ClusterDetailsDao.java +++ b/engine/schema/src/main/java/com/cloud/dc/ClusterDetailsDao.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.dc; +import java.util.Collection; import java.util.Map; import com.cloud.utils.db.GenericDao; @@ -30,6 +31,8 @@ public interface ClusterDetailsDao extends GenericDao, R ClusterDetailsVO findDetail(long clusterId, String name); + Map findDetails(long clusterId, Collection names); + void deleteDetails(long clusterId); String getVmwareDcName(Long clusterId); diff --git a/engine/schema/src/main/java/com/cloud/dc/ClusterDetailsDaoImpl.java b/engine/schema/src/main/java/com/cloud/dc/ClusterDetailsDaoImpl.java index 37e10910978..7650b40dd2f 100644 --- a/engine/schema/src/main/java/com/cloud/dc/ClusterDetailsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/dc/ClusterDetailsDaoImpl.java @@ -16,14 +16,16 @@ // under the License. package com.cloud.dc; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; - +import java.util.stream.Collectors; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.ConfigKey.Scope; import org.apache.cloudstack.framework.config.ScopedConfigStorage; +import org.apache.commons.collections.CollectionUtils; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.db.SearchBuilder; @@ -89,6 +91,23 @@ public class ClusterDetailsDaoImpl extends ResourceDetailsDaoBase findDetails(long clusterId, Collection names) { + if (CollectionUtils.isEmpty(names)) { + return new HashMap<>(); + } + SearchBuilder sb = createSearchBuilder(); + sb.and("clusterId", sb.entity().getResourceId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.IN); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("clusterId", clusterId); + sc.setParameters("name", names.toArray()); + List results = search(sc, null); + return results.stream() + .collect(Collectors.toMap(ClusterDetailsVO::getName, ClusterDetailsVO::getValue)); + } + @Override public void deleteDetails(long clusterId) { SearchCriteria sc = ClusterSearch.create(); @@ -142,9 +161,9 @@ public class ClusterDetailsDaoImpl extends ResourceDetailsDaoBase key) { - ClusterDetailsVO vo = findDetail(id, key.key()); - return vo == null ? null : getActualValue(vo); + public String getConfigValue(long id, String key) { + ClusterDetailsVO vo = findDetail(id, key); + return vo == null ? null : vo.getValue(); } @Override diff --git a/engine/schema/src/main/java/com/cloud/dc/ClusterVO.java b/engine/schema/src/main/java/com/cloud/dc/ClusterVO.java index f60765e2856..434901ef5b3 100644 --- a/engine/schema/src/main/java/com/cloud/dc/ClusterVO.java +++ b/engine/schema/src/main/java/com/cloud/dc/ClusterVO.java @@ -16,14 +16,18 @@ // under the License. package com.cloud.dc; +import com.cloud.cpu.CPU; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Cluster; import com.cloud.org.Grouping; import com.cloud.org.Managed.ManagedState; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.util.CPUArchConverter; +import org.apache.cloudstack.util.HypervisorTypeConverter; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; @@ -56,6 +60,7 @@ public class ClusterVO implements Cluster { long podId; @Column(name = "hypervisor_type") + @Convert(converter = HypervisorTypeConverter.class) String hypervisorType; @Column(name = "cluster_type") @@ -66,6 +71,10 @@ public class ClusterVO implements Cluster { @Enumerated(value = EnumType.STRING) AllocationState allocationState; + @Column(name = "arch") + @Convert(converter = CPUArchConverter.class) + private String arch; + @Column(name = "managed_state") @Enumerated(value = EnumType.STRING) ManagedState managedState; @@ -197,6 +206,15 @@ public class ClusterVO implements Cluster { return PartitionType.Cluster; } + @Override + public CPU.CPUArch getArch() { + return CPU.CPUArch.fromType(arch); + } + + public void setArch(String arch) { + this.arch = arch; + } + @Override public String toString() { return String.format("Cluster {id: \"%s\", name: \"%s\", uuid: \"%s\"}", id, name, uuid); diff --git a/engine/schema/src/main/java/com/cloud/dc/DataCenterIpAddressVO.java b/engine/schema/src/main/java/com/cloud/dc/DataCenterIpAddressVO.java index 3d68cc3d9a8..874b05673eb 100644 --- a/engine/schema/src/main/java/com/cloud/dc/DataCenterIpAddressVO.java +++ b/engine/schema/src/main/java/com/cloud/dc/DataCenterIpAddressVO.java @@ -55,7 +55,7 @@ public class DataCenterIpAddressVO implements InternalIdentity { String reservationId; @Column(name = "nic_id") - private Long instanceId; + private Long nicId; @Column(name = "mac_address") long macAddress; @@ -88,12 +88,12 @@ public class DataCenterIpAddressVO implements InternalIdentity { return id; } - public Long getInstanceId() { - return instanceId; + public Long getNicId() { + return nicId; } - public void setInstanceId(Long instanceId) { - this.instanceId = instanceId; + public void setNicId(Long nicId) { + this.nicId = nicId; } public long getPodId() { diff --git a/engine/schema/src/main/java/com/cloud/dc/HostPodVO.java b/engine/schema/src/main/java/com/cloud/dc/HostPodVO.java index d9971815f5e..fdda38fbc39 100644 --- a/engine/schema/src/main/java/com/cloud/dc/HostPodVO.java +++ b/engine/schema/src/main/java/com/cloud/dc/HostPodVO.java @@ -31,6 +31,7 @@ import javax.persistence.Table; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "host_pod_ref") @@ -197,4 +198,11 @@ public class HostPodVO implements Pod { public void setUuid(String uuid) { this.uuid = uuid; } + + @Override + public String toString() { + return String.format("HostPod %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); + } } diff --git a/engine/schema/src/main/java/com/cloud/dc/VlanVO.java b/engine/schema/src/main/java/com/cloud/dc/VlanVO.java index 7423ded598f..c271325f3de 100644 --- a/engine/schema/src/main/java/com/cloud/dc/VlanVO.java +++ b/engine/schema/src/main/java/com/cloud/dc/VlanVO.java @@ -29,6 +29,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "vlan") @@ -192,24 +193,11 @@ public class VlanVO implements Vlan { @Override public String toString() { if (toString == null) { - toString = - new StringBuilder("Vlan[").append(vlanTag) - .append("|") - .append(vlanGateway) - .append("|") - .append(vlanNetmask) - .append("|") - .append(ip6Gateway) - .append("|") - .append(ip6Cidr) - .append("|") - .append(ipRange) - .append("|") - .append(ip6Range) - .append("|") - .append(networkId) - .append("]") - .toString(); + toString = String.format("Vlan %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "uuid", + "vlanTag", "vlanGateway", "vlanNetmask", "ip6Gateway", "ip6Cidr", + "ipRange", "ip6Range", "networkId")); + } return toString; } diff --git a/engine/schema/src/main/java/com/cloud/dc/VmwareDatacenterVO.java b/engine/schema/src/main/java/com/cloud/dc/VmwareDatacenterVO.java index 6390d923ed8..5a4a71f82e7 100644 --- a/engine/schema/src/main/java/com/cloud/dc/VmwareDatacenterVO.java +++ b/engine/schema/src/main/java/com/cloud/dc/VmwareDatacenterVO.java @@ -28,6 +28,7 @@ import javax.persistence.Table; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.Encrypt; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; /** * VmwareDatacenterVO contains information of Vmware Datacenter associated with a CloudStack zone. @@ -125,7 +126,9 @@ public class VmwareDatacenterVO implements VmwareDatacenter { @Override public String toString() { - return new StringBuilder("VmwareDatacenter[").append(guid).append("]").toString(); + return String.format("VmwareDatacenter %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "guid")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberDao.java b/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberDao.java new file mode 100644 index 00000000000..192f6bbaf31 --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberDao.java @@ -0,0 +1,41 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.dc.dao; + +import com.cloud.dc.ASNumberVO; +import com.cloud.user.Account; +import com.cloud.utils.Pair; +import com.cloud.utils.db.GenericDao; + +import java.util.List; + +public interface ASNumberDao extends GenericDao { + + Pair, Integer> searchAndCountByZoneOrRangeOrAllocated(Long zoneId, Long asnRangeId, Integer asNumber, Long networkId, Long vpcId, + Boolean allocated, Long accountId, Long domainId, String keyword, Account caller, + Long startIndex, Long pageSizeVal); + ASNumberVO findByAsNumber(Long asNumber); + + ASNumberVO findOneByAllocationStateAndZone(long zoneId, boolean allocated); + + List listAllocatedByASRange(Long asRangeId); + + ASNumberVO findByZoneAndNetworkId(long zoneId, long networkId); + ASNumberVO findByZoneAndVpcId(long zoneId, long vpcId); + + int removeASRangeNumbers(long rangeId); +} diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberDaoImpl.java b/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberDaoImpl.java new file mode 100644 index 00000000000..1d2adf4d424 --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberDaoImpl.java @@ -0,0 +1,141 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.dc.dao; + +import com.cloud.dc.ASNumberVO; +import com.cloud.user.Account; +import com.cloud.utils.Pair; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +import java.util.Arrays; +import java.util.List; + +public class ASNumberDaoImpl extends GenericDaoBase implements ASNumberDao { + + private final SearchBuilder asNumberSearch; + + public ASNumberDaoImpl() { + asNumberSearch = createSearchBuilder(); + asNumberSearch.and("zoneId", asNumberSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + asNumberSearch.and("rangeId", asNumberSearch.entity().getAsNumberRangeId(), SearchCriteria.Op.EQ); + asNumberSearch.and("isAllocated", asNumberSearch.entity().isAllocated(), SearchCriteria.Op.EQ); + asNumberSearch.and("asNumber", asNumberSearch.entity().getAsNumber(), SearchCriteria.Op.EQ); + asNumberSearch.and("networkId", asNumberSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); + asNumberSearch.and("vpcId", asNumberSearch.entity().getVpcId(), SearchCriteria.Op.EQ); + asNumberSearch.and("accountId", asNumberSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + asNumberSearch.and("domainId", asNumberSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + asNumberSearch.done(); + } + + @Override + public Pair, Integer> searchAndCountByZoneOrRangeOrAllocated(Long zoneId, Long asnRangeId, + Integer asNumber, Long networkId, Long vpcId, + Boolean allocated, + Long accountId, Long domainId, + String keyword, Account caller, + Long startIndex, Long pageSizeVal) { + SearchCriteria sc = asNumberSearch.create(); + if (zoneId != null) { + sc.setParameters("zoneId", zoneId); + } + if (asnRangeId != null) { + sc.setParameters("rangeId", asnRangeId); + } + if (networkId != null) { + sc.setParameters("networkId", networkId); + } + if (vpcId != null) { + sc.setParameters("vpcId", vpcId); + } + if (allocated != null) { + sc.setParameters("isAllocated", allocated); + } + if (asNumber != null) { + sc.setParameters("asNumber", asNumber); + } + if (accountId != null) { + sc.setParameters("accountId", accountId); + } + if (domainId != null) { + sc.setParameters("domainId", domainId); + } + if (keyword != null) { + sc.addAnd("asNumber", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + } + if (Arrays.asList(Account.Type.DOMAIN_ADMIN, Account.Type.RESOURCE_DOMAIN_ADMIN).contains(caller.getType())) { + SearchCriteria scc = asNumberSearch.create(); + scc.addOr("domainId", SearchCriteria.Op.NULL); + scc.addOr("domainId", SearchCriteria.Op.EQ, caller.getDomainId()); + sc.addAnd("domainId", SearchCriteria.Op.SC, scc); + } else if (Arrays.asList(Account.Type.NORMAL, Account.Type.PROJECT).contains(caller.getType())) { + SearchCriteria scc = asNumberSearch.create(); + scc.addOr("domainId", SearchCriteria.Op.NULL); + scc.addOr("accountId", SearchCriteria.Op.EQ, caller.getAccountId()); + sc.addAnd("domainId", SearchCriteria.Op.SC, scc); + } + Filter searchFilter = new Filter(ASNumberVO.class, "id", true, startIndex, pageSizeVal); + return searchAndCount(sc, searchFilter); + } + + @Override + public ASNumberVO findByAsNumber(Long asNumber) { + SearchCriteria sc = asNumberSearch.create(); + sc.setParameters("asNumber", asNumber); + return findOneBy(sc); + } + + @Override + public ASNumberVO findOneByAllocationStateAndZone(long zoneId, boolean allocated) { + SearchCriteria sc = asNumberSearch.create(); + sc.setParameters("zoneId", zoneId); + sc.setParameters("isAllocated", allocated); + return findOneBy(sc); + } + + @Override + public List listAllocatedByASRange(Long asRangeId) { + SearchCriteria sc = asNumberSearch.create(); + sc.setParameters("rangeId", asRangeId); + sc.setParameters("isAllocated", true); + return listBy(sc); + } + + public ASNumberVO findByZoneAndNetworkId(long zoneId, long networkId) { + SearchCriteria sc = asNumberSearch.create(); + sc.setParameters("zoneId", zoneId); + sc.setParameters("networkId", networkId); + return findOneBy(sc); + } + + @Override + public ASNumberVO findByZoneAndVpcId(long zoneId, long vpcId) { + SearchCriteria sc = asNumberSearch.create(); + sc.setParameters("zoneId", zoneId); + sc.setParameters("vpcId", vpcId); + return findOneBy(sc); + } + + @Override + public int removeASRangeNumbers(long rangeId) { + SearchCriteria sc = asNumberSearch.create(); + sc.setParameters("rangeId", rangeId); + return remove(sc); + } +} diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberRangeDao.java b/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberRangeDao.java new file mode 100644 index 00000000000..3309a6f5fe5 --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberRangeDao.java @@ -0,0 +1,27 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.dc.dao; + +import com.cloud.dc.ASNumberRangeVO; +import com.cloud.utils.db.GenericDao; + +import java.util.List; + +public interface ASNumberRangeDao extends GenericDao { + + List listByZoneId(long zoneId); +} diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberRangeDaoImpl.java b/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberRangeDaoImpl.java new file mode 100644 index 00000000000..4a4170685dc --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/dc/dao/ASNumberRangeDaoImpl.java @@ -0,0 +1,42 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.dc.dao; + +import com.cloud.dc.ASNumberRangeVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +import java.util.List; + +public class ASNumberRangeDaoImpl extends GenericDaoBase implements ASNumberRangeDao { + + private final SearchBuilder searchBuilder; + + public ASNumberRangeDaoImpl() { + searchBuilder = createSearchBuilder(); + searchBuilder.and("zoneId", searchBuilder.entity().getDataCenterId(), SearchCriteria.Op.EQ); + searchBuilder.done(); + } + + @Override + public List listByZoneId(long zoneId) { + SearchCriteria sc = searchBuilder.create(); + sc.setParameters("zoneId", zoneId); + return listBy(sc); + } +} diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/ClusterDao.java b/engine/schema/src/main/java/com/cloud/dc/dao/ClusterDao.java index ab9c5cab8c4..69b5f0e146e 100644 --- a/engine/schema/src/main/java/com/cloud/dc/dao/ClusterDao.java +++ b/engine/schema/src/main/java/com/cloud/dc/dao/ClusterDao.java @@ -16,26 +16,25 @@ // under the License. package com.cloud.dc.dao; -import com.cloud.dc.ClusterVO; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.utils.db.GenericDao; - import java.util.List; import java.util.Map; -import java.util.Set; + +import com.cloud.cpu.CPU; +import com.cloud.dc.ClusterVO; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.utils.Pair; +import com.cloud.utils.db.GenericDao; public interface ClusterDao extends GenericDao { List listByPodId(long podId); ClusterVO findBy(String name, long podId); - List listByHyTypeWithoutGuid(String hyType); - List listByZoneId(long zoneId); List getAvailableHypervisorInZone(Long zoneId); - Set getDistictAvailableHypervisorsAcrossClusters(); + List> listDistinctHypervisorsArchAcrossClusters(Long zoneId); List listByDcHyType(long dcId, String hyType); @@ -45,9 +44,17 @@ public interface ClusterDao extends GenericDao { List listClustersWithDisabledPods(long zoneId); + Integer countAllByDcId(long zoneId); + + Integer countAllManagedAndEnabledByDcId(long zoneId); + List listClustersByDcId(long zoneId); - List listAllClusters(Long zoneId); + List listAllClusterIds(Long zoneId); boolean getSupportsResigning(long clusterId); + + List getClustersArchsByZone(long zoneId); + + List listClustersByArchAndZoneId(long zoneId, CPU.CPUArch arch); } diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/ClusterDaoImpl.java b/engine/schema/src/main/java/com/cloud/dc/dao/ClusterDaoImpl.java index 4d9bedba966..59614b54745 100644 --- a/engine/schema/src/main/java/com/cloud/dc/dao/ClusterDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/dc/dao/ClusterDaoImpl.java @@ -16,12 +16,28 @@ // under the License. package com.cloud.dc.dao; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import javax.inject.Inject; + +import org.springframework.stereotype.Component; + +import com.cloud.cpu.CPU; import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.ClusterDetailsVO; import com.cloud.dc.ClusterVO; import com.cloud.dc.HostPodVO; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Grouping; +import com.cloud.org.Managed; +import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.JoinBuilder; @@ -31,18 +47,6 @@ import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.exception.CloudRuntimeException; -import org.springframework.stereotype.Component; - -import javax.inject.Inject; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; @Component public class ClusterDaoImpl extends GenericDaoBase implements ClusterDao { @@ -54,7 +58,8 @@ public class ClusterDaoImpl extends GenericDaoBase implements C protected final SearchBuilder ZoneHyTypeSearch; protected final SearchBuilder ZoneClusterSearch; protected final SearchBuilder ClusterSearch; - + protected final SearchBuilder ClusterDistinctArchSearch; + protected final SearchBuilder ClusterArchSearch; protected GenericSearchBuilder ClusterIdSearch; private static final String GET_POD_CLUSTER_MAP_PREFIX = "SELECT pod_id, id FROM cloud.cluster WHERE cluster.id IN( "; @@ -94,6 +99,8 @@ public class ClusterDaoImpl extends GenericDaoBase implements C ZoneClusterSearch = createSearchBuilder(); ZoneClusterSearch.and("dataCenterId", ZoneClusterSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + ZoneClusterSearch.and("allocationState", ZoneClusterSearch.entity().getAllocationState(), Op.EQ); + ZoneClusterSearch.and("managedState", ZoneClusterSearch.entity().getManagedState(), Op.EQ); ZoneClusterSearch.done(); ClusterIdSearch = createSearchBuilder(Long.class); @@ -104,6 +111,16 @@ public class ClusterDaoImpl extends GenericDaoBase implements C ClusterSearch = createSearchBuilder(); ClusterSearch.select(null, Func.DISTINCT, ClusterSearch.entity().getHypervisorType()); ClusterIdSearch.done(); + + ClusterDistinctArchSearch = createSearchBuilder(); + ClusterDistinctArchSearch.and("dataCenterId", ClusterDistinctArchSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + ClusterDistinctArchSearch.select(null, Func.DISTINCT, ClusterDistinctArchSearch.entity().getArch()); + ClusterDistinctArchSearch.done(); + + ClusterArchSearch = createSearchBuilder(); + ClusterArchSearch.and("dataCenterId", ClusterArchSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + ClusterArchSearch.and("arch", ClusterArchSearch.entity().getArch(), SearchCriteria.Op.EQ); + ClusterArchSearch.done(); } @Override @@ -130,14 +147,6 @@ public class ClusterDaoImpl extends GenericDaoBase implements C return findOneBy(sc); } - @Override - public List listByHyTypeWithoutGuid(String hyType) { - SearchCriteria sc = HyTypeWithoutGuidSearch.create(); - sc.setParameters("hypervisorType", hyType); - - return listBy(sc); - } - @Override public List listByDcHyType(long dcId, String hyType) { SearchCriteria sc = ZoneHyTypeSearch.create(); @@ -153,23 +162,26 @@ public class ClusterDaoImpl extends GenericDaoBase implements C sc.setParameters("zoneId", zoneId); } List clusters = listBy(sc); - List hypers = new ArrayList(4); - for (ClusterVO cluster : clusters) { - hypers.add(cluster.getHypervisorType()); - } - - return hypers; + return clusters.stream() + .map(ClusterVO::getHypervisorType) + .distinct() + .collect(Collectors.toList()); } @Override - public Set getDistictAvailableHypervisorsAcrossClusters() { - SearchCriteria sc = ClusterSearch.create(); - List clusters = listBy(sc); - Set hypers = new HashSet<>(); - for (ClusterVO cluster : clusters) { - hypers.add(cluster.getHypervisorType()); + public List> listDistinctHypervisorsArchAcrossClusters(Long zoneId) { + SearchBuilder sb = createSearchBuilder(); + sb.select(null, Func.DISTINCT_PAIR, sb.entity().getHypervisorType(), sb.entity().getArch()); + sb.and("zoneId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.done(); + SearchCriteria sc = sb.create(); + if (zoneId != null) { + sc.setParameters("zoneId", zoneId); } - return hypers; + final List clusters = search(sc, null); + return clusters.stream() + .map(c -> new Pair<>(c.getHypervisorType(), c.getArch())) + .collect(Collectors.toList()); } @Override @@ -252,6 +264,23 @@ public class ClusterDaoImpl extends GenericDaoBase implements C return customSearch(sc, null); } + @Override + public Integer countAllByDcId(long zoneId) { + SearchCriteria sc = ZoneClusterSearch.create(); + sc.setParameters("dataCenterId", zoneId); + return getCount(sc); + } + + @Override + public Integer countAllManagedAndEnabledByDcId(long zoneId) { + SearchCriteria sc = ZoneClusterSearch.create(); + sc.setParameters("dataCenterId", zoneId); + sc.setParameters("allocationState", Grouping.AllocationState.Enabled); + sc.setParameters("managedState", Managed.ManagedState.Managed); + + return getCount(sc); + } + @Override public List listClustersByDcId(long zoneId) { SearchCriteria sc = ZoneClusterSearch.create(); @@ -275,7 +304,7 @@ public class ClusterDaoImpl extends GenericDaoBase implements C } @Override - public List listAllClusters(Long zoneId) { + public List listAllClusterIds(Long zoneId) { SearchCriteria sc = ClusterIdSearch.create(); if (zoneId != null) { sc.setParameters("dataCenterId", zoneId); @@ -301,4 +330,20 @@ public class ClusterDaoImpl extends GenericDaoBase implements C return false; } + + @Override + public List getClustersArchsByZone(long zoneId) { + SearchCriteria sc = ClusterDistinctArchSearch.create(); + sc.setParameters("dataCenterId", zoneId); + List clusters = listBy(sc); + return clusters.stream().map(ClusterVO::getArch).collect(Collectors.toList()); + } + + @Override + public List listClustersByArchAndZoneId(long zoneId, CPU.CPUArch arch) { + SearchCriteria sc = ClusterArchSearch.create(); + sc.setParameters("dataCenterId", zoneId); + sc.setParameters("arch", arch); + return listBy(sc); + } } diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterDaoImpl.java b/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterDaoImpl.java index 491919bbca7..7719e5adfc7 100644 --- a/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterDaoImpl.java @@ -26,7 +26,6 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.dc.DataCenter; @@ -55,7 +54,6 @@ import com.cloud.utils.db.TransactionLegacy; **/ @Component public class DataCenterDaoImpl extends GenericDaoBase implements DataCenterDao { - private static final Logger s_logger = Logger.getLogger(DataCenterDaoImpl.class); protected SearchBuilder NameSearch; protected SearchBuilder ListZonesByDomainIdSearch; @@ -166,8 +164,8 @@ public class DataCenterDaoImpl extends GenericDaoBase implem } @Override - public void releasePrivateIpAddress(String ipAddress, long dcId, Long instanceId) { - _ipAllocDao.releaseIpAddress(ipAddress, dcId, instanceId); + public void releasePrivateIpAddress(String ipAddress, long dcId, Long nicId) { + _ipAllocDao.releaseIpAddress(ipAddress, dcId, nicId); } @Override @@ -181,8 +179,8 @@ public class DataCenterDaoImpl extends GenericDaoBase implem } @Override - public void releaseLinkLocalIpAddress(String ipAddress, long dcId, Long instanceId) { - _linkLocalIpAllocDao.releaseIpAddress(ipAddress, dcId, instanceId); + public void releaseLinkLocalIpAddress(String ipAddress, long dcId, Long nicId) { + _linkLocalIpAllocDao.releaseIpAddress(ipAddress, dcId, nicId); } @Override @@ -228,9 +226,9 @@ public class DataCenterDaoImpl extends GenericDaoBase implem } @Override - public PrivateAllocationData allocatePrivateIpAddress(long dcId, long podId, long instanceId, String reservationId, boolean forSystemVms) { - _ipAllocDao.releaseIpAddress(instanceId); - DataCenterIpAddressVO vo = _ipAllocDao.takeIpAddress(dcId, podId, instanceId, reservationId, forSystemVms); + public PrivateAllocationData allocatePrivateIpAddress(long dcId, long podId, long nicId, String reservationId, boolean forSystemVms) { + _ipAllocDao.releaseIpAddress(nicId); + DataCenterIpAddressVO vo = _ipAllocDao.takeIpAddress(dcId, podId, nicId, reservationId, forSystemVms); if (vo == null) { return null; } @@ -244,8 +242,8 @@ public class DataCenterDaoImpl extends GenericDaoBase implem } @Override - public String allocateLinkLocalIpAddress(long dcId, long podId, long instanceId, String reservationId) { - DataCenterLinkLocalIpAddressVO vo = _linkLocalIpAllocDao.takeIpAddress(dcId, podId, instanceId, reservationId); + public String allocateLinkLocalIpAddress(long dcId, long podId, long nicId, String reservationId) { + DataCenterLinkLocalIpAddressVO vo = _linkLocalIpAllocDao.takeIpAddress(dcId, podId, nicId, reservationId); if (vo == null) { return null; } @@ -405,7 +403,7 @@ public class DataCenterDaoImpl extends GenericDaoBase implem Long dcId = Long.parseLong(tokenOrIdOrName); return findById(dcId); } catch (NumberFormatException nfe) { - s_logger.debug("Cannot parse " + tokenOrIdOrName + " into long. " + nfe); + logger.debug("Cannot parse " + tokenOrIdOrName + " into long. " + nfe); } } } diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterDetailsDaoImpl.java b/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterDetailsDaoImpl.java index 27210dfcf0d..bb03a96d02e 100644 --- a/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterDetailsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterDetailsDaoImpl.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.dc.dao; +import org.apache.cloudstack.api.ResourceDetail; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.ConfigKey.Scope; import org.apache.cloudstack.framework.config.ScopedConfigStorage; @@ -43,9 +44,9 @@ public class DataCenterDetailsDaoImpl extends ResourceDetailsDaoBase key) { - DataCenterDetailVO vo = findDetail(id, key.key()); - return vo == null ? null : getActualValue(vo); + public String getConfigValue(long id, String key) { + ResourceDetail vo = findDetail(id, key); + return vo == null ? null : vo.getValue(); } @Override diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterIpAddressDaoImpl.java b/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterIpAddressDaoImpl.java index e58b08da4c1..ba01e31f80a 100644 --- a/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterIpAddressDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterIpAddressDaoImpl.java @@ -23,7 +23,6 @@ import java.util.List; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.dc.DataCenterIpAddressVO; @@ -40,7 +39,6 @@ import com.cloud.utils.net.NetUtils; @Component @DB public class DataCenterIpAddressDaoImpl extends GenericDaoBase implements DataCenterIpAddressDao, Configurable { - private static final Logger s_logger = Logger.getLogger(DataCenterIpAddressDaoImpl.class); private final SearchBuilder AllFieldsSearch; private final GenericSearchBuilder AllIpCount; @@ -53,7 +51,7 @@ public class DataCenterIpAddressDaoImpl extends GenericDaoBase sc = AllFieldsSearch.create(); sc.setParameters("pod", podId); sc.setParameters("taken", (Date)null); @@ -73,7 +71,7 @@ public class DataCenterIpAddressDaoImpl extends GenericDaoBase sc = AllFieldsSearch.create(); sc.setParameters("ip", ipAddress); sc.setParameters("dc", dcId); - sc.setParameters("instance", instanceId); + sc.setParameters("nic", nicId); DataCenterIpAddressVO vo = createForUpdate(); vo.setTakenAt(null); - vo.setInstanceId(null); + vo.setNicId(null); vo.setReservationId(null); update(vo, sc); } @Override public void releaseIpAddress(long nicId, String reservationId) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Releasing ip address for reservationId=" + reservationId + ", instance=" + nicId); + if (logger.isDebugEnabled()) { + logger.debug("Releasing ip address for reservationId=" + reservationId + ", nic=" + nicId); } SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("instance", nicId); + sc.setParameters("nic", nicId); sc.setParameters("reservation", reservationId); DataCenterIpAddressVO vo = createForUpdate(); vo.setTakenAt(null); - vo.setInstanceId(null); + vo.setNicId(null); vo.setReservationId(null); update(vo, sc); } @Override public void releasePodIpAddress(long id) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Releasing ip address for ID=" + id); + if (logger.isDebugEnabled()) { + logger.debug("Releasing ip address for ID=" + id); } DataCenterIpAddressVO vo = this.findById(id); vo.setTakenAt(null); - vo.setInstanceId(null); + vo.setNicId(null); vo.setReservationId(null); persist(vo); } @Override public void releaseIpAddress(long nicId) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Releasing ip address for instance=" + nicId); + if (logger.isDebugEnabled()) { + logger.debug("Releasing ip address for nic=" + nicId); } SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("instance", nicId); + sc.setParameters("nic", nicId); DataCenterIpAddressVO vo = createForUpdate(); vo.setTakenAt(null); - vo.setInstanceId(null); + vo.setNicId(null); vo.setReservationId(null); update(vo, sc); } @@ -296,8 +294,7 @@ public class DataCenterIpAddressDaoImpl extends GenericDaoBase result = listBy(sc); - return result.size(); + return getCount(sc); } public DataCenterIpAddressDaoImpl() { @@ -307,7 +304,7 @@ public class DataCenterIpAddressDaoImpl extends GenericDaoBase implements DataCenterLinkLocalIpAddressDao { - private static final Logger s_logger = Logger.getLogger(DataCenterLinkLocalIpAddressDaoImpl.class); private final SearchBuilder AllFieldsSearch; private final GenericSearchBuilder AllIpCount; @@ -105,8 +103,8 @@ public class DataCenterLinkLocalIpAddressDaoImpl extends GenericDaoBase sc = AllFieldsSearch.create(); sc.setParameters("ip", ipAddress); diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterVnetDaoImpl.java b/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterVnetDaoImpl.java index 1c29e6a944c..ff668249779 100644 --- a/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterVnetDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/dc/dao/DataCenterVnetDaoImpl.java @@ -81,7 +81,7 @@ public class DataCenterVnetDaoImpl extends GenericDaoBase sc = DcSearchAllocated.create(); sc.setParameters("physicalNetworkId", physicalNetworkId); - return listBy(sc).size(); + return getCount(sc); } @Override diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/HostPodDaoImpl.java b/engine/schema/src/main/java/com/cloud/dc/dao/HostPodDaoImpl.java index 3fbeb58c56f..f1835067380 100644 --- a/engine/schema/src/main/java/com/cloud/dc/dao/HostPodDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/dc/dao/HostPodDaoImpl.java @@ -24,7 +24,6 @@ import java.util.HashMap; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.dc.HostPodVO; @@ -38,7 +37,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class HostPodDaoImpl extends GenericDaoBase implements HostPodDao { - private static final Logger s_logger = Logger.getLogger(HostPodDaoImpl.class); protected SearchBuilder DataCenterAndNameSearch; protected SearchBuilder DataCenterIdSearch; @@ -100,7 +98,7 @@ public class HostPodDaoImpl extends GenericDaoBase implements H currentPodCidrSubnets.put(podId, cidrPair); } } catch (SQLException ex) { - s_logger.warn("DB exception " + ex.getMessage(), ex); + logger.warn("DB exception " + ex.getMessage(), ex); return null; } diff --git a/engine/schema/src/main/java/com/cloud/dc/dao/VsphereStoragePolicyDaoImpl.java b/engine/schema/src/main/java/com/cloud/dc/dao/VsphereStoragePolicyDaoImpl.java index 0cdb6ad7422..c99fec5a17a 100644 --- a/engine/schema/src/main/java/com/cloud/dc/dao/VsphereStoragePolicyDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/dc/dao/VsphereStoragePolicyDaoImpl.java @@ -20,7 +20,6 @@ import com.cloud.dc.VsphereStoragePolicyVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import java.util.List; @@ -28,7 +27,6 @@ import java.util.List; @Component public class VsphereStoragePolicyDaoImpl extends GenericDaoBase implements VsphereStoragePolicyDao { - protected static final Logger LOGGER = Logger.getLogger(VsphereStoragePolicyDaoImpl.class); private final SearchBuilder zoneSearch; private final SearchBuilder policySearch; diff --git a/engine/schema/src/main/java/com/cloud/domain/DomainVO.java b/engine/schema/src/main/java/com/cloud/domain/DomainVO.java index 05cd4cc492e..c950fa31c88 100644 --- a/engine/schema/src/main/java/com/cloud/domain/DomainVO.java +++ b/engine/schema/src/main/java/com/cloud/domain/DomainVO.java @@ -26,14 +26,16 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import org.apache.log4j.Logger; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.utils.db.GenericDao; @Entity @Table(name = "domain") public class DomainVO implements Domain { - public static final Logger s_logger = Logger.getLogger(DomainVO.class.getName()); + protected transient Logger logger = LogManager.getLogger(getClass()); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -205,7 +207,9 @@ public class DomainVO implements Domain { @Override public String toString() { - return new StringBuilder("Domain:").append(id).append(path).toString(); + return String.format("Domain %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "path")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/domain/dao/DomainDaoImpl.java b/engine/schema/src/main/java/com/cloud/domain/dao/DomainDaoImpl.java index c020493d8f9..74f2932ca43 100644 --- a/engine/schema/src/main/java/com/cloud/domain/dao/DomainDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/domain/dao/DomainDaoImpl.java @@ -25,7 +25,6 @@ import java.util.Set; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.domain.Domain; @@ -40,7 +39,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class DomainDaoImpl extends GenericDaoBase implements DomainDao { - private static final Logger s_logger = Logger.getLogger(DomainDaoImpl.class); protected SearchBuilder DomainNameLikeSearch; protected SearchBuilder ParentDomainNameLikeSearch; @@ -112,7 +110,7 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom DomainVO parentDomain = findById(parent); if (parentDomain == null) { - s_logger.error("Unable to load parent domain: " + parent); + logger.error("Unable to load parent domain: " + parent); return null; } @@ -122,7 +120,7 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom parentDomain = this.lockRow(parent, true); if (parentDomain == null) { - s_logger.error("Unable to lock parent domain: " + parent); + logger.error("Unable to lock parent domain: " + parent); return null; } @@ -137,7 +135,7 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom txn.commit(); return domain; } catch (Exception e) { - s_logger.error("Unable to create domain due to " + e.getMessage(), e); + logger.error("Unable to create domain due to " + e.getMessage(), e); txn.rollback(); return null; } @@ -148,23 +146,23 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom public boolean remove(Long id) { // check for any active users / domains assigned to the given domain id and don't remove the domain if there are any if (id != null && id.longValue() == Domain.ROOT_DOMAIN) { - s_logger.error("Can not remove domain " + id + " as it is ROOT domain"); + logger.error("Can not remove domain " + id + " as it is ROOT domain"); return false; } else { if(id == null) { - s_logger.error("Can not remove domain without id."); + logger.error("Can not remove domain without id."); return false; } } DomainVO domain = findById(id); if (domain == null) { - s_logger.info("Unable to remove domain as domain " + id + " no longer exists"); + logger.info("Unable to remove domain as domain " + id + " no longer exists"); return true; } if (domain.getParent() == null) { - s_logger.error("Invalid domain " + id + ", orphan?"); + logger.error("Invalid domain " + id + ", orphan?"); return false; } @@ -177,7 +175,7 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom txn.start(); DomainVO parentDomain = super.lockRow(domain.getParent(), true); if (parentDomain == null) { - s_logger.error("Unable to load parent domain: " + domain.getParent()); + logger.error("Unable to load parent domain: " + domain.getParent()); return false; } @@ -198,7 +196,7 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom txn.commit(); } catch (SQLException ex) { success = false; - s_logger.error("error removing domain: " + id, ex); + logger.error("error removing domain: " + id, ex); txn.rollback(); } return success; @@ -310,7 +308,7 @@ public class DomainDaoImpl extends GenericDaoBase implements Dom return true; } } catch (NumberFormatException nfe) { - s_logger.debug(String.format("Unable to parse %s as domain ID from the list of domain IDs: %s", domainIdList.trim(), domainIdList), nfe); + logger.debug(String.format("Unable to parse %s as domain ID from the list of domain IDs: %s", domainIdList.trim(), domainIdList), nfe); } } return false; diff --git a/engine/schema/src/main/java/com/cloud/domain/dao/DomainDetailsDaoImpl.java b/engine/schema/src/main/java/com/cloud/domain/dao/DomainDetailsDaoImpl.java index 72532f4ea26..5b4e4c591ff 100644 --- a/engine/schema/src/main/java/com/cloud/domain/dao/DomainDetailsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/domain/dao/DomainDetailsDaoImpl.java @@ -22,6 +22,10 @@ import java.util.Map; import javax.inject.Inject; +import org.apache.cloudstack.framework.config.ConfigKey.Scope; +import org.apache.cloudstack.framework.config.ScopedConfigStorage; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; + import com.cloud.domain.DomainDetailVO; import com.cloud.domain.DomainVO; import com.cloud.utils.db.QueryBuilder; @@ -29,10 +33,6 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.TransactionLegacy; -import org.apache.cloudstack.framework.config.ConfigKey; -import org.apache.cloudstack.framework.config.ConfigKey.Scope; -import org.apache.cloudstack.framework.config.ScopedConfigStorage; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; public class DomainDetailsDaoImpl extends ResourceDetailsDaoBase implements DomainDetailsDao, ScopedConfigStorage { @@ -111,17 +111,17 @@ public class DomainDetailsDaoImpl extends ResourceDetailsDaoBase } @Override - public String getConfigValue(long id, ConfigKey key) { + public String getConfigValue(long id, String key) { DomainDetailVO vo = null; String enableDomainSettingsForChildDomain = _configDao.getValue("enable.domain.settings.for.child.domain"); if (!Boolean.parseBoolean(enableDomainSettingsForChildDomain)) { - vo = findDetail(id, key.key()); + vo = findDetail(id, key); return vo == null ? null : getActualValue(vo); } DomainVO domain = _domainDao.findById(id); // if value is not configured in domain then check its parent domain till ROOT while (domain != null) { - vo = findDetail(domain.getId(), key.key()); + vo = findDetail(domain.getId(), key); if (vo != null) { break; } else if (domain.getParent() != null) { diff --git a/engine/schema/src/main/java/com/cloud/event/dao/EventDaoImpl.java b/engine/schema/src/main/java/com/cloud/event/dao/EventDaoImpl.java index d4627904f0b..e748e98900e 100644 --- a/engine/schema/src/main/java/com/cloud/event/dao/EventDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/event/dao/EventDaoImpl.java @@ -20,7 +20,6 @@ import java.util.Date; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.event.Event.State; @@ -34,7 +33,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class EventDaoImpl extends GenericDaoBase implements EventDao { - public static final Logger s_logger = Logger.getLogger(EventDaoImpl.class.getName()); protected final SearchBuilder CompletedEventSearch; protected final SearchBuilder ToArchiveOrDeleteEventSearch; diff --git a/engine/schema/src/main/java/com/cloud/event/dao/UsageEventDaoImpl.java b/engine/schema/src/main/java/com/cloud/event/dao/UsageEventDaoImpl.java index 519b2ecfe73..fdef509da5b 100644 --- a/engine/schema/src/main/java/com/cloud/event/dao/UsageEventDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/event/dao/UsageEventDaoImpl.java @@ -25,7 +25,6 @@ import java.util.TimeZone; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.dc.Vlan; @@ -42,7 +41,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class UsageEventDaoImpl extends GenericDaoBase implements UsageEventDao { - public static final Logger s_logger = Logger.getLogger(UsageEventDaoImpl.class.getName()); private final SearchBuilder latestEventsSearch; private final SearchBuilder IpeventsSearch; @@ -101,8 +99,8 @@ public class UsageEventDaoImpl extends GenericDaoBase implem // Copy events from cloud db to usage db String sql = COPY_EVENTS; if (recentEventId == 0) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("no recent event date, copying all events"); + if (logger.isDebugEnabled()) { + logger.debug("no recent event date, copying all events"); } sql = COPY_ALL_EVENTS; } @@ -120,7 +118,7 @@ public class UsageEventDaoImpl extends GenericDaoBase implem txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error copying events from cloud db to usage db", ex); + logger.error("error copying events from cloud db to usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } finally { txn.close(); @@ -129,8 +127,8 @@ public class UsageEventDaoImpl extends GenericDaoBase implem // Copy event details from cloud db to usage db sql = COPY_EVENT_DETAILS; if (recentEventId == 0) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("no recent event date, copying all event detailss"); + if (logger.isDebugEnabled()) { + logger.debug("no recent event date, copying all event detailss"); } sql = COPY_ALL_EVENT_DETAILS; } @@ -148,7 +146,7 @@ public class UsageEventDaoImpl extends GenericDaoBase implem txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error copying event details from cloud db to usage db", ex); + logger.error("error copying event details from cloud db to usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } finally { txn.close(); @@ -171,7 +169,7 @@ public class UsageEventDaoImpl extends GenericDaoBase implem } return 0; } catch (Exception ex) { - s_logger.error("error getting most recent event id", ex); + logger.error("error getting most recent event id", ex); throw new CloudRuntimeException(ex.getMessage()); } finally { txn.close(); @@ -183,7 +181,7 @@ public class UsageEventDaoImpl extends GenericDaoBase implem try { return listLatestEvents(endDate); } catch (Exception ex) { - s_logger.error("error getting most recent event date", ex); + logger.error("error getting most recent event date", ex); throw new CloudRuntimeException(ex.getMessage()); } finally { txn.close(); @@ -203,7 +201,7 @@ public class UsageEventDaoImpl extends GenericDaoBase implem } return 0; } catch (Exception ex) { - s_logger.error("error getting max event id", ex); + logger.error("error getting max event id", ex); throw new CloudRuntimeException(ex.getMessage()); } finally { txn.close(); diff --git a/engine/schema/src/main/java/com/cloud/event/dao/UsageEventDetailsDaoImpl.java b/engine/schema/src/main/java/com/cloud/event/dao/UsageEventDetailsDaoImpl.java index 43e00efc1ad..37b203b2e88 100644 --- a/engine/schema/src/main/java/com/cloud/event/dao/UsageEventDetailsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/event/dao/UsageEventDetailsDaoImpl.java @@ -20,7 +20,6 @@ import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.event.UsageEventDetailsVO; @@ -31,7 +30,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class UsageEventDetailsDaoImpl extends GenericDaoBase implements UsageEventDetailsDao { - public static final Logger s_logger = Logger.getLogger(UsageEventDetailsDaoImpl.class.getName()); protected final SearchBuilder EventDetailsSearch; protected final SearchBuilder DetailSearch; diff --git a/engine/schema/src/main/java/com/cloud/gpu/dao/HostGpuGroupsDaoImpl.java b/engine/schema/src/main/java/com/cloud/gpu/dao/HostGpuGroupsDaoImpl.java index 25f8d245a3b..30535c7e27d 100644 --- a/engine/schema/src/main/java/com/cloud/gpu/dao/HostGpuGroupsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/gpu/dao/HostGpuGroupsDaoImpl.java @@ -19,7 +19,6 @@ package com.cloud.gpu.dao; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.gpu.HostGpuGroupsVO; @@ -30,7 +29,6 @@ import com.cloud.utils.db.SearchCriteria; @Component public class HostGpuGroupsDaoImpl extends GenericDaoBase implements HostGpuGroupsDao { - private static final Logger s_logger = Logger.getLogger(HostGpuGroupsDaoImpl.class); private final SearchBuilder _hostIdGroupNameSearch; private final SearchBuilder _searchByHostId; diff --git a/engine/schema/src/main/java/com/cloud/gpu/dao/VGPUTypesDaoImpl.java b/engine/schema/src/main/java/com/cloud/gpu/dao/VGPUTypesDaoImpl.java index d4e31d365d9..edc5e1f67c8 100644 --- a/engine/schema/src/main/java/com/cloud/gpu/dao/VGPUTypesDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/gpu/dao/VGPUTypesDaoImpl.java @@ -27,7 +27,6 @@ import java.util.Map.Entry; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.agent.api.VgpuTypesInfo; @@ -41,7 +40,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class VGPUTypesDaoImpl extends GenericDaoBase implements VGPUTypesDao { - private static final Logger s_logger = Logger.getLogger(VGPUTypesDaoImpl.class); private final SearchBuilder _searchByGroupId; private final SearchBuilder _searchByGroupIdVGPUType; diff --git a/engine/schema/src/main/java/com/cloud/host/HostTagVO.java b/engine/schema/src/main/java/com/cloud/host/HostTagVO.java index cd4ac29738d..98071a2c073 100644 --- a/engine/schema/src/main/java/com/cloud/host/HostTagVO.java +++ b/engine/schema/src/main/java/com/cloud/host/HostTagVO.java @@ -40,6 +40,9 @@ public class HostTagVO implements InternalIdentity { @Column(name = "tag") private String tag; + @Column(name = "is_implicit") + private boolean isImplicit = false; + @Column(name = "is_tag_a_rule") private boolean isTagARule; @@ -74,6 +77,13 @@ public class HostTagVO implements InternalIdentity { return isTagARule; } + public void setIsImplicit(boolean isImplicit) { + this.isImplicit = isImplicit; + } + + public boolean getIsImplicit() { + return isImplicit; + } @Override public long getId() { diff --git a/engine/schema/src/main/java/com/cloud/host/HostVO.java b/engine/schema/src/main/java/com/cloud/host/HostVO.java index 697401ad069..a449eb450cf 100644 --- a/engine/schema/src/main/java/com/cloud/host/HostVO.java +++ b/engine/schema/src/main/java/com/cloud/host/HostVO.java @@ -16,13 +16,17 @@ // under the License. package com.cloud.host; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.Entity; @@ -38,20 +42,25 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; +import com.cloud.cpu.CPU; +import org.apache.cloudstack.util.CPUArchConverter; +import org.apache.cloudstack.util.HypervisorTypeConverter; +import org.apache.cloudstack.utils.jsinterpreter.TagAsRuleHelper; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang3.StringUtils; + import com.cloud.agent.api.VgpuTypesInfo; import com.cloud.host.dao.HostTagsDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.offering.ServiceOffering; import com.cloud.resource.ResourceState; import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.util.StoragePoolTypeConverter; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; -import java.util.Arrays; - -import org.apache.cloudstack.utils.jsinterpreter.TagAsRuleHelper; -import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang3.StringUtils; @Entity @Table(name = "host") @@ -120,7 +129,7 @@ public class HostVO implements Host { private String storageMacAddressDeux; @Column(name = "hypervisor_type", updatable = true, nullable = false) - @Enumerated(value = EnumType.STRING) + @Convert(converter = HypervisorTypeConverter.class) private HypervisorType hypervisorType; @Column(name = "proxy_port") @@ -130,6 +139,7 @@ public class HostVO implements Host { private String resource; @Column(name = "fs_type") + @Convert(converter = StoragePoolTypeConverter.class) private StoragePoolType fsType; @Column(name = "available") @@ -145,6 +155,10 @@ public class HostVO implements Host { @Column(name = "hypervisor_version") private String hypervisorVersion; + @Column(name = "arch") + @Convert(converter = CPUArchConverter.class) + private CPU.CPUArch arch; + @Column(name = "update_count", updatable = true, nullable = false) protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code. @@ -698,7 +712,7 @@ public class HostVO implements Host { @Override public String toString() { - return String.format("Host %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "name", "uuid", "type")); + return String.format("Host %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "uuid", "name", "type")); } public void setHypervisorType(HypervisorType hypervisorType) { @@ -730,6 +744,15 @@ public class HostVO implements Host { return resourceState; } + @Override + public CPU.CPUArch getArch() { + return arch; + } + + public void setArch(CPU.CPUArch arch) { + this.arch = arch; + } + public void setResourceState(ResourceState state) { resourceState = state; } @@ -761,7 +784,49 @@ public class HostVO implements Host { this.uuid = uuid; } - public boolean checkHostServiceOfferingTags(ServiceOffering serviceOffering){ + private Set getHostServiceOfferingAndTemplateStrictTags(ServiceOffering serviceOffering, VirtualMachineTemplate template, Set strictHostTags) { + if (StringUtils.isEmpty(serviceOffering.getHostTag()) && StringUtils.isEmpty(template.getTemplateTag())) { + return new HashSet<>(); + } + List hostTagsList = getHostTags(); + HashSet hostTagsSet = CollectionUtils.isNotEmpty(hostTagsList) ? new HashSet<>(hostTagsList) : new HashSet<>(); + HashSet tags = new HashSet<>(); + if (StringUtils.isNotEmpty(serviceOffering.getHostTag())) { + tags.addAll(Arrays.asList(serviceOffering.getHostTag().split(","))); + } + if (StringUtils.isNotEmpty(template.getTemplateTag())) { + tags.add(template.getTemplateTag()); + } + tags.removeIf(tag -> !strictHostTags.contains(tag)); + tags.removeAll(hostTagsSet); + return tags; + } + + public boolean checkHostServiceOfferingAndTemplateTags(ServiceOffering serviceOffering, VirtualMachineTemplate template, Set strictHostTags) { + if (serviceOffering == null || template == null) { + return false; + } + Set tags = getHostServiceOfferingAndTemplateStrictTags(serviceOffering, template, strictHostTags); + if (tags.isEmpty()) { + return true; + } + List hostTagsList = getHostTags(); + HashSet hostTagsSet = CollectionUtils.isNotEmpty(hostTagsList) ? new HashSet<>(hostTagsList) : new HashSet<>(); + return hostTagsSet.containsAll(tags); + } + + public Set getHostServiceOfferingAndTemplateMissingTags(ServiceOffering serviceOffering, VirtualMachineTemplate template, Set strictHostTags) { + Set tags = getHostServiceOfferingAndTemplateStrictTags(serviceOffering, template, strictHostTags); + if (tags.isEmpty()) { + return new HashSet<>(); + } + List hostTagsList = getHostTags(); + HashSet hostTagsSet = CollectionUtils.isNotEmpty(hostTagsList) ? new HashSet<>(hostTagsList) : new HashSet<>(); + tags.removeAll(hostTagsSet); + return tags; + } + + public boolean checkHostServiceOfferingTags(ServiceOffering serviceOffering) { if (serviceOffering == null) { return false; } @@ -773,7 +838,6 @@ public class HostVO implements Host { if (StringUtils.isEmpty(serviceOffering.getHostTag())) { return true; } - List serviceOfferingTags = Arrays.asList(serviceOffering.getHostTag().split(",")); return this.getHostTags() != null && this.getHostTags().containsAll(serviceOfferingTags); } diff --git a/engine/schema/src/main/java/com/cloud/host/dao/HostDao.java b/engine/schema/src/main/java/com/cloud/host/dao/HostDao.java index 7e944291994..57ac35d3eb1 100644 --- a/engine/schema/src/main/java/com/cloud/host/dao/HostDao.java +++ b/engine/schema/src/main/java/com/cloud/host/dao/HostDao.java @@ -19,6 +19,7 @@ package com.cloud.host.dao; import java.util.Date; import java.util.List; +import com.cloud.cpu.CPU; import com.cloud.host.Host; import com.cloud.host.Host.Type; import com.cloud.host.HostVO; @@ -27,6 +28,7 @@ import com.cloud.hypervisor.Hypervisor; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.info.RunningHostCountInfo; import com.cloud.resource.ResourceState; +import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; import com.cloud.utils.fsm.StateDao; @@ -39,8 +41,14 @@ public interface HostDao extends GenericDao, StateDao status); + Integer countAllByTypeInZone(long zoneId, final Host.Type type); + Integer countUpAndEnabledHostsInZone(long zoneId); + + Pair countAllHostsAndCPUSocketsByType(Type type); + /** * Mark all hosts associated with a certain management server * as disconnected. @@ -63,7 +71,7 @@ public interface HostDao extends GenericDao, StateDao listByHostTag(Host.Type type, Long clusterId, Long podId, long dcId, String hostTag); + List listByHostTag(Host.Type type, Long clusterId, Long podId, Long dcId, String hostTag); List findAndUpdateApplianceToLoad(long lastPingSecondsAfter, long managementServerId); @@ -75,32 +83,41 @@ public interface HostDao extends GenericDao, StateDao findHypervisorHostInCluster(long clusterId); + HostVO findAnyStateHypervisorHostInCluster(long clusterId); + HostVO findOldestExistentHypervisorHostInCluster(long clusterId); List listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId, String haTag); List findByDataCenterId(Long zoneId); + List listIdsByDataCenterId(Long zoneId); + List findByPodId(Long podId); + List listIdsByPodId(Long podId); + List findByClusterId(Long clusterId); + List listIdsByClusterId(Long clusterId); + + List listIdsForUpRouting(Long zoneId, Long podId, Long clusterId); + + List listIdsByType(Type type); + + List listIdsForUpEnabledByZoneAndHypervisor(Long zoneId, HypervisorType hypervisorType); + List findByClusterIdAndEncryptionSupport(Long clusterId); /** - * Returns hosts that are 'Up' and 'Enabled' from the given Data Center/Zone + * Returns host Ids that are 'Up' and 'Enabled' from the given Data Center/Zone */ - List listByDataCenterId(long id); + List listEnabledIdsByDataCenterId(long id); /** - * Returns hosts that are from the given Data Center/Zone and at a given state (e.g. Creating, Enabled, Disabled, etc). + * Returns host Ids that are 'Up' and 'Disabled' from the given Data Center/Zone */ - List listByDataCenterIdAndState(long id, ResourceState state); - - /** - * Returns hosts that are 'Up' and 'Disabled' from the given Data Center/Zone - */ - List listDisabledByDataCenterId(long id); + List listDisabledIdsByDataCenterId(long id); List listByDataCenterIdAndHypervisorType(long zoneId, Hypervisor.HypervisorType hypervisorType); @@ -110,8 +127,6 @@ public interface HostDao extends GenericDao, StateDao listAllHostsThatHaveNoRuleTag(Host.Type type, Long clusterId, Long podId, Long dcId); - List listAllHostsByType(Host.Type type); - HostVO findByPublicIp(String publicIp); List listClustersByHostTag(String hostTagOnOffering); @@ -169,4 +184,20 @@ public interface HostDao extends GenericDao, StateDao findHostsWithTagRuleThatMatchComputeOferringTags(String computeOfferingTags); List findClustersThatMatchHostTagRule(String computeOfferingTags); + + List listSsvmHostsWithPendingMigrateJobsOrderedByJobCount(); + + boolean isHostUp(long hostId); + + List findHostIdsByZoneClusterResourceStateTypeAndHypervisorType(final Long zoneId, final Long clusterId, + final List resourceStates, final List types, + final List hypervisorTypes); + + List listDistinctHypervisorTypes(final Long zoneId); + + List> listDistinctHypervisorArchTypes(final Long zoneId); + + List listDistinctArchTypes(final Long clusterId); + + List listByIds(final List ids); } diff --git a/engine/schema/src/main/java/com/cloud/host/dao/HostDaoImpl.java b/engine/schema/src/main/java/com/cloud/host/dao/HostDaoImpl.java index 4f0ae3cce9c..e67eb1cd832 100644 --- a/engine/schema/src/main/java/com/cloud/host/dao/HostDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/host/dao/HostDaoImpl.java @@ -20,6 +20,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -36,18 +37,18 @@ import javax.persistence.TableGenerator; import org.apache.cloudstack.utils.jsinterpreter.TagAsRuleHelper; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import com.cloud.agent.api.VgpuTypesInfo; import com.cloud.cluster.agentlb.HostTransferMapVO; import com.cloud.cluster.agentlb.dao.HostTransferMapDao; import com.cloud.configuration.ManagementServiceConfiguration; +import com.cloud.cpu.CPU; import com.cloud.dc.ClusterVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.gpu.dao.HostGpuGroupsDao; import com.cloud.gpu.dao.VGPUTypesDao; -import com.cloud.host.Host; import com.cloud.host.DetailVO; +import com.cloud.host.Host; import com.cloud.host.Host.Type; import com.cloud.host.HostTagVO; import com.cloud.host.HostVO; @@ -60,6 +61,7 @@ import com.cloud.org.Grouping; import com.cloud.org.Managed; import com.cloud.resource.ResourceState; import com.cloud.utils.DateUtil; +import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.db.Attribute; import com.cloud.utils.db.DB; @@ -75,14 +77,10 @@ import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.db.UpdateBuilder; import com.cloud.utils.exception.CloudRuntimeException; -import java.util.Arrays; @DB @TableGenerator(name = "host_req_sq", table = "op_host", pkColumnName = "id", valueColumnName = "sequence", allocationSize = 1) public class HostDaoImpl extends GenericDaoBase implements HostDao { //FIXME: , ExternalIdDao { - private static final Logger s_logger = Logger.getLogger(HostDaoImpl.class); - private static final Logger status_logger = Logger.getLogger(Status.class); - private static final Logger state_logger = Logger.getLogger(ResourceState.class); private static final String LIST_HOST_IDS_BY_HOST_TAGS = "SELECT filtered.host_id, COUNT(filtered.tag) AS tag_count " + "FROM (SELECT host_id, tag, is_tag_a_rule FROM host_tags GROUP BY host_id,tag,is_tag_a_rule) AS filtered " @@ -102,6 +100,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao protected SearchBuilder TypePodDcStatusSearch; + protected SearchBuilder IdsSearch; protected SearchBuilder IdStatusSearch; protected SearchBuilder TypeDcSearch; protected SearchBuilder TypeDcStatusSearch; @@ -128,6 +127,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao protected SearchBuilder UnmanagedApplianceSearch; protected SearchBuilder MaintenanceCountSearch; protected SearchBuilder HostTypeCountSearch; + protected SearchBuilder HostTypeClusterCountSearch; protected SearchBuilder ResponsibleMsCountSearch; protected SearchBuilder HostTypeZoneCountSearch; protected SearchBuilder ClusterStatusSearch; @@ -140,8 +140,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao protected SearchBuilder ManagedRoutingServersSearch; protected SearchBuilder SecondaryStorageVMSearch; - protected GenericSearchBuilder HostIdSearch; - protected GenericSearchBuilder HostsInStatusSearch; + protected GenericSearchBuilder HostsInStatusesSearch; protected GenericSearchBuilder CountRoutingByDc; protected SearchBuilder HostTransferSearch; protected SearchBuilder ClusterManagedSearch; @@ -191,12 +190,21 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao HostTypeCountSearch = createSearchBuilder(); HostTypeCountSearch.and("type", HostTypeCountSearch.entity().getType(), SearchCriteria.Op.EQ); + HostTypeCountSearch.and("zoneId", HostTypeCountSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + HostTypeCountSearch.and("resourceState", HostTypeCountSearch.entity().getResourceState(), SearchCriteria.Op.EQ); HostTypeCountSearch.done(); ResponsibleMsCountSearch = createSearchBuilder(); ResponsibleMsCountSearch.and("managementServerId", ResponsibleMsCountSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ); ResponsibleMsCountSearch.done(); + HostTypeClusterCountSearch = createSearchBuilder(); + HostTypeClusterCountSearch.and("cluster", HostTypeClusterCountSearch.entity().getClusterId(), SearchCriteria.Op.EQ); + HostTypeClusterCountSearch.and("type", HostTypeClusterCountSearch.entity().getType(), SearchCriteria.Op.EQ); + HostTypeClusterCountSearch.and("status", HostTypeClusterCountSearch.entity().getStatus(), SearchCriteria.Op.IN); + HostTypeClusterCountSearch.and("removed", HostTypeClusterCountSearch.entity().getRemoved(), SearchCriteria.Op.NULL); + HostTypeClusterCountSearch.done(); + HostTypeZoneCountSearch = createSearchBuilder(); HostTypeZoneCountSearch.and("type", HostTypeZoneCountSearch.entity().getType(), SearchCriteria.Op.EQ); HostTypeZoneCountSearch.and("dc", HostTypeZoneCountSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); @@ -244,6 +252,10 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao TypeClusterStatusSearch.and("resourceState", TypeClusterStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ); TypeClusterStatusSearch.done(); + IdsSearch = createSearchBuilder(); + IdsSearch.and("id", IdsSearch.entity().getId(), SearchCriteria.Op.IN); + IdsSearch.done(); + IdStatusSearch = createSearchBuilder(); IdStatusSearch.and("id", IdStatusSearch.entity().getId(), SearchCriteria.Op.EQ); IdStatusSearch.and("states", IdStatusSearch.entity().getStatus(), SearchCriteria.Op.IN); @@ -357,7 +369,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao try { HostTransferSearch = _hostTransferDao.createSearchBuilder(); } catch (Throwable e) { - s_logger.debug("error", e); + logger.debug("error", e); } HostTransferSearch.and("id", HostTransferSearch.entity().getId(), SearchCriteria.Op.NULL); UnmanagedDirectConnectSearch.join("hostTransferSearch", HostTransferSearch, HostTransferSearch.entity().getId(), UnmanagedDirectConnectSearch.entity().getId(), @@ -390,14 +402,14 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao AvailHypevisorInZone.groupBy(AvailHypevisorInZone.entity().getHypervisorType()); AvailHypevisorInZone.done(); - HostsInStatusSearch = createSearchBuilder(Long.class); - HostsInStatusSearch.selectFields(HostsInStatusSearch.entity().getId()); - HostsInStatusSearch.and("dc", HostsInStatusSearch.entity().getDataCenterId(), Op.EQ); - HostsInStatusSearch.and("pod", HostsInStatusSearch.entity().getPodId(), Op.EQ); - HostsInStatusSearch.and("cluster", HostsInStatusSearch.entity().getClusterId(), Op.EQ); - HostsInStatusSearch.and("type", HostsInStatusSearch.entity().getType(), Op.EQ); - HostsInStatusSearch.and("statuses", HostsInStatusSearch.entity().getStatus(), Op.IN); - HostsInStatusSearch.done(); + HostsInStatusesSearch = createSearchBuilder(Long.class); + HostsInStatusesSearch.selectFields(HostsInStatusesSearch.entity().getId()); + HostsInStatusesSearch.and("dc", HostsInStatusesSearch.entity().getDataCenterId(), Op.EQ); + HostsInStatusesSearch.and("pod", HostsInStatusesSearch.entity().getPodId(), Op.EQ); + HostsInStatusesSearch.and("cluster", HostsInStatusesSearch.entity().getClusterId(), Op.EQ); + HostsInStatusesSearch.and("type", HostsInStatusesSearch.entity().getType(), Op.EQ); + HostsInStatusesSearch.and("statuses", HostsInStatusesSearch.entity().getStatus(), Op.IN); + HostsInStatusesSearch.done(); CountRoutingByDc = createSearchBuilder(Long.class); CountRoutingByDc.select(null, Func.COUNT, null); @@ -460,11 +472,6 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao HostsInClusterSearch.and("server", HostsInClusterSearch.entity().getManagementServerId(), SearchCriteria.Op.NNULL); HostsInClusterSearch.done(); - HostIdSearch = createSearchBuilder(Long.class); - HostIdSearch.selectFields(HostIdSearch.entity().getId()); - HostIdSearch.and("dataCenterId", HostIdSearch.entity().getDataCenterId(), Op.EQ); - HostIdSearch.done(); - searchBuilderFindByRuleTag = _hostTagsDao.createSearchBuilder(); searchBuilderFindByRuleTag.and("is_tag_a_rule", searchBuilderFindByRuleTag.entity().getIsTagARule(), Op.EQ); searchBuilderFindByRuleTag.or("tagDoesNotExist", searchBuilderFindByRuleTag.entity().getIsTagARule(), Op.NULL); @@ -496,8 +503,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao sc.setParameters("resourceState", (Object[])states); sc.setParameters("cluster", clusterId); - List hosts = listBy(sc); - return hosts.size(); + return getCount(sc); } @Override @@ -508,36 +514,62 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao } @Override - public Integer countAllByTypeInZone(long zoneId, Type type) { - SearchCriteria sc = HostTypeCountSearch.create(); - sc.setParameters("type", type); - sc.setParameters("dc", zoneId); + public Integer countAllInClusterByTypeAndStates(Long clusterId, final Host.Type type, List status) { + SearchCriteria sc = HostTypeClusterCountSearch.create(); + if (clusterId != null) { + sc.setParameters("cluster", clusterId); + } + if (type != null) { + sc.setParameters("type", type); + } + if (status != null) { + sc.setParameters("status", status.toArray()); + } return getCount(sc); } @Override - public List listByDataCenterId(long id) { - return listByDataCenterIdAndState(id, ResourceState.Enabled); + public Integer countAllByTypeInZone(long zoneId, Type type) { + SearchCriteria sc = HostTypeCountSearch.create(); + sc.setParameters("type", type); + sc.setParameters("zoneId", zoneId); + return getCount(sc); } @Override - public List listByDataCenterIdAndState(long id, ResourceState state) { - SearchCriteria sc = scHostsFromZoneUpRouting(id); - sc.setParameters("resourceState", state); - return listBy(sc); + public Integer countUpAndEnabledHostsInZone(long zoneId) { + SearchCriteria sc = HostTypeCountSearch.create(); + sc.setParameters("type", Type.Routing); + sc.setParameters("resourceState", ResourceState.Enabled); + sc.setParameters("zoneId", zoneId); + return getCount(sc); } @Override - public List listDisabledByDataCenterId(long id) { - return listByDataCenterIdAndState(id, ResourceState.Disabled); + public Pair countAllHostsAndCPUSocketsByType(Type type) { + GenericSearchBuilder sb = createSearchBuilder(SumCount.class); + sb.select("sum", Func.SUM, sb.entity().getCpuSockets()); + sb.select("count", Func.COUNT, null); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("type", type); + SumCount result = customSearch(sc, null).get(0); + return new Pair<>((int)result.count, (int)result.sum); } - private SearchCriteria scHostsFromZoneUpRouting(long id) { - SearchCriteria sc = DcSearch.create(); - sc.setParameters("dc", id); - sc.setParameters("status", Status.Up); - sc.setParameters("type", Host.Type.Routing); - return sc; + private List listIdsForRoutingByZoneIdAndResourceState(long zoneId, ResourceState state) { + return listIdsBy(Type.Routing, Status.Up, state, null, zoneId, null, null); + } + + @Override + public List listEnabledIdsByDataCenterId(long id) { + return listIdsForRoutingByZoneIdAndResourceState(id, ResourceState.Enabled); + } + + @Override + public List listDisabledIdsByDataCenterId(long id) { + return listIdsForRoutingByZoneIdAndResourceState(id, ResourceState.Disabled); } @Override @@ -595,9 +627,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao sb.append(" "); } - if (s_logger.isTraceEnabled()) { - s_logger.trace("Following hosts got reset: " + sb.toString()); - } + logger.trace("Following hosts got reset: {}", sb); } /* @@ -607,8 +637,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao SearchCriteria sc = ClustersOwnedByMSSearch.create(); sc.setParameters("server", managementServerId); - List clusters = customSearch(sc, null); - return clusters; + return customSearch(sc, null); } /* @@ -618,13 +647,11 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao SearchCriteria sc = ClustersForHostsNotOwnedByAnyMSSearch.create(); sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed); - List clusters = customSearch(sc, null); - return clusters; + return customSearch(sc, null); } /** * This determines if hosts belonging to cluster(@clusterId) are up for grabs - * * This is used for handling following cases: * 1. First host added in cluster * 2. During MS restart all hosts in a cluster are without any MS @@ -634,9 +661,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao sc.setParameters("cluster", clusterId); List hosts = search(sc, null); - boolean ownCluster = (hosts == null || hosts.size() == 0); - - return ownCluster; + return (hosts == null || hosts.isEmpty()); } @Override @@ -644,23 +669,23 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao public List findAndUpdateDirectAgentToLoad(long lastPingSecondsAfter, Long limit, long managementServerId) { TransactionLegacy txn = TransactionLegacy.currentTxn(); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Resetting hosts suitable for reconnect"); + if (logger.isDebugEnabled()) { + logger.debug("Resetting hosts suitable for reconnect"); } // reset hosts that are suitable candidates for reconnect resetHosts(managementServerId, lastPingSecondsAfter); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Completed resetting hosts suitable for reconnect"); + if (logger.isDebugEnabled()) { + logger.debug("Completed resetting hosts suitable for reconnect"); } - List assignedHosts = new ArrayList(); + List assignedHosts = new ArrayList<>(); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Acquiring hosts for clusters already owned by this management server"); + if (logger.isDebugEnabled()) { + logger.debug("Acquiring hosts for clusters already owned by this management server"); } List clusters = findClustersOwnedByManagementServer(managementServerId); txn.start(); - if (clusters.size() > 0) { + if (!clusters.isEmpty()) { // handle clusters already owned by @managementServerId SearchCriteria sc = UnmanagedDirectConnectSearch.create(); sc.setParameters("lastPinged", lastPingSecondsAfter); @@ -675,17 +700,13 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao sb.append(host.getId()); sb.append(" "); } - if (s_logger.isTraceEnabled()) { - s_logger.trace("Following hosts got acquired for clusters already owned: " + sb.toString()); - } - } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Completed acquiring hosts for clusters already owned by this management server"); + logger.trace("Following hosts got acquired for clusters already owned: {}", sb); } + logger.debug("Completed acquiring hosts for clusters already owned by this management server"); if (assignedHosts.size() < limit) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Acquiring hosts for clusters not owned by any management server"); + if (logger.isDebugEnabled()) { + logger.debug("Acquiring hosts for clusters not owned by any management server"); } // for remaining hosts not owned by any MS check if they can be owned (by owning full cluster) clusters = findClustersForHostsNotOwnedByAnyManagementServer(); @@ -693,7 +714,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao if (clusters.size() > limit) { updatedClusters = clusters.subList(0, limit.intValue()); } - if (updatedClusters.size() > 0) { + if (!updatedClusters.isEmpty()) { SearchCriteria sc = UnmanagedDirectConnectSearch.create(); sc.setParameters("lastPinged", lastPingSecondsAfter); sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed); @@ -701,10 +722,10 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao List unmanagedHosts = lockRows(sc, null, true); // group hosts based on cluster - Map> hostMap = new HashMap>(); + Map> hostMap = new HashMap<>(); for (HostVO host : unmanagedHosts) { if (hostMap.get(host.getClusterId()) == null) { - hostMap.put(host.getClusterId(), new ArrayList()); + hostMap.put(host.getClusterId(), new ArrayList<>()); } hostMap.get(host.getClusterId()).add(host); } @@ -725,13 +746,9 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao break; } } - if (s_logger.isTraceEnabled()) { - s_logger.trace("Following hosts got acquired from newly owned clusters: " + sb.toString()); - } - } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Completed acquiring hosts for clusters not owned by any management server"); + logger.trace("Following hosts got acquired from newly owned clusters: {}", sb); } + logger.debug("Completed acquiring hosts for clusters not owned by any management server"); } txn.commit(); @@ -785,14 +802,14 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao } @Override - public List listByHostTag(Host.Type type, Long clusterId, Long podId, long dcId, String hostTag) { + public List listByHostTag(Host.Type type, Long clusterId, Long podId, Long dcId, String hostTag) { return listHostsWithOrWithoutHostTags(type, clusterId, podId, dcId, hostTag, true); } - private List listHostsWithOrWithoutHostTags(Host.Type type, Long clusterId, Long podId, long dcId, String hostTags, boolean withHostTags) { + private List listHostsWithOrWithoutHostTags(Host.Type type, Long clusterId, Long podId, Long dcId, String hostTags, boolean withHostTags) { if (StringUtils.isEmpty(hostTags)) { - s_logger.debug("Host tags not specified, to list hosts"); - return new ArrayList(); + logger.debug("Host tags not specified, to list hosts"); + return new ArrayList<>(); } SearchBuilder hostSearch = createSearchBuilder(); @@ -814,26 +831,28 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao if (clusterId != null) { sc.setParameters("cluster", clusterId); } - sc.setParameters("dc", dcId); + if (dcId != null) { + sc.setParameters("dc", dcId); + } sc.setParameters("status", Status.Up.toString()); sc.setParameters("resourceState", ResourceState.Enabled.toString()); List upAndEnabledHosts = listBy(sc); if (CollectionUtils.isEmpty(upAndEnabledHosts)) { - return new ArrayList(); + return new ArrayList<>(); } List hostIdsByHostTags = findHostIdsByHostTags(hostTags); if (CollectionUtils.isEmpty(hostIdsByHostTags)) { - return withHostTags ? new ArrayList() : upAndEnabledHosts; + return withHostTags ? new ArrayList<>() : upAndEnabledHosts; } if (withHostTags) { - List upAndEnabledHostsWithHostTags = new ArrayList(); + List upAndEnabledHostsWithHostTags = new ArrayList<>(); upAndEnabledHosts.forEach((host) -> { if (hostIdsByHostTags.contains(host.getId())) upAndEnabledHostsWithHostTags.add(host);}); return upAndEnabledHostsWithHostTags; } else { - List upAndEnabledHostsWithoutHostTags = new ArrayList(); + List upAndEnabledHostsWithoutHostTags = new ArrayList<>(); upAndEnabledHosts.forEach((host) -> { if (!hostIdsByHostTags.contains(host.getId())) upAndEnabledHostsWithoutHostTags.add(host);}); return upAndEnabledHostsWithoutHostTags; } @@ -905,19 +924,19 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao @DB @Override public List findLostHosts(long timeout) { - List result = new ArrayList(); + List result = new ArrayList<>(); String sql = "select h.id from host h left join cluster c on h.cluster_id=c.id where h.mgmt_server_id is not null and h.last_ping < ? and h.status in ('Up', 'Updating', 'Disconnected', 'Connecting') and h.type not in ('ExternalFirewall', 'ExternalLoadBalancer', 'TrafficMonitor', 'SecondaryStorage', 'LocalSecondaryStorage', 'L2Networking') and (h.cluster_id is null or c.managed_state = 'Managed') ;"; try (TransactionLegacy txn = TransactionLegacy.currentTxn(); - PreparedStatement pstmt = txn.prepareStatement(sql);) { + PreparedStatement pstmt = txn.prepareStatement(sql)) { pstmt.setLong(1, timeout); - try (ResultSet rs = pstmt.executeQuery();) { + try (ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { long id = rs.getLong(1); //ID column result.add(findById(id)); } } } catch (SQLException e) { - s_logger.warn("Exception: ", e); + logger.warn("Exception: ", e); } return result; } @@ -943,7 +962,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao HashMap> groupDetails = host.getGpuGroupDetails(); if (groupDetails != null) { // Create/Update GPU group entries - _hostGpuGroupsDao.persist(host.getId(), new ArrayList(groupDetails.keySet())); + _hostGpuGroupsDao.persist(host.getId(), new ArrayList<>(groupDetails.keySet())); // Create/Update VGPU types entries _vgpuTypesDao.persist(host.getId(), groupDetails); } @@ -986,7 +1005,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao boolean persisted = super.update(hostId, host); if (!persisted) { - return persisted; + return false; } saveDetails(host); @@ -995,7 +1014,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao txn.commit(); - return persisted; + return true; } @Override @@ -1006,11 +1025,10 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao + "select h.data_center_id, h.type, count(*) as count from host as h INNER JOIN mshost as m ON h.mgmt_server_id=m.msid " + "where h.status='Up' and h.type='Routing' and m.last_update > ? " + "group by h.data_center_id, h.type) as t " + "ORDER by t.data_center_id, t.type"; - ArrayList l = new ArrayList(); + ArrayList l = new ArrayList<>(); TransactionLegacy txn = TransactionLegacy.currentTxn(); - ; - PreparedStatement pstmt = null; + PreparedStatement pstmt; try { pstmt = txn.prepareAutoCloseStatement(sql); String gmtCutTime = DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime); @@ -1027,16 +1045,14 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao l.add(info); } } catch (SQLException e) { - s_logger.debug("SQLException caught", e); + logger.debug("SQLException caught", e); } return l; } @Override public long getNextSequence(long hostId) { - if (s_logger.isTraceEnabled()) { - s_logger.trace("getNextSequence(), hostId: " + hostId); - } + logger.trace("getNextSequence(), hostId: {}", hostId); TableGenerator tg = _tgs.get("host_req_sq"); assert tg != null : "how can this be wrong!"; @@ -1105,31 +1121,30 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao HostVO ho = findById(host.getId()); assert ho != null : "How how how? : " + host.getId(); - if (status_logger.isDebugEnabled()) { - - StringBuilder str = new StringBuilder("Unable to update host for event:").append(event.toString()); - str.append(". Name=").append(host.getName()); - str.append("; New=[status=").append(newStatus.toString()).append(":msid=").append(newStatus.lostConnection() ? "null" : host.getManagementServerId()) - .append(":lastpinged=").append(host.getLastPinged()).append("]"); - str.append("; Old=[status=").append(oldStatus.toString()).append(":msid=").append(host.getManagementServerId()).append(":lastpinged=").append(oldPingTime) - .append("]"); - str.append("; DB=[status=").append(vo.getStatus().toString()).append(":msid=").append(vo.getManagementServerId()).append(":lastpinged=").append(vo.getLastPinged()) - .append(":old update count=").append(oldUpdateCount).append("]"); - status_logger.debug(str.toString()); + // TODO handle this if(debug){}else{log.debug} it makes no sense + if (logger.isDebugEnabled()) { + String str = "Unable to update host for event:" + event + + ". Name=" + host.getName() + + "; New=[status=" + newStatus + ":msid=" + (newStatus.lostConnection() ? "null" : host.getManagementServerId()) + + ":lastpinged=" + host.getLastPinged() + "]" + + "; Old=[status=" + oldStatus.toString() + ":msid=" + host.getManagementServerId() + ":lastpinged=" + oldPingTime + + "]" + + "; DB=[status=" + vo.getStatus().toString() + ":msid=" + vo.getManagementServerId() + ":lastpinged=" + vo.getLastPinged() + + ":old update count=" + oldUpdateCount + "]"; + logger.debug(str); } else { - StringBuilder msg = new StringBuilder("Agent status update: ["); - msg.append("id = " + host.getId()); - msg.append("; name = " + host.getName()); - msg.append("; old status = " + oldStatus); - msg.append("; event = " + event); - msg.append("; new status = " + newStatus); - msg.append("; old update count = " + oldUpdateCount); - msg.append("; new update count = " + newUpdateCount + "]"); - status_logger.debug(msg.toString()); + String msg = "Agent status update: [" + "id = " + host.getId() + + "; name = " + host.getName() + + "; old status = " + oldStatus + + "; event = " + event + + "; new status = " + newStatus + + "; old update count = " + oldUpdateCount + + "; new update count = " + newUpdateCount + "]"; + logger.debug(msg); } if (ho.getState() == newStatus) { - status_logger.debug("Host " + ho.getName() + " state has already been updated to " + newStatus); + logger.debug("Host {} state has already been updated to {}", ho.getName(), newStatus); return true; } } @@ -1155,25 +1170,24 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao int result = update(ub, sc, null); assert result <= 1 : "How can this update " + result + " rows? "; - if (state_logger.isDebugEnabled() && result == 0) { + // TODO handle this if(debug){}else{log.debug} it makes no sense + if (logger.isDebugEnabled() && result == 0) { HostVO ho = findById(host.getId()); assert ho != null : "How how how? : " + host.getId(); - StringBuilder str = new StringBuilder("Unable to update resource state: ["); - str.append("m = " + host.getId()); - str.append("; name = " + host.getName()); - str.append("; old state = " + oldState); - str.append("; event = " + event); - str.append("; new state = " + newState + "]"); - state_logger.debug(str.toString()); + String str = "Unable to update resource state: [" + "m = " + host.getId() + + "; name = " + host.getName() + + "; old state = " + oldState + + "; event = " + event + + "; new state = " + newState + "]"; + logger.debug(str); } else { - StringBuilder msg = new StringBuilder("Resource state update: ["); - msg.append("id = " + host.getId()); - msg.append("; name = " + host.getName()); - msg.append("; old state = " + oldState); - msg.append("; event = " + event); - msg.append("; new state = " + newState + "]"); - state_logger.debug(msg.toString()); + String msg = "Resource state update: [" + "id = " + host.getId() + + "; name = " + host.getName() + + "; old state = " + oldState + + "; event = " + event + + "; new state = " + newState + "]"; + logger.debug(msg); } return result > 0; @@ -1196,6 +1210,11 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao return listBy(sc); } + @Override + public List listIdsByDataCenterId(Long zoneId) { + return listIdsBy(Type.Routing, null, null, null, zoneId, null, null); + } + @Override public List findByPodId(Long podId) { SearchCriteria sc = PodSearch.create(); @@ -1203,6 +1222,11 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao return listBy(sc); } + @Override + public List listIdsByPodId(Long podId) { + return listIdsBy(null, null, null, null, null, podId, null); + } + @Override public List findByClusterId(Long clusterId) { SearchCriteria sc = ClusterSearch.create(); @@ -1210,6 +1234,63 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao return listBy(sc); } + protected List listIdsBy(Host.Type type, Status status, ResourceState resourceState, + HypervisorType hypervisorType, Long zoneId, Long podId, Long clusterId) { + GenericSearchBuilder sb = createSearchBuilder(Long.class); + sb.selectFields(sb.entity().getId()); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); + sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ); + sb.and("resourceState", sb.entity().getResourceState(), SearchCriteria.Op.EQ); + sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ); + sb.and("zoneId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ); + sb.done(); + SearchCriteria sc = sb.create(); + if (type != null) { + sc.setParameters("type", type); + } + if (status != null) { + sc.setParameters("status", status); + } + if (resourceState != null) { + sc.setParameters("resourceState", resourceState); + } + if (hypervisorType != null) { + sc.setParameters("hypervisorType", hypervisorType); + } + if (zoneId != null) { + sc.setParameters("zoneId", zoneId); + } + if (podId != null) { + sc.setParameters("podId", podId); + } + if (clusterId != null) { + sc.setParameters("clusterId", clusterId); + } + return customSearch(sc, null); + } + + @Override + public List listIdsByClusterId(Long clusterId) { + return listIdsBy(null, null, null, null, null, null, clusterId); + } + + @Override + public List listIdsForUpRouting(Long zoneId, Long podId, Long clusterId) { + return listIdsBy(Type.Routing, Status.Up, null, null, zoneId, podId, clusterId); + } + + @Override + public List listIdsByType(Type type) { + return listIdsBy(type, null, null, null, null, null, null); + } + + @Override + public List listIdsForUpEnabledByZoneAndHypervisor(Long zoneId, HypervisorType hypervisorType) { + return listIdsBy(null, Status.Up, ResourceState.Enabled, hypervisorType, zoneId, null, null); + } + @Override public List findByClusterIdAndEncryptionSupport(Long clusterId) { SearchBuilder hostCapabilitySearch = _detailsDao.createSearchBuilder(); @@ -1262,6 +1343,15 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao return listBy(sc); } + @Override + public HostVO findAnyStateHypervisorHostInCluster(long clusterId) { + SearchCriteria sc = TypeClusterStatusSearch.create(); + sc.setParameters("type", Host.Type.Routing); + sc.setParameters("cluster", clusterId); + List list = listBy(sc, new Filter(1)); + return list.isEmpty() ? null : list.get(0); + } + @Override public HostVO findOldestExistentHypervisorHostInCluster(long clusterId) { SearchCriteria sc = TypeClusterStatusSearch.create(); @@ -1272,7 +1362,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao Filter orderByFilter = new Filter(HostVO.class, "created", true, null, null); List hosts = search(sc, orderByFilter, null, false); - if (hosts != null && hosts.size() > 0) { + if (hosts != null && !hosts.isEmpty()) { return hosts.get(0); } @@ -1281,9 +1371,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao @Override public List listAllHosts(long zoneId) { - SearchCriteria sc = HostIdSearch.create(); - sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); - return customSearch(sc, null); + return listIdsBy(null, null, null, null, zoneId, null, null); } @Override @@ -1319,10 +1407,10 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao @Override public List listClustersByHostTag(String hostTags) { TransactionLegacy txn = TransactionLegacy.currentTxn(); - String selectStmtToListClusterIdsByHostTags = this.LIST_CLUSTER_IDS_FOR_HOST_TAGS; - PreparedStatement pstmt = null; - List result = new ArrayList(); - List tags = Arrays.asList(hostTags.split(this.SEPARATOR)); + String selectStmtToListClusterIdsByHostTags = LIST_CLUSTER_IDS_FOR_HOST_TAGS; + PreparedStatement pstmt; + List result = new ArrayList<>(); + List tags = Arrays.asList(hostTags.split(SEPARATOR)); String selectStmtToListHostIdsByHostTags = getSelectStmtToListHostIdsByHostTags(tags); selectStmtToListClusterIdsByHostTags = String.format(selectStmtToListClusterIdsByHostTags, selectStmtToListHostIdsByHostTags); @@ -1346,9 +1434,9 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao private List findHostIdsByHostTags(String hostTags){ TransactionLegacy txn = TransactionLegacy.currentTxn(); - PreparedStatement pstmt = null; - List result = new ArrayList(); - List tags = Arrays.asList(hostTags.split(this.SEPARATOR)); + PreparedStatement pstmt; + List result = new ArrayList<>(); + List tags = Arrays.asList(hostTags.split(SEPARATOR)); String selectStmtToListHostIdsByHostTags = getSelectStmtToListHostIdsByHostTags(tags); try { pstmt = txn.prepareStatement(selectStmtToListHostIdsByHostTags); @@ -1389,16 +1477,41 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao return new ArrayList<>(result); } + @Override + public List listSsvmHostsWithPendingMigrateJobsOrderedByJobCount() { + String query = "SELECT cel.host_id, COUNT(*) " + + "FROM cmd_exec_log cel " + + "JOIN host h ON cel.host_id = h.id " + + "WHERE h.removed IS NULL " + + "GROUP BY cel.host_id " + + "ORDER BY 2"; + + TransactionLegacy txn = TransactionLegacy.currentTxn(); + List result = new ArrayList<>(); + + PreparedStatement pstmt; + try { + pstmt = txn.prepareAutoCloseStatement(query); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + result.add((long) rs.getInt(1)); + } + } catch (SQLException e) { + logger.warn("SQLException caught while listing SSVMs with least migrate jobs.", e); + } + return result; + } + private String getSelectStmtToListHostIdsByHostTags(List hostTags){ - List questionMarks = new ArrayList(); - hostTags.forEach((tag) -> { questionMarks.add("?"); }); - return String.format(this.LIST_HOST_IDS_BY_HOST_TAGS, String.join(",", questionMarks), questionMarks.size()); + List questionMarks = new ArrayList<>(); + hostTags.forEach((tag) -> questionMarks.add("?")); + return String.format(LIST_HOST_IDS_BY_HOST_TAGS, String.join(SEPARATOR, questionMarks), questionMarks.size()); } @Override public List listHostsWithActiveVMs(long offeringId) { TransactionLegacy txn = TransactionLegacy.currentTxn(); - PreparedStatement pstmt = null; + PreparedStatement pstmt; List result = new ArrayList<>(); StringBuilder sql = new StringBuilder(GET_HOSTS_OF_ACTIVE_VMS); try { @@ -1425,7 +1538,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao @Override public List listOrderedHostsHypervisorVersionsInDatacenter(long datacenterId, HypervisorType hypervisorType) { - PreparedStatement pstmt = null; + PreparedStatement pstmt; List result = new ArrayList<>(); try { TransactionLegacy txn = TransactionLegacy.currentTxn(); @@ -1437,20 +1550,11 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao result.add(resultSet.getString(1)); } } catch (SQLException e) { - s_logger.error("Error trying to obtain hypervisor version on datacenter", e); + logger.error("Error trying to obtain hypervisor version on datacenter", e); } return result; } - @Override - public List listAllHostsByType(Host.Type type) { - SearchCriteria sc = TypeSearch.create(); - sc.setParameters("type", type); - sc.setParameters("resourceState", ResourceState.Enabled); - - return listBy(sc); - } - @Override public List listByType(Host.Type type) { SearchCriteria sc = TypeSearch.create(); @@ -1595,4 +1699,106 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao } return String.format(sqlFindHostInZoneToExecuteCommand, hostResourceStatus); } + + @Override + public boolean isHostUp(long hostId) { + GenericSearchBuilder sb = createSearchBuilder(Status.class); + sb.and("id", sb.entity().getId(), Op.EQ); + sb.selectFields(sb.entity().getStatus()); + SearchCriteria sc = sb.create(); + sc.setParameters("id", hostId); + List statuses = customSearch(sc, null); + return CollectionUtils.isNotEmpty(statuses) && Status.Up.equals(statuses.get(0)); + } + + @Override + public List findHostIdsByZoneClusterResourceStateTypeAndHypervisorType(final Long zoneId, final Long clusterId, + final List resourceStates, final List types, + final List hypervisorTypes) { + GenericSearchBuilder sb = createSearchBuilder(Long.class); + sb.selectFields(sb.entity().getId()); + sb.and("zoneId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ); + sb.and("resourceState", sb.entity().getResourceState(), SearchCriteria.Op.IN); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.IN); + if (CollectionUtils.isNotEmpty(hypervisorTypes)) { + sb.and().op(sb.entity().getHypervisorType(), SearchCriteria.Op.NULL); + sb.or("hypervisorTypes", sb.entity().getHypervisorType(), SearchCriteria.Op.IN); + sb.cp(); + } + sb.done(); + SearchCriteria sc = sb.create(); + if (zoneId != null) { + sc.setParameters("zoneId", zoneId); + } + if (clusterId != null) { + sc.setParameters("clusterId", clusterId); + } + if (CollectionUtils.isNotEmpty(hypervisorTypes)) { + sc.setParameters("hypervisorTypes", hypervisorTypes.toArray()); + } + sc.setParameters("resourceState", resourceStates.toArray()); + sc.setParameters("type", types.toArray()); + return customSearch(sc, null); + } + + @Override + public List listDistinctHypervisorTypes(final Long zoneId) { + GenericSearchBuilder sb = createSearchBuilder(String.class); + sb.and("zoneId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); + sb.select(null, Func.DISTINCT, sb.entity().getHypervisorType()); + sb.done(); + SearchCriteria sc = sb.create(); + if (zoneId != null) { + sc.setParameters("zoneId", zoneId); + } + sc.setParameters("type", Type.Routing); + List hypervisorString = customSearch(sc, null); + return hypervisorString.stream().map(HypervisorType::getType).collect(Collectors.toList()); + } + + @Override + public List> listDistinctHypervisorArchTypes(final Long zoneId) { + SearchBuilder sb = createSearchBuilder(); + sb.select(null, Func.DISTINCT_PAIR, sb.entity().getHypervisorType(), sb.entity().getArch()); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); + sb.and("zoneId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("type", Type.Routing); + if (zoneId != null) { + sc.setParameters("zoneId", zoneId); + } + final List hosts = search(sc, null); + return hosts.stream() + .map(h -> new Pair<>(h.getHypervisorType(), h.getArch())) + .collect(Collectors.toList()); + } + + @Override + public List listDistinctArchTypes(final Long clusterId) { + GenericSearchBuilder sb = createSearchBuilder(String.class); + sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); + sb.select(null, Func.DISTINCT, sb.entity().getArch()); + sb.done(); + SearchCriteria sc = sb.create(); + if (clusterId != null) { + sc.setParameters("clusterId", clusterId); + } + sc.setParameters("type", Type.Routing); + List archStrings = customSearch(sc, null); + return archStrings.stream().map(CPU.CPUArch::fromType).collect(Collectors.toList()); + } + + @Override + public List listByIds(List ids) { + if (CollectionUtils.isEmpty(ids)) { + return new ArrayList<>(); + } + SearchCriteria sc = IdsSearch.create(); + sc.setParameters("id", ids.toArray()); + return search(sc, null); + } } diff --git a/engine/schema/src/main/java/com/cloud/host/dao/HostTagsDao.java b/engine/schema/src/main/java/com/cloud/host/dao/HostTagsDao.java index d134db33403..7a00829fd44 100644 --- a/engine/schema/src/main/java/com/cloud/host/dao/HostTagsDao.java +++ b/engine/schema/src/main/java/com/cloud/host/dao/HostTagsDao.java @@ -20,6 +20,7 @@ import java.util.List; import com.cloud.host.HostTagVO; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.response.HostTagResponse; import org.apache.cloudstack.framework.config.ConfigKey; public interface HostTagsDao extends GenericDao { @@ -35,6 +36,13 @@ public interface HostTagsDao extends GenericDao { void deleteTags(long hostId); + boolean updateImplicitTags(long hostId, List hostTags); + + List getExplicitHostTags(long hostId); + List findHostRuleTags(); + HostTagResponse newHostTagResponse(HostTagVO hostTag); + + List searchByIds(Long... hostTagIds); } diff --git a/engine/schema/src/main/java/com/cloud/host/dao/HostTagsDaoImpl.java b/engine/schema/src/main/java/com/cloud/host/dao/HostTagsDaoImpl.java index 65deb1d1c9b..4aa14a31cfc 100644 --- a/engine/schema/src/main/java/com/cloud/host/dao/HostTagsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/host/dao/HostTagsDaoImpl.java @@ -16,10 +16,14 @@ // under the License. package com.cloud.host.dao; +import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.HostTagResponse; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import com.cloud.host.HostTagVO; @@ -30,14 +34,23 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.db.SearchCriteria.Func; +import javax.inject.Inject; + @Component public class HostTagsDaoImpl extends GenericDaoBase implements HostTagsDao, Configurable { protected final SearchBuilder HostSearch; protected final GenericSearchBuilder DistinctImplictTagsSearch; + private final SearchBuilder stSearch; + private final SearchBuilder tagIdsearch; + private final SearchBuilder ImplicitTagsSearch; + + @Inject + private ConfigurationDao _configDao; public HostTagsDaoImpl() { HostSearch = createSearchBuilder(); HostSearch.and("hostId", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); + HostSearch.and("isImplicit", HostSearch.entity().getIsImplicit(), SearchCriteria.Op.EQ); HostSearch.and("isTagARule", HostSearch.entity().getIsTagARule(), SearchCriteria.Op.EQ); HostSearch.done(); @@ -46,6 +59,19 @@ public class HostTagsDaoImpl extends GenericDaoBase implements DistinctImplictTagsSearch.and("hostIds", DistinctImplictTagsSearch.entity().getHostId(), SearchCriteria.Op.IN); DistinctImplictTagsSearch.and("implicitTags", DistinctImplictTagsSearch.entity().getTag(), SearchCriteria.Op.IN); DistinctImplictTagsSearch.done(); + + stSearch = createSearchBuilder(); + stSearch.and("idIN", stSearch.entity().getId(), SearchCriteria.Op.IN); + stSearch.done(); + + tagIdsearch = createSearchBuilder(); + tagIdsearch.and("id", tagIdsearch.entity().getId(), SearchCriteria.Op.EQ); + tagIdsearch.done(); + + ImplicitTagsSearch = createSearchBuilder(); + ImplicitTagsSearch.and("hostId", ImplicitTagsSearch.entity().getHostId(), SearchCriteria.Op.EQ); + ImplicitTagsSearch.and("isImplicit", ImplicitTagsSearch.entity().getIsImplicit(), SearchCriteria.Op.EQ); + ImplicitTagsSearch.done(); } @Override @@ -74,6 +100,36 @@ public class HostTagsDaoImpl extends GenericDaoBase implements txn.commit(); } + @Override + public boolean updateImplicitTags(long hostId, List hostTags) { + TransactionLegacy txn = TransactionLegacy.currentTxn(); + txn.start(); + SearchCriteria sc = ImplicitTagsSearch.create(); + sc.setParameters("hostId", hostId); + sc.setParameters("isImplicit", true); + boolean expunged = expunge(sc) > 0; + boolean persisted = false; + for (String tag : hostTags) { + if (StringUtils.isNotBlank(tag)) { + HostTagVO vo = new HostTagVO(hostId, tag.trim()); + vo.setIsImplicit(true); + persist(vo); + persisted = true; + } + } + txn.commit(); + return expunged || persisted; + } + + @Override + public List getExplicitHostTags(long hostId) { + SearchCriteria sc = ImplicitTagsSearch.create(); + sc.setParameters("hostId", hostId); + sc.setParameters("isImplicit", false); + + return search(sc, null); + } + @Override public List findHostRuleTags() { SearchCriteria sc = HostSearch.create(); @@ -89,6 +145,7 @@ public class HostTagsDaoImpl extends GenericDaoBase implements txn.start(); SearchCriteria sc = HostSearch.create(); sc.setParameters("hostId", hostId); + sc.setParameters("isImplicit", false); expunge(sc); for (String tag : hostTags) { @@ -110,4 +167,72 @@ public class HostTagsDaoImpl extends GenericDaoBase implements public String getConfigComponentName() { return HostTagsDaoImpl.class.getSimpleName(); } + + @Override + public HostTagResponse newHostTagResponse(HostTagVO tag) { + HostTagResponse tagResponse = new HostTagResponse(); + + tagResponse.setName(tag.getTag()); + tagResponse.setHostId(tag.getHostId()); + tagResponse.setImplicit(tag.getIsImplicit()); + + tagResponse.setObjectName("hosttag"); + + return tagResponse; + } + + @Override + public List searchByIds(Long... tagIds) { + String batchCfg = _configDao.getValue("detail.batch.query.size"); + + final int detailsBatchSize = batchCfg != null ? Integer.parseInt(batchCfg) : 2000; + + // query details by batches + List tagList = new ArrayList<>(); + int curr_index = 0; + + if (tagIds.length > detailsBatchSize) { + while ((curr_index + detailsBatchSize) <= tagIds.length) { + Long[] ids = new Long[detailsBatchSize]; + + for (int k = 0, j = curr_index; j < curr_index + detailsBatchSize; j++, k++) { + ids[k] = tagIds[j]; + } + + SearchCriteria sc = stSearch.create(); + + sc.setParameters("idIN", (Object[])ids); + + List vms = searchIncludingRemoved(sc, null, null, false); + + if (vms != null) { + tagList.addAll(vms); + } + + curr_index += detailsBatchSize; + } + } + + if (curr_index < tagIds.length) { + int batch_size = (tagIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = tagIds[j]; + } + + SearchCriteria sc = stSearch.create(); + + sc.setParameters("idIN", (Object[])ids); + + List tags = searchIncludingRemoved(sc, null, null, false); + + if (tags != null) { + tagList.addAll(tags); + } + } + + return tagList; + } } diff --git a/engine/schema/src/main/java/com/cloud/hypervisor/HypervisorCapabilitiesVO.java b/engine/schema/src/main/java/com/cloud/hypervisor/HypervisorCapabilitiesVO.java index 118699c1f84..a3b03280fdf 100644 --- a/engine/schema/src/main/java/com/cloud/hypervisor/HypervisorCapabilitiesVO.java +++ b/engine/schema/src/main/java/com/cloud/hypervisor/HypervisorCapabilitiesVO.java @@ -19,9 +19,8 @@ package com.cloud.hypervisor; import java.util.UUID; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @@ -29,6 +28,7 @@ import javax.persistence.Table; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.NumbersUtil; +import org.apache.cloudstack.util.HypervisorTypeConverter; @Entity @Table(name = "hypervisor_capabilities") @@ -39,7 +39,7 @@ public class HypervisorCapabilitiesVO implements HypervisorCapabilities { private long id; @Column(name = "hypervisor_type") - @Enumerated(value = EnumType.STRING) + @Convert(converter = HypervisorTypeConverter.class) private HypervisorType hypervisorType; @Column(name = "hypervisor_version") diff --git a/engine/schema/src/main/java/com/cloud/hypervisor/dao/HypervisorCapabilitiesDaoImpl.java b/engine/schema/src/main/java/com/cloud/hypervisor/dao/HypervisorCapabilitiesDaoImpl.java index a4ec0a66360..f636c2eb762 100644 --- a/engine/schema/src/main/java/com/cloud/hypervisor/dao/HypervisorCapabilitiesDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/hypervisor/dao/HypervisorCapabilitiesDaoImpl.java @@ -21,7 +21,6 @@ import java.util.List; import org.apache.cloudstack.utils.CloudStackVersion; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.hypervisor.Hypervisor.HypervisorType; @@ -33,7 +32,6 @@ import com.cloud.utils.db.SearchCriteria; @Component public class HypervisorCapabilitiesDaoImpl extends GenericDaoBase implements HypervisorCapabilitiesDao { - private static final Logger s_logger = Logger.getLogger(HypervisorCapabilitiesDaoImpl.class); protected final SearchBuilder HypervisorTypeSearch; protected final SearchBuilder HypervisorTypeAndVersionSearch; @@ -80,8 +78,8 @@ public class HypervisorCapabilitiesDaoImpl extends GenericDaoBase implements VmwareDatacenterDao { - protected static final Logger s_logger = Logger.getLogger(VmwareDatacenterDaoImpl.class); final SearchBuilder nameSearch; final SearchBuilder guidSearch; diff --git a/engine/schema/src/main/java/com/cloud/network/LBHealthCheckPolicyVO.java b/engine/schema/src/main/java/com/cloud/network/LBHealthCheckPolicyVO.java index 22bb2c26b65..ee5f67b09cd 100644 --- a/engine/schema/src/main/java/com/cloud/network/LBHealthCheckPolicyVO.java +++ b/engine/schema/src/main/java/com/cloud/network/LBHealthCheckPolicyVO.java @@ -27,6 +27,7 @@ import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import com.cloud.network.rules.HealthCheckPolicy; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "load_balancer_healthcheck_policies") @@ -169,4 +170,11 @@ public class LBHealthCheckPolicyVO implements HealthCheckPolicy { public boolean isDisplay() { return display; } + + @Override + public String toString() { + return String.format("LBHealthCheckPolicy %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "pingPath")); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/as/AutoScalePolicyVO.java b/engine/schema/src/main/java/com/cloud/network/as/AutoScalePolicyVO.java index fa5dcafba34..24d8b8e7f40 100644 --- a/engine/schema/src/main/java/com/cloud/network/as/AutoScalePolicyVO.java +++ b/engine/schema/src/main/java/com/cloud/network/as/AutoScalePolicyVO.java @@ -33,6 +33,7 @@ import javax.persistence.TemporalType; import org.apache.cloudstack.api.InternalIdentity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "autoscale_policies") @@ -92,7 +93,9 @@ public class AutoScalePolicyVO implements AutoScalePolicy, InternalIdentity { @Override public String toString() { - return new StringBuilder("AutoScalePolicy[").append("id-").append(id).append("]").toString(); + return String.format("AutoScalePolicy %s.", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/as/AutoScaleVmGroupVO.java b/engine/schema/src/main/java/com/cloud/network/as/AutoScaleVmGroupVO.java index 652cbb340a3..307de9f1a60 100644 --- a/engine/schema/src/main/java/com/cloud/network/as/AutoScaleVmGroupVO.java +++ b/engine/schema/src/main/java/com/cloud/network/as/AutoScaleVmGroupVO.java @@ -32,6 +32,7 @@ import javax.persistence.TemporalType; import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import org.apache.commons.lang3.StringUtils; import com.cloud.utils.db.GenericDao; @@ -126,11 +127,9 @@ public class AutoScaleVmGroupVO implements AutoScaleVmGroup, InternalIdentity, I @Override public String toString() { - return new StringBuilder("AutoScaleVmGroupVO[").append("id=").append(id) - .append("|name=").append(name) - .append("|loadBalancerId=").append(loadBalancerId) - .append("|profileId=").append(profileId) - .append("]").toString(); + return String.format("AutoScaleVmGroup %s.", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "loadBalancerId", "profileId")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/as/AutoScaleVmProfileVO.java b/engine/schema/src/main/java/com/cloud/network/as/AutoScaleVmProfileVO.java index 21291062756..562d908507e 100644 --- a/engine/schema/src/main/java/com/cloud/network/as/AutoScaleVmProfileVO.java +++ b/engine/schema/src/main/java/com/cloud/network/as/AutoScaleVmProfileVO.java @@ -37,6 +37,7 @@ import javax.persistence.Table; import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; @@ -126,7 +127,9 @@ public class AutoScaleVmProfileVO implements AutoScaleVmProfile, Identity, Inter @Override public String toString() { - return new StringBuilder("AutoScaleVMProfileVO[").append("id").append(id).append("-").append("templateId").append("-").append(templateId).append("]").toString(); + return String.format("AutoScaleVMProfile %s.", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "templateId")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/as/ConditionVO.java b/engine/schema/src/main/java/com/cloud/network/as/ConditionVO.java index 18e67a4af61..0679dac3235 100644 --- a/engine/schema/src/main/java/com/cloud/network/as/ConditionVO.java +++ b/engine/schema/src/main/java/com/cloud/network/as/ConditionVO.java @@ -33,6 +33,7 @@ import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "conditions") @@ -91,7 +92,9 @@ public class ConditionVO implements Condition, Identity, InternalIdentity { @Override public String toString() { - return new StringBuilder("Condition[").append("id-").append(id).append("]").toString(); + return String.format("Condition %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/as/CounterVO.java b/engine/schema/src/main/java/com/cloud/network/as/CounterVO.java index e5ab9886dda..be21515bb51 100644 --- a/engine/schema/src/main/java/com/cloud/network/as/CounterVO.java +++ b/engine/schema/src/main/java/com/cloud/network/as/CounterVO.java @@ -34,6 +34,7 @@ import org.apache.cloudstack.api.InternalIdentity; import com.cloud.network.Network; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "counter") @@ -79,7 +80,9 @@ public class CounterVO implements Counter, Identity, InternalIdentity { @Override public String toString() { - return new StringBuilder("Counter[").append("id-").append(id).append("]").toString(); + return String.format("Counter %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDao.java b/engine/schema/src/main/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDao.java index 409042e7e33..9775f8ad5b1 100644 --- a/engine/schema/src/main/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDao.java +++ b/engine/schema/src/main/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDao.java @@ -36,5 +36,7 @@ public interface AutoScaleVmGroupVmMapDao extends GenericDao vmIds, Long batchSize); + int getErroredInstanceCount(long vmGroupId); } diff --git a/engine/schema/src/main/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImpl.java index 6e47cfec577..b2f4e578a82 100644 --- a/engine/schema/src/main/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImpl.java @@ -18,7 +18,10 @@ package com.cloud.network.as.dao; import java.util.List; +import javax.annotation.PostConstruct; +import javax.inject.Inject; +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; import com.cloud.network.as.AutoScaleVmGroupVmMapVO; @@ -31,9 +34,6 @@ import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.VMInstanceDao; -import javax.annotation.PostConstruct; -import javax.inject.Inject; - @Component public class AutoScaleVmGroupVmMapDaoImpl extends GenericDaoBase implements AutoScaleVmGroupVmMapDao { @@ -116,6 +116,18 @@ public class AutoScaleVmGroupVmMapDaoImpl extends GenericDaoBase= 0; } + @Override + public int expungeByVmList(List vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getInstanceId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + return batchExpunge(sc, batchSize); + } + @Override public int getErroredInstanceCount(long vmGroupId) { SearchCriteria sc = CountBy.create(); diff --git a/engine/schema/src/main/java/com/cloud/network/dao/ExternalLoadBalancerDeviceVO.java b/engine/schema/src/main/java/com/cloud/network/dao/ExternalLoadBalancerDeviceVO.java index 80bec1b8152..88c5c0885a8 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/ExternalLoadBalancerDeviceVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/ExternalLoadBalancerDeviceVO.java @@ -30,6 +30,7 @@ import javax.persistence.Table; import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; import org.apache.cloudstack.network.ExternalNetworkDeviceManager; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; /** * ExternalLoadBalancerDeviceVO contains information on external load balancer devices (F5/Netscaler VPX,MPX,SDX) added into a deployment @@ -244,4 +245,11 @@ public class ExternalLoadBalancerDeviceVO implements InternalIdentity, Identity public void setUuid(String uuid) { this.uuid = uuid; } + + @Override + public String toString() { + return String.format("ExternalLoadBalancerDevice %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "providerName")); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesCidrsDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesCidrsDaoImpl.java index 4630925ddee..6279289bdfe 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesCidrsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesCidrsDaoImpl.java @@ -21,7 +21,6 @@ import java.util.List; import org.apache.commons.collections4.CollectionUtils; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.DB; @@ -32,7 +31,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class FirewallRulesCidrsDaoImpl extends GenericDaoBase implements FirewallRulesCidrsDao { - private static final Logger s_logger = Logger.getLogger(FirewallRulesCidrsDaoImpl.class); protected final SearchBuilder CidrsSearch; protected FirewallRulesCidrsDaoImpl() { @@ -48,7 +46,7 @@ public class FirewallRulesCidrsDaoImpl extends GenericDaoBase results = search(sc, null); - List cidrs = new ArrayList(results.size()); + List cidrs = new ArrayList<>(results.size()); for (FirewallRulesCidrsVO result : results) { cidrs.add(result.getCidr()); } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesDao.java b/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesDao.java index 21200dbf9b5..b80ccd9cd1b 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesDao.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesDao.java @@ -72,4 +72,6 @@ public interface FirewallRulesDao extends GenericDao { void loadSourceCidrs(FirewallRuleVO rule); void loadDestinationCidrs(FirewallRuleVO rule); + + List listRoutingIngressFirewallRules(long networkId); } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesDaoImpl.java index f18fb98f3de..c8bd7e2147e 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/FirewallRulesDaoImpl.java @@ -50,6 +50,7 @@ public class FirewallRulesDaoImpl extends GenericDaoBase i protected SearchBuilder VmSearch; protected final SearchBuilder SystemRuleSearch; protected final GenericSearchBuilder RulesByIpCount; + protected final SearchBuilder RoutingFirewallRulesSearch; @Inject protected FirewallRulesCidrsDao _firewallRulesCidrsDao; @@ -104,6 +105,13 @@ public class FirewallRulesDaoImpl extends GenericDaoBase i RulesByIpCount.and("ipAddressId", RulesByIpCount.entity().getSourceIpAddressId(), Op.EQ); RulesByIpCount.and("state", RulesByIpCount.entity().getState(), Op.EQ); RulesByIpCount.done(); + + RoutingFirewallRulesSearch = createSearchBuilder(); + RoutingFirewallRulesSearch.and("networkId", RoutingFirewallRulesSearch.entity().getNetworkId(), Op.EQ); + RoutingFirewallRulesSearch.and("purpose", RoutingFirewallRulesSearch.entity().getPurpose(), Op.EQ); + RoutingFirewallRulesSearch.and("trafficType", RoutingFirewallRulesSearch.entity().getTrafficType(), Op.EQ); + RoutingFirewallRulesSearch.and("ipId", RoutingFirewallRulesSearch.entity().getSourceIpAddressId(), Op.NULL); + RoutingFirewallRulesSearch.done(); } @Override @@ -383,4 +391,12 @@ public class FirewallRulesDaoImpl extends GenericDaoBase i rule.setDestinationCidrsList(destCidrs); } + @Override + public List listRoutingIngressFirewallRules(long networkId) { + SearchCriteria sc = RoutingFirewallRulesSearch.create(); + sc.setParameters("networkId", networkId); + sc.setParameters("purpose", Purpose.Firewall); + sc.setParameters("trafficType", TrafficType.Ingress); + return listBy(sc); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/IPAddressDao.java b/engine/schema/src/main/java/com/cloud/network/dao/IPAddressDao.java index b1b1e1cf757..3f8c36ac94e 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/IPAddressDao.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/IPAddressDao.java @@ -105,4 +105,6 @@ public interface IPAddressDao extends GenericDao { void buildQuarantineSearchCriteria(SearchCriteria sc); IPAddressVO findBySourceNetworkIdAndDatacenterIdAndState(long sourceNetworkId, long dataCenterId, State state); + + int expungeByVmList(List vmIds, Long batchSize); } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/IPAddressDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/IPAddressDaoImpl.java index d1427522715..5499d04e3a1 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/IPAddressDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/IPAddressDaoImpl.java @@ -26,7 +26,7 @@ import javax.inject.Inject; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.resourcedetail.dao.UserIpAddressDetailsDao; -import org.apache.log4j.Logger; +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; import com.cloud.dc.Vlan.VlanType; @@ -50,7 +50,6 @@ import com.cloud.utils.net.Ip; @Component @DB public class IPAddressDaoImpl extends GenericDaoBase implements IPAddressDao { - private static final Logger s_logger = Logger.getLogger(IPAddressDaoImpl.class); protected SearchBuilder AllFieldsSearch; protected SearchBuilder VlanDbIdSearchUnallocated; @@ -374,7 +373,7 @@ public class IPAddressDaoImpl extends GenericDaoBase implemen ipCount = rs.getInt(1); } } catch (Exception e) { - s_logger.warn("Exception counting IP addresses", e); + logger.warn("Exception counting IP addresses", e); } return ipCount; @@ -422,7 +421,7 @@ public class IPAddressDaoImpl extends GenericDaoBase implemen public long countFreeIpsInVlan(long vlanDbId) { SearchCriteria sc = VlanDbIdSearchUnallocated.create(); sc.setParameters("vlanDbId", vlanDbId); - return listBy(sc).size(); + return getCount(sc); } @Override @@ -563,4 +562,16 @@ public class IPAddressDaoImpl extends GenericDaoBase implemen sc.setParameters("state", State.Free); return findOneBy(sc); } + + @Override + public int expungeByVmList(List vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getAssociatedWithVmId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + return batchExpunge(sc, batchSize); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/IPAddressVO.java b/engine/schema/src/main/java/com/cloud/network/dao/IPAddressVO.java index 4c7569a55b9..88e146d2a80 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/IPAddressVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/IPAddressVO.java @@ -33,6 +33,7 @@ import javax.persistence.TemporalType; import com.cloud.network.IpAddress; import com.cloud.utils.db.GenericDao; import com.cloud.utils.net.Ip; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; /** * A bean representing a public IP Address @@ -268,7 +269,9 @@ public class IPAddressVO implements IpAddress { @Override public String toString() { - return new StringBuilder("Ip[").append(address).append("-").append(dataCenterId).append("]").toString(); + return String.format("IPAddress %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "dataCenterId", "address")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapDao.java b/engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapDao.java index ac3845beffe..b1831b407a4 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapDao.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapDao.java @@ -16,10 +16,14 @@ // under the License. package com.cloud.network.dao; +import java.util.List; + import com.cloud.utils.db.GenericDao; public interface InlineLoadBalancerNicMapDao extends GenericDao { InlineLoadBalancerNicMapVO findByPublicIpAddress(String publicIpAddress); InlineLoadBalancerNicMapVO findByNicId(long nicId); + int expungeByNicList(List nicIds, Long batchSize); + } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapDaoImpl.java index 1c3f231f9c1..d64ba8b4155 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/InlineLoadBalancerNicMapDaoImpl.java @@ -17,9 +17,13 @@ package com.cloud.network.dao; +import java.util.List; + +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @Component @@ -41,4 +45,15 @@ public class InlineLoadBalancerNicMapDaoImpl extends GenericDaoBase nicIds, Long batchSize) { + if (CollectionUtils.isEmpty(nicIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("nicIds", sb.entity().getNicId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("nicIds", nicIds.toArray()); + return batchExpunge(sc, batchSize); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/LBStickinessPolicyVO.java b/engine/schema/src/main/java/com/cloud/network/dao/LBStickinessPolicyVO.java index e9f50a75a7b..72b8fc151b7 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/LBStickinessPolicyVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/LBStickinessPolicyVO.java @@ -33,6 +33,7 @@ import javax.persistence.Table; import com.cloud.network.rules.StickinessPolicy; import com.cloud.utils.Pair; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "load_balancer_stickiness_policies") @@ -162,4 +163,11 @@ public class LBStickinessPolicyVO implements StickinessPolicy { public boolean isDisplay() { return display; } + + @Override + public String toString() { + return String.format("LBStickinessPolicy %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "methodName")); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVMMapDao.java b/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVMMapDao.java index a25534b7010..be2941d5cb2 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVMMapDao.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVMMapDao.java @@ -42,4 +42,5 @@ public interface LoadBalancerVMMapDao extends GenericDao vmIds, Long batchSize); } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java index b32320a84cb..dc37cdeefe3 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java @@ -18,11 +18,12 @@ package com.cloud.network.dao; import java.util.List; - +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; @@ -135,4 +136,16 @@ public class LoadBalancerVMMapDaoImpl extends GenericDaoBase vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getInstanceId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + return batchExpunge(sc, batchSize); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVO.java b/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVO.java index bd5ea95dcc7..ad0338b9849 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/LoadBalancerVO.java @@ -27,6 +27,7 @@ import javax.persistence.Table; import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.LoadBalancer; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; /** * This VO represents Public Load Balancer @@ -136,4 +137,11 @@ public class LoadBalancerVO extends FirewallRuleVO implements LoadBalancer { public String getCidrList() { return cidrList; } + + @Override + public String toString() { + return String.format("LoadBalancer %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "purpose", "state")); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/NetworkDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/NetworkDaoImpl.java index fa448b026e4..0aae532eac5 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/NetworkDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/NetworkDaoImpl.java @@ -415,8 +415,7 @@ public class NetworkDaoImpl extends GenericDaoBaseimplements Ne sc.setParameters("broadcastUri", broadcastURI); sc.setParameters("guestType", guestTypes); sc.setJoinParameters("persistent", "persistent", isPersistent); - List persistentNetworks = search(sc, null); - return persistentNetworks.size(); + return getCount(sc); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/dao/NetworkDomainDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/NetworkDomainDaoImpl.java index ce86a8636a1..e8c55131ecd 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/NetworkDomainDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/NetworkDomainDaoImpl.java @@ -26,7 +26,6 @@ import java.util.List; import java.util.Map; import com.cloud.utils.db.TransactionLegacy; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.DB; @@ -38,7 +37,6 @@ import com.cloud.utils.db.SearchCriteria.Op; @Component @DB() public class NetworkDomainDaoImpl extends GenericDaoBase implements NetworkDomainDao { - public static Logger logger = Logger.getLogger(NetworkDomainDaoImpl.class.getName()); final SearchBuilder AllFieldsSearch; final SearchBuilder DomainsSearch; diff --git a/engine/schema/src/main/java/com/cloud/network/dao/NetworkServiceMapDao.java b/engine/schema/src/main/java/com/cloud/network/dao/NetworkServiceMapDao.java index e0509f80c2a..1675c89811a 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/NetworkServiceMapDao.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/NetworkServiceMapDao.java @@ -30,6 +30,8 @@ import com.cloud.utils.db.GenericDao; public interface NetworkServiceMapDao extends GenericDao { boolean areServicesSupportedInNetwork(long networkId, Service... services); + boolean isAnyServiceSupportedInNetwork(long networkId, Provider provider, Service... services); + boolean canProviderSupportServiceInNetwork(long networkId, Service service, Provider provider); List getServicesInNetwork(long networkId); diff --git a/engine/schema/src/main/java/com/cloud/network/dao/NetworkServiceMapDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/NetworkServiceMapDaoImpl.java index 31e083075fa..f25bee5da47 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/NetworkServiceMapDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/NetworkServiceMapDaoImpl.java @@ -90,6 +90,28 @@ public class NetworkServiceMapDaoImpl extends GenericDaoBase sc = MultipleServicesSearch.create(); + sc.setParameters("networkId", networkId); + sc.setParameters("provider", provider.getName()); + + if (services != null) { + String[] servicesStr = new String[services.length]; + + int i = 0; + for (Service service : services) { + servicesStr[i] = service.getName(); + i++; + } + + sc.setParameters("service", (Object[])servicesStr); + } + + List networkServices = listBy(sc); + return !networkServices.isEmpty(); + } + @Override public boolean canProviderSupportServiceInNetwork(long networkId, Service service, Provider provider) { SearchCriteria sc = AllFieldsSearch.create(); diff --git a/engine/schema/src/main/java/com/cloud/network/dao/NetworkVO.java b/engine/schema/src/main/java/com/cloud/network/dao/NetworkVO.java index f24eec4931e..02abaacd854 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/NetworkVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/NetworkVO.java @@ -39,7 +39,6 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; import com.cloud.utils.net.NetUtils; -import org.apache.log4j.Logger; /** * NetworkConfigurationVO contains information about a specific network. @@ -48,7 +47,6 @@ import org.apache.log4j.Logger; @Entity @Table(name = "networks") public class NetworkVO implements Network { - static final Logger s_logger = Logger.getLogger(NetworkVO.class); @Id @TableGenerator(name = "networks_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "networks_seq", allocationSize = 1) @Column(name = "id") @@ -205,6 +203,9 @@ public class NetworkVO implements Network { @Column(name = "private_mtu") Integer privateMtu; + @Transient + Integer networkCidrSize; + public NetworkVO() { uuid = UUID.randomUUID().toString(); } @@ -369,6 +370,10 @@ public class NetworkVO implements Network { return mode; } + public void setAccountId(long accountId) { + this.accountId = accountId; + } + @Override public long getAccountId() { return accountId; @@ -442,6 +447,7 @@ public class NetworkVO implements Network { return gateway; } + @Override public void setGateway(String gateway) { this.gateway = gateway; } @@ -455,6 +461,7 @@ public class NetworkVO implements Network { return cidr; } + @Override public void setCidr(String cidr) { this.cidr = cidr; } @@ -757,4 +764,13 @@ public class NetworkVO implements Network { public void setPrivateMtu(Integer privateMtu) { this.privateMtu = privateMtu; } + + @Override + public Integer getNetworkCidrSize() { + return networkCidrSize; + } + + public void setNetworkCidrSize(Integer networkCidrSize) { + this.networkCidrSize = networkCidrSize; + } } diff --git a/server/src/main/java/com/cloud/api/query/dao/HostTagDao.java b/engine/schema/src/main/java/com/cloud/network/dao/NsxProviderDao.java similarity index 73% rename from server/src/main/java/com/cloud/api/query/dao/HostTagDao.java rename to engine/schema/src/main/java/com/cloud/network/dao/NsxProviderDao.java index ab43e71221c..0fc77537711 100644 --- a/server/src/main/java/com/cloud/api/query/dao/HostTagDao.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/NsxProviderDao.java @@ -14,17 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.query.dao; +package com.cloud.network.dao; + +import com.cloud.network.element.NsxProviderVO; +import com.cloud.utils.db.GenericDao; import java.util.List; -import org.apache.cloudstack.api.response.HostTagResponse; +public interface NsxProviderDao extends GenericDao { + NsxProviderVO findByZoneId(long zoneId); -import com.cloud.api.query.vo.HostTagVO; -import com.cloud.utils.db.GenericDao; + NsxProviderVO findByUuid(String uuid); -public interface HostTagDao extends GenericDao { - HostTagResponse newHostTagResponse(HostTagVO hostTag); - - List searchByIds(Long... hostTagIds); + List findAll(); } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/NsxProviderDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/NsxProviderDaoImpl.java new file mode 100644 index 00000000000..cf7b5d405c0 --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/network/dao/NsxProviderDaoImpl.java @@ -0,0 +1,65 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.network.dao; + +import com.cloud.network.element.NsxProviderVO; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +@DB() +public class NsxProviderDaoImpl extends GenericDaoBase + implements NsxProviderDao { + + final SearchBuilder allFieldsSearch; + + public NsxProviderDaoImpl() { + super(); + allFieldsSearch = createSearchBuilder(); + allFieldsSearch.and("id", allFieldsSearch.entity().getId(), + SearchCriteria.Op.EQ); + allFieldsSearch.and("uuid", allFieldsSearch.entity().getUuid(), + SearchCriteria.Op.EQ); + allFieldsSearch.and("hostname", allFieldsSearch.entity().getHostname(), + SearchCriteria.Op.EQ); + allFieldsSearch.and("provider_name", allFieldsSearch.entity().getProviderName(), + SearchCriteria.Op.EQ); + allFieldsSearch.and("tier0_gateway", allFieldsSearch.entity().getTier0Gateway(), + SearchCriteria.Op.EQ); + allFieldsSearch.and("zone_id", allFieldsSearch.entity().getZoneId(), + SearchCriteria.Op.EQ); + allFieldsSearch.and("edge_cluster", allFieldsSearch.entity().getEdgeCluster(), + SearchCriteria.Op.EQ); + allFieldsSearch.done(); + } + @Override + public NsxProviderVO findByZoneId(long zoneId) { + SearchCriteria sc = allFieldsSearch.create(); + sc.setParameters("zone_id", zoneId); + return findOneBy(sc); + } + + @Override + public List findAll() { + return listAll(); + } +} diff --git a/engine/schema/src/main/java/com/cloud/network/dao/OpRouterMonitorServiceDao.java b/engine/schema/src/main/java/com/cloud/network/dao/OpRouterMonitorServiceDao.java index ebc0f1af227..0516e26e13a 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/OpRouterMonitorServiceDao.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/OpRouterMonitorServiceDao.java @@ -18,8 +18,12 @@ package com.cloud.network.dao; +import java.util.List; + import com.cloud.utils.db.GenericDao; public interface OpRouterMonitorServiceDao extends GenericDao { + int expungeByVmList(List vmIds, Long batchSize); + } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/OpRouterMonitorServiceDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/OpRouterMonitorServiceDaoImpl.java index 451320ac9b6..a8e818cfb18 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/OpRouterMonitorServiceDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/OpRouterMonitorServiceDaoImpl.java @@ -17,10 +17,27 @@ package com.cloud.network.dao; -import com.cloud.utils.db.GenericDaoBase; +import java.util.List; + +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + @Component public class OpRouterMonitorServiceDaoImpl extends GenericDaoBase implements OpRouterMonitorServiceDao { + @Override + public int expungeByVmList(List vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + return batchExpunge(sc, batchSize); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java b/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java index 415b513b405..9557c7465bf 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java @@ -35,6 +35,7 @@ import org.apache.cloudstack.api.InternalIdentity; import com.cloud.network.Network.Service; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "physical_network_service_providers") @@ -109,6 +110,13 @@ public class PhysicalNetworkServiceProviderVO implements PhysicalNetworkServiceP this.uuid = UUID.randomUUID().toString(); } + + @Override + public String toString() { + return String.format("PhysicalNetworkServiceProvider %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "providerName")); + } + @Override public long getId() { return id; diff --git a/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkVO.java b/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkVO.java index 52ebe7596a4..68e023984a0 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkVO.java @@ -37,6 +37,7 @@ import com.cloud.network.PhysicalNetwork; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; /** * NetworkConfigurationVO contains information about a specific physical network. @@ -248,4 +249,11 @@ public class PhysicalNetworkVO implements PhysicalNetwork { public String getName() { return name; } + + @Override + public String toString() { + return String.format("PhysicalNetwork %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/PortProfileDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/PortProfileDaoImpl.java index a90ce059c31..eb2a1968158 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/PortProfileDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/PortProfileDaoImpl.java @@ -22,7 +22,6 @@ import java.sql.SQLException; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.DB; @@ -36,7 +35,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component @DB() public class PortProfileDaoImpl extends GenericDaoBase implements PortProfileDao { - protected static final Logger s_logger = Logger.getLogger(PortProfileDaoImpl.class); final SearchBuilder nameSearch; final SearchBuilder accessVlanSearch; diff --git a/engine/schema/src/main/java/com/cloud/network/dao/RemoteAccessVpnDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/RemoteAccessVpnDaoImpl.java index 3aa2e749712..484aa6f6631 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/RemoteAccessVpnDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/RemoteAccessVpnDaoImpl.java @@ -19,7 +19,6 @@ package com.cloud.network.dao; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.network.RemoteAccessVpn; @@ -29,7 +28,6 @@ import com.cloud.utils.db.SearchCriteria; @Component public class RemoteAccessVpnDaoImpl extends GenericDaoBase implements RemoteAccessVpnDao { - private static final Logger s_logger = Logger.getLogger(RemoteAccessVpnDaoImpl.class); private final SearchBuilder AllFieldsSearch; diff --git a/engine/schema/src/main/java/com/cloud/network/dao/RemoteAccessVpnVO.java b/engine/schema/src/main/java/com/cloud/network/dao/RemoteAccessVpnVO.java index 95e3693a99c..2439ea55b4a 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/RemoteAccessVpnVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/RemoteAccessVpnVO.java @@ -18,6 +18,7 @@ package com.cloud.network.dao; import com.cloud.network.RemoteAccessVpn; import com.cloud.utils.db.Encrypt; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import javax.persistence.Column; import javax.persistence.Entity; @@ -86,6 +87,11 @@ public class RemoteAccessVpnVO implements RemoteAccessVpn { this.vpcId = vpcId; } + @Override + public String toString() { + return String.format("RemoteAccessVpn %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "uuid")); + } + @Override public State getState() { return state; diff --git a/engine/schema/src/main/java/com/cloud/network/dao/RouterHealthCheckResultDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/RouterHealthCheckResultDaoImpl.java index 991365b5f54..b1292aebfd1 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/RouterHealthCheckResultDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/RouterHealthCheckResultDaoImpl.java @@ -19,7 +19,6 @@ package com.cloud.network.dao; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.GenericDaoBase; @@ -28,7 +27,6 @@ import com.cloud.utils.db.SearchCriteria; @Component public class RouterHealthCheckResultDaoImpl extends GenericDaoBase implements RouterHealthCheckResultDao { - private final static Logger s_logger = Logger.getLogger(RouterHealthCheckResultDaoImpl.class); private SearchBuilder RouterChecksSearchBuilder; private SearchBuilder IsRouterFailingSearchBuilder; @@ -69,7 +67,7 @@ public class RouterHealthCheckResultDaoImpl extends GenericDaoBase checks = listBy(sc); if (checks.size() > 1) { - s_logger.error("Found multiple entries for router Id: " + routerId + ", check name: " + checkName); + logger.error("Found multiple entries for router Id: " + routerId + ", check name: " + checkName); } return checks.isEmpty() ? null : checks.get(0); } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteCustomerGatewayVO.java b/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteCustomerGatewayVO.java index 52741fdd9a5..e5394238c31 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteCustomerGatewayVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteCustomerGatewayVO.java @@ -29,6 +29,7 @@ import javax.persistence.Table; import com.cloud.network.Site2SiteCustomerGateway; import com.cloud.utils.db.Encrypt; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @@ -110,6 +111,13 @@ public class Site2SiteCustomerGatewayVO implements Site2SiteCustomerGateway { this.ikeVersion = ikeVersion; } + @Override + public String toString() { + return String.format("Site2SiteCustomerGateway %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); + } + @Override public long getId() { return id; diff --git a/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnConnectionDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnConnectionDaoImpl.java index b55f39ab31b..f9c5ce08964 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnConnectionDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnConnectionDaoImpl.java @@ -21,7 +21,6 @@ import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.GenericDaoBase; @@ -31,7 +30,6 @@ import com.cloud.utils.db.SearchCriteria; @Component public class Site2SiteVpnConnectionDaoImpl extends GenericDaoBase implements Site2SiteVpnConnectionDao { - private static final Logger s_logger = Logger.getLogger(Site2SiteVpnConnectionDaoImpl.class); @Inject protected IPAddressDao _addrDao; diff --git a/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnConnectionVO.java b/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnConnectionVO.java index b032966dd5a..4d6bee5c861 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnConnectionVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnConnectionVO.java @@ -32,6 +32,7 @@ import org.apache.cloudstack.api.InternalIdentity; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @@ -182,4 +183,11 @@ public class Site2SiteVpnConnectionVO implements Site2SiteVpnConnection, Interna public String getName() { return null; } + + @Override + public String toString() { + return String.format("Site2SiteVpnConnection %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "state")); + } } diff --git a/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnGatewayDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnGatewayDaoImpl.java index 80465f9ee1e..d1fde963217 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnGatewayDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnGatewayDaoImpl.java @@ -18,7 +18,6 @@ package com.cloud.network.dao; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.GenericDaoBase; @@ -30,7 +29,6 @@ public class Site2SiteVpnGatewayDaoImpl extends GenericDaoBase AllFieldsSearch; diff --git a/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnGatewayVO.java b/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnGatewayVO.java index 703c78c7b86..a5eb7efce23 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnGatewayVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/Site2SiteVpnGatewayVO.java @@ -28,6 +28,7 @@ import javax.persistence.Table; import com.cloud.network.Site2SiteVpnGateway; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @@ -70,6 +71,13 @@ public class Site2SiteVpnGatewayVO implements Site2SiteVpnGateway { this.domainId = domainId; } + @Override + public String toString() { + return String.format("Site2SiteVpnGateway %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); + } + @Override public long getId() { return id; diff --git a/engine/schema/src/main/java/com/cloud/network/dao/UserIpv6AddressDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/UserIpv6AddressDaoImpl.java index 08f0829f4ac..407d34fa365 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/UserIpv6AddressDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/UserIpv6AddressDaoImpl.java @@ -20,7 +20,6 @@ import java.util.List; import com.cloud.network.IpAddress; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.network.UserIpv6AddressVO; @@ -33,7 +32,6 @@ import com.cloud.utils.db.SearchCriteria.Op; @Component public class UserIpv6AddressDaoImpl extends GenericDaoBase implements UserIpv6AddressDao { - private static final Logger s_logger = Logger.getLogger(IPAddressDaoImpl.class); protected final SearchBuilder AllFieldsSearch; protected GenericSearchBuilder CountFreePublicIps; diff --git a/engine/schema/src/main/java/com/cloud/network/element/NsxProviderVO.java b/engine/schema/src/main/java/com/cloud/network/element/NsxProviderVO.java new file mode 100644 index 00000000000..f08e08b1ca0 --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/network/element/NsxProviderVO.java @@ -0,0 +1,285 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.network.element; + +import com.cloud.network.nsx.NsxProvider; +import com.cloud.utils.db.Encrypt; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import java.util.Date; +import java.util.UUID; + +@Entity +@Table(name = "nsx_providers") +public class NsxProviderVO implements NsxProvider { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + long id; + + @Column(name = "zone_id") + private long zoneId; + + @Column(name = "host_id") + private long hostId; + + @Column(name = "uuid") + private String uuid; + + @Column(name = "provider_name") + private String providerName; + + @Column(name = "hostname") + private String hostname; + + @Column(name = "port") + private String port = "443"; + + @Column(name = "username") + private String username; + + @Encrypt + @Column(name = "password") + private String password; + + @Column(name = "tier0_gateway") + private String tier0Gateway; + + @Column(name = "edge_cluster") + private String edgeCluster; + + @Column(name = "transport_zone") + private String transportZone; + + @Column(name = "created") + private Date created; + + @Column(name = "removed") + private Date removed; + public NsxProviderVO() { + this.uuid = UUID.randomUUID().toString(); + } + + @Override + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + @Override + public long getZoneId() { + return zoneId; + } + + public void setZoneId(long zoneId) { + this.zoneId = zoneId; + } + + public long getHostId() { + return hostId; + } + + public void setHostId(long hostId) { + this.hostId = hostId; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + @Override + public String getProviderName() { + return providerName; + } + + public void setProviderName(String providerName) { + this.providerName = providerName; + } + + @Override + public String getHostname() { + return hostname; + } + + public void setPort(String port) { + this.port = port; + } + + @Override + public String getPort() { + return port; + } + + public void setHostname(String hostname) { + this.hostname = hostname; + } + + @Override + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getTier0Gateway() { + return tier0Gateway; + } + + public void setTier0Gateway(String tier0Gateway) { + this.tier0Gateway = tier0Gateway; + } + + public String getEdgeCluster() { + return edgeCluster; + } + + public void setEdgeCluster(String edgeCluster) { + this.edgeCluster = edgeCluster; + } + + public String getTransportZone() { + return transportZone; + } + + public void setTransportZone(String transportZone) { + this.transportZone = transportZone; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public static final class Builder { + private long zoneId; + private long hostId; + private String providerName; + private String hostname; + private String port; + private String username; + private String password; + private String tier0Gateway; + private String edgeCluster; + private String transportZone; + + + public Builder() { + // Default constructor + } + + public Builder setZoneId(long zoneId) { + this.zoneId = zoneId; + return this; + } + + public Builder setHostId(long hostId) { + this.hostId = hostId; + return this; + } + + public Builder setProviderName(String providerName) { + this.providerName = providerName; + return this; + } + + public Builder setHostname(String hostname) { + this.hostname = hostname; + return this; + } + + public Builder setPort(String port) { + this.port = port; + return this; + } + + public Builder setUsername(String username) { + this.username = username; + return this; + } + + public Builder setPassword(String password) { + this.password = password; + return this; + } + + public Builder setTier0Gateway(String tier0Gateway) { + this.tier0Gateway = tier0Gateway; + return this; + } + + public Builder setEdgeCluster(String edgeCluster) { + this.edgeCluster = edgeCluster; + return this; + } + + public Builder setTransportZone(String transportZone) { + this.transportZone = transportZone; + return this; + } + public NsxProviderVO build() { + NsxProviderVO provider = new NsxProviderVO(); + provider.setZoneId(this.zoneId); + provider.setHostId(this.hostId); + provider.setUuid(UUID.randomUUID().toString()); + provider.setProviderName(this.providerName); + provider.setHostname(this.hostname); + provider.setPort(this.port); + provider.setUsername(this.username); + provider.setPassword(this.password); + provider.setTier0Gateway(this.tier0Gateway); + provider.setEdgeCluster(this.edgeCluster); + provider.setTransportZone(this.transportZone); + provider.setCreated(new Date()); + return provider; + } + } +} diff --git a/engine/schema/src/main/java/com/cloud/network/rules/FirewallRuleVO.java b/engine/schema/src/main/java/com/cloud/network/rules/FirewallRuleVO.java index 07b25e7a28c..1dfdc5093a5 100644 --- a/engine/schema/src/main/java/com/cloud/network/rules/FirewallRuleVO.java +++ b/engine/schema/src/main/java/com/cloud/network/rules/FirewallRuleVO.java @@ -36,6 +36,7 @@ import javax.persistence.Transient; import com.cloud.utils.db.GenericDao; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "firewall_rules") @@ -258,7 +259,9 @@ public class FirewallRuleVO implements FirewallRule { @Override public String toString() { - return new StringBuilder("Rule[").append(id).append("-").append(purpose).append("-").append(state).append("]").toString(); + return String.format("FirewallRule %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "networkId", "purpose", "state")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/rules/PortForwardingRuleVO.java b/engine/schema/src/main/java/com/cloud/network/rules/PortForwardingRuleVO.java index 28d12fb24b4..576e2f8172e 100644 --- a/engine/schema/src/main/java/com/cloud/network/rules/PortForwardingRuleVO.java +++ b/engine/schema/src/main/java/com/cloud/network/rules/PortForwardingRuleVO.java @@ -64,6 +64,16 @@ public class PortForwardingRuleVO extends FirewallRuleVO implements PortForwardi this.sourceCidrs = sourceCidrs; } + public PortForwardingRuleVO(String xId, long srcIpId, int srcPortStart, int srcPortEnd, Ip dstIp, int dstPortStart, int dstPortEnd, String protocol, long networkId, + long accountId, long domainId, long instanceId) { + this(xId, srcIpId, srcPortStart, srcPortEnd, dstIp, dstPortStart, dstPortEnd, protocol.toLowerCase(), networkId, accountId, domainId, instanceId, null); + } + + public PortForwardingRuleVO(String xId, long srcIpId, int srcPort, Ip dstIp, int dstPort, String protocol, long networkId, long accountId, + long domainId, long instanceId) { + this(xId, srcIpId, srcPort, srcPort, dstIp, dstPort, dstPort, protocol.toLowerCase(), networkId, accountId, domainId, instanceId, null); + } + @Override public Ip getDestinationIpAddress() { return destinationIpAddress; diff --git a/engine/schema/src/main/java/com/cloud/network/rules/dao/PortForwardingRulesDao.java b/engine/schema/src/main/java/com/cloud/network/rules/dao/PortForwardingRulesDao.java index b89d04ad15a..8cd114b7fc4 100644 --- a/engine/schema/src/main/java/com/cloud/network/rules/dao/PortForwardingRulesDao.java +++ b/engine/schema/src/main/java/com/cloud/network/rules/dao/PortForwardingRulesDao.java @@ -47,4 +47,5 @@ public interface PortForwardingRulesDao extends GenericDao listByNetworkAndDestIpAddr(String ip4Address, long networkId); + int expungeByVmList(List vmIds, Long batchSize); } diff --git a/engine/schema/src/main/java/com/cloud/network/rules/dao/PortForwardingRulesDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/rules/dao/PortForwardingRulesDaoImpl.java index 1ddecaa8a17..1b3df06e1a2 100644 --- a/engine/schema/src/main/java/com/cloud/network/rules/dao/PortForwardingRulesDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/rules/dao/PortForwardingRulesDaoImpl.java @@ -20,9 +20,7 @@ import java.util.List; import javax.inject.Inject; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallback; -import com.cloud.utils.db.TransactionLegacy; +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; import com.cloud.network.dao.FirewallRulesCidrsDao; @@ -33,6 +31,9 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallback; +import com.cloud.utils.db.TransactionLegacy; @Component public class PortForwardingRulesDaoImpl extends GenericDaoBase implements PortForwardingRulesDao { @@ -175,6 +176,17 @@ public class PortForwardingRulesDaoImpl extends GenericDaoBase vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getVirtualMachineId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + return batchExpunge(sc, batchSize); + } + public PortForwardingRuleVO persist(PortForwardingRuleVO portForwardingRule) { return Transaction.execute((TransactionCallback) transactionStatus -> { PortForwardingRuleVO dbPfRule = super.persist(portForwardingRule); diff --git a/engine/schema/src/main/java/com/cloud/network/security/SecurityGroupRuleVO.java b/engine/schema/src/main/java/com/cloud/network/security/SecurityGroupRuleVO.java index 1980cd33d14..325a6efc867 100644 --- a/engine/schema/src/main/java/com/cloud/network/security/SecurityGroupRuleVO.java +++ b/engine/schema/src/main/java/com/cloud/network/security/SecurityGroupRuleVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.security; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; + import java.util.UUID; import javax.persistence.Column; @@ -89,6 +91,13 @@ public class SecurityGroupRuleVO implements SecurityRule { } } + @Override + public String toString() { + return String.format("SecurityGroupRule %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "type")); + } + @Override public long getId() { return id; diff --git a/engine/schema/src/main/java/com/cloud/network/security/SecurityGroupVO.java b/engine/schema/src/main/java/com/cloud/network/security/SecurityGroupVO.java index ec1cfae43b6..940baaad18d 100644 --- a/engine/schema/src/main/java/com/cloud/network/security/SecurityGroupVO.java +++ b/engine/schema/src/main/java/com/cloud/network/security/SecurityGroupVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.security; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; + import java.util.UUID; import javax.persistence.Column; @@ -60,6 +62,13 @@ public class SecurityGroupVO implements SecurityGroup { uuid = UUID.randomUUID().toString(); } + @Override + public String toString() { + return String.format("SecurityGroup %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); + } + @Override public long getId() { return id; diff --git a/engine/schema/src/main/java/com/cloud/network/security/dao/SecurityGroupWorkDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/security/dao/SecurityGroupWorkDaoImpl.java index 9b0bf088a14..327d12c759a 100644 --- a/engine/schema/src/main/java/com/cloud/network/security/dao/SecurityGroupWorkDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/security/dao/SecurityGroupWorkDaoImpl.java @@ -20,7 +20,6 @@ import java.util.Date; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.network.security.SecurityGroupWork; @@ -37,7 +36,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class SecurityGroupWorkDaoImpl extends GenericDaoBase implements SecurityGroupWorkDao { - private static final Logger s_logger = Logger.getLogger(SecurityGroupWorkDaoImpl.class); private final SearchBuilder VmIdTakenSearch; private final SearchBuilder VmIdSeqNumSearch; @@ -107,8 +105,8 @@ public class SecurityGroupWorkDaoImpl extends GenericDaoBase vos = lockRows(sc, filter, true); if (vos.size() == 0) { txn.commit(); - if (s_logger.isTraceEnabled()) { - s_logger.trace("Security Group take: no work found"); + if (logger.isTraceEnabled()) { + logger.trace("Security Group take: no work found"); } return null; } @@ -117,8 +115,8 @@ public class SecurityGroupWorkDaoImpl extends GenericDaoBase im } catch (SQLTransactionRollbackException e1) { if (i < maxTries - 1) { int delayMs = (i + 1) * 1000; - s_logger.debug("Caught a deadlock exception while inserting security group rule log, retrying in " + delayMs); + logger.debug("Caught a deadlock exception while inserting security group rule log, retrying in " + delayMs); try { Thread.sleep(delayMs); } catch (InterruptedException ie) { - s_logger.debug("[ignored] interrupted while inserting security group rule log."); + logger.debug("[ignored] interrupted while inserting security group rule log."); } } else - s_logger.warn("Caught another deadlock exception while retrying inserting security group rule log, giving up"); + logger.warn("Caught another deadlock exception while retrying inserting security group rule log, giving up"); } } - if (s_logger.isTraceEnabled()) { - s_logger.trace("Inserted or updated " + numUpdated + " rows"); + if (logger.isTraceEnabled()) { + logger.trace("Inserted or updated " + numUpdated + " rows"); } return numUpdated; } @@ -134,8 +132,8 @@ public class VmRulesetLogDaoImpl extends GenericDaoBase im vmIds.add(vmId); } int numUpdated = executeWithRetryOnDeadlock(txn, pstmt, vmIds); - if (s_logger.isTraceEnabled()) { - s_logger.trace("Inserted or updated " + numUpdated + " rows"); + if (logger.isTraceEnabled()) { + logger.trace("Inserted or updated " + numUpdated + " rows"); } if (numUpdated > 0) count += stmtSize; @@ -145,7 +143,7 @@ public class VmRulesetLogDaoImpl extends GenericDaoBase im } } catch (SQLException sqe) { - s_logger.warn("Failed to execute multi insert ", sqe); + logger.warn("Failed to execute multi insert ", sqe); } return count; @@ -173,10 +171,10 @@ public class VmRulesetLogDaoImpl extends GenericDaoBase im queryResult = stmtInsert.executeBatch(); txn.commit(); - if (s_logger.isTraceEnabled()) - s_logger.trace("Updated or inserted " + workItems.size() + " log items"); + if (logger.isTraceEnabled()) + logger.trace("Updated or inserted " + workItems.size() + " log items"); } catch (SQLException e) { - s_logger.warn("Failed to execute batch update statement for ruleset log: ", e); + logger.warn("Failed to execute batch update statement for ruleset log: ", e); txn.rollback(); success = false; } @@ -185,7 +183,7 @@ public class VmRulesetLogDaoImpl extends GenericDaoBase im workItems.toArray(arrayItems); for (int i = 0; i < queryResult.length; i++) { if (queryResult[i] < 0) { - s_logger.debug("Batch query update failed for vm " + arrayItems[i]); + logger.debug("Batch query update failed for vm " + arrayItems[i]); } } } diff --git a/engine/schema/src/main/java/com/cloud/network/vpc/NetworkACLItemVO.java b/engine/schema/src/main/java/com/cloud/network/vpc/NetworkACLItemVO.java index f28b3125a09..4333d35d473 100644 --- a/engine/schema/src/main/java/com/cloud/network/vpc/NetworkACLItemVO.java +++ b/engine/schema/src/main/java/com/cloud/network/vpc/NetworkACLItemVO.java @@ -35,6 +35,7 @@ import javax.persistence.Transient; import com.cloud.utils.db.GenericDao; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "network_acl_item") @@ -168,7 +169,9 @@ public class NetworkACLItemVO implements NetworkACLItem, Cloneable { @Override public String toString() { - return new StringBuilder("Rule[").append(id).append("-").append("NetworkACL").append("-").append(state).append("]").toString(); + return String.format("NetworkACLItem %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "aclId", "state")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/vpc/NetworkACLVO.java b/engine/schema/src/main/java/com/cloud/network/vpc/NetworkACLVO.java index 280d5dfaf4b..37b9e7ff296 100644 --- a/engine/schema/src/main/java/com/cloud/network/vpc/NetworkACLVO.java +++ b/engine/schema/src/main/java/com/cloud/network/vpc/NetworkACLVO.java @@ -89,7 +89,7 @@ public class NetworkACLVO implements NetworkACL { @Override public String toString() { - return ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "uuid", "name", "vpcId"); + return ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "uuid", "name", "vpcId"); } public void setUuid(String uuid) { diff --git a/engine/schema/src/main/java/com/cloud/network/vpc/VpcGatewayVO.java b/engine/schema/src/main/java/com/cloud/network/vpc/VpcGatewayVO.java index 72f6a89e70f..b1d4df35d4c 100644 --- a/engine/schema/src/main/java/com/cloud/network/vpc/VpcGatewayVO.java +++ b/engine/schema/src/main/java/com/cloud/network/vpc/VpcGatewayVO.java @@ -29,6 +29,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "vpc_gateways") @@ -163,9 +164,9 @@ public class VpcGatewayVO implements VpcGateway { @Override public String toString() { - StringBuilder buf = new StringBuilder("VpcGateway["); - buf.append(id).append("|").append(ip4Address.toString()).append("|").append(vpcId).append("]"); - return buf.toString(); + return String.format("VpcGateway %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "vpcId", "ip4Address")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/vpc/VpcOfferingVO.java b/engine/schema/src/main/java/com/cloud/network/vpc/VpcOfferingVO.java index aa26f16568a..274b9fedecc 100644 --- a/engine/schema/src/main/java/com/cloud/network/vpc/VpcOfferingVO.java +++ b/engine/schema/src/main/java/com/cloud/network/vpc/VpcOfferingVO.java @@ -28,7 +28,9 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import com.cloud.offering.NetworkOffering; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "vpc_offerings") @@ -58,6 +60,12 @@ public class VpcOfferingVO implements VpcOffering { @Column(name = "default") boolean isDefault = false; + @Column(name = "for_nsx") + boolean forNsx = false; + + @Column(name = "network_mode") + NetworkOffering.NetworkMode networkMode; + @Column(name = GenericDao.REMOVED_COLUMN) Date removed; @@ -79,6 +87,13 @@ public class VpcOfferingVO implements VpcOffering { @Column(name = "sort_key") int sortKey; + @Column(name="routing_mode") + @Enumerated(value = EnumType.STRING) + private NetworkOffering.RoutingMode routingMode; + + @Column(name = "specify_as_number") + private Boolean specifyAsNumber = false; + public VpcOfferingVO() { this.uuid = UUID.randomUUID().toString(); } @@ -144,14 +159,31 @@ public class VpcOfferingVO implements VpcOffering { return isDefault; } + public boolean isForNsx() { + return forNsx; + } + + public void setForNsx(boolean forNsx) { + this.forNsx = forNsx; + } + + public NetworkOffering.NetworkMode getNetworkMode() { + return networkMode; + } + + public void setNetworkMode(NetworkOffering.NetworkMode networkMode) { + this.networkMode = networkMode; + } + public void setUniqueName(String uniqueName) { this.uniqueName = uniqueName; } @Override public String toString() { - StringBuilder buf = new StringBuilder("[VPC Offering ["); - return buf.append(id).append("-").append(name).append("]").toString(); + return String.format("VPCOffering %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); } public void setName(String name) { @@ -204,4 +236,21 @@ public class VpcOfferingVO implements VpcOffering { return sortKey; } + @Override + public NetworkOffering.RoutingMode getRoutingMode() { + return routingMode; + } + + public void setRoutingMode(NetworkOffering.RoutingMode routingMode) { + this.routingMode = routingMode; + } + + @Override + public Boolean isSpecifyAsNumber() { + return specifyAsNumber; + } + + public void setSpecifyAsNumber(Boolean specifyAsNumber) { + this.specifyAsNumber = specifyAsNumber; + } } diff --git a/engine/schema/src/main/java/com/cloud/network/vpc/VpcVO.java b/engine/schema/src/main/java/com/cloud/network/vpc/VpcVO.java index c2024e06c51..e8ccc2ebcf1 100644 --- a/engine/schema/src/main/java/com/cloud/network/vpc/VpcVO.java +++ b/engine/schema/src/main/java/com/cloud/network/vpc/VpcVO.java @@ -28,6 +28,7 @@ import javax.persistence.Table; import javax.persistence.Transient; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "vpc") @@ -159,6 +160,10 @@ public class VpcVO implements Vpc { return cidr; } + public void setCidr(String cidr) { + this.cidr = cidr; + } + @Override public long getDomainId() { return domainId; @@ -206,8 +211,9 @@ public class VpcVO implements Vpc { @Override public String toString() { - final StringBuilder buf = new StringBuilder("[VPC ["); - return buf.append(id).append("-").append(name).append("]").toString(); + return String.format("VPC %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/vpc/dao/NetworkACLItemCidrsDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/vpc/dao/NetworkACLItemCidrsDaoImpl.java index 4501f1493b5..1eb6482dd3a 100644 --- a/engine/schema/src/main/java/com/cloud/network/vpc/dao/NetworkACLItemCidrsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/vpc/dao/NetworkACLItemCidrsDaoImpl.java @@ -21,7 +21,6 @@ package com.cloud.network.vpc.dao; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.network.vpc.NetworkACLItemCidrsDao; @@ -37,7 +36,6 @@ import com.cloud.utils.db.TransactionLegacy; */ @Component public class NetworkACLItemCidrsDaoImpl extends GenericDaoBase implements NetworkACLItemCidrsDao { - private static final Logger s_logger = Logger.getLogger(NetworkACLItemCidrsDaoImpl.class); protected final SearchBuilder cidrsSearch; protected NetworkACLItemCidrsDaoImpl() { diff --git a/engine/schema/src/main/java/com/cloud/network/vpc/dao/PrivateIpDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/vpc/dao/PrivateIpDaoImpl.java index 8b090fdfbc8..47b91b24c27 100644 --- a/engine/schema/src/main/java/com/cloud/network/vpc/dao/PrivateIpDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/vpc/dao/PrivateIpDaoImpl.java @@ -20,7 +20,6 @@ import java.util.Date; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.network.vpc.PrivateIpVO; @@ -36,7 +35,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component @DB() public class PrivateIpDaoImpl extends GenericDaoBase implements PrivateIpDao { - private static final Logger s_logger = Logger.getLogger(PrivateIpDaoImpl.class); private final SearchBuilder AllFieldsSearch; private final GenericSearchBuilder CountAllocatedByNetworkId; @@ -90,8 +88,8 @@ public class PrivateIpDaoImpl extends GenericDaoBase implemen @Override public void releaseIpAddress(String ipAddress, long networkId) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Releasing private ip address: " + ipAddress + " network id " + networkId); + if (logger.isDebugEnabled()) { + logger.debug("Releasing private ip address: " + ipAddress + " network id " + networkId); } SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("ip", ipAddress); diff --git a/engine/schema/src/main/java/com/cloud/network/vpc/dao/VpcOfferingDao.java b/engine/schema/src/main/java/com/cloud/network/vpc/dao/VpcOfferingDao.java index 264a1ebc75e..aa17723f0b1 100644 --- a/engine/schema/src/main/java/com/cloud/network/vpc/dao/VpcOfferingDao.java +++ b/engine/schema/src/main/java/com/cloud/network/vpc/dao/VpcOfferingDao.java @@ -33,4 +33,6 @@ public interface VpcOfferingDao extends GenericDao { NetUtils.InternetProtocol getVpcOfferingInternetProtocol(long offeringId); boolean isIpv6Supported(long offeringId); + + boolean isRoutedVpc(long offeringId); } diff --git a/engine/schema/src/main/java/com/cloud/network/vpc/dao/VpcOfferingDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/vpc/dao/VpcOfferingDaoImpl.java index 1cc6a21da76..b83fd891305 100644 --- a/engine/schema/src/main/java/com/cloud/network/vpc/dao/VpcOfferingDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/vpc/dao/VpcOfferingDaoImpl.java @@ -19,6 +19,7 @@ package com.cloud.network.vpc.dao; import javax.inject.Inject; +import com.cloud.offering.NetworkOffering; import org.apache.cloudstack.api.ApiConstants; import org.springframework.stereotype.Component; @@ -84,4 +85,9 @@ public class VpcOfferingDaoImpl extends GenericDaoBase impl NetUtils.InternetProtocol internetProtocol = getVpcOfferingInternetProtocol(offeringId); return NetUtils.InternetProtocol.isIpv6EnabledProtocol(internetProtocol); } + + @Override + public boolean isRoutedVpc(long offeringId) { + return NetworkOffering.NetworkMode.ROUTED.equals(findById(offeringId).getNetworkMode()); + } } diff --git a/engine/schema/src/main/java/com/cloud/offerings/NetworkOfferingVO.java b/engine/schema/src/main/java/com/cloud/offerings/NetworkOfferingVO.java index ae5e6fb95ea..5cad366945f 100644 --- a/engine/schema/src/main/java/com/cloud/offerings/NetworkOfferingVO.java +++ b/engine/schema/src/main/java/com/cloud/offerings/NetworkOfferingVO.java @@ -32,6 +32,7 @@ import com.cloud.network.Network; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "network_offerings") @@ -136,6 +137,12 @@ public class NetworkOfferingVO implements NetworkOffering { @Column(name = "for_tungsten") boolean forTungsten = false; + @Column(name = "for_nsx") + boolean forNsx = false; + + @Column(name = "network_mode") + NetworkMode networkMode; + @Column(name = "egress_default_policy") boolean egressdefaultpolicy; @@ -168,6 +175,13 @@ public class NetworkOfferingVO implements NetworkOffering { @Column(name="service_package_id") String servicePackageUuid = null; + @Column(name="routing_mode") + @Enumerated(value = EnumType.STRING) + private RoutingMode routingMode; + + @Column(name = "specify_as_number") + private Boolean specifyAsNumber = false; + @Override public boolean isKeepAliveEnabled() { return keepAliveEnabled; @@ -195,6 +209,24 @@ public class NetworkOfferingVO implements NetworkOffering { this.forTungsten = forTungsten; } + @Override + public boolean isForNsx() { + return forNsx; + } + + public void setForNsx(boolean forNsx) { + this.forNsx = forNsx; + } + + @Override + public NetworkMode getNetworkMode() { + return networkMode; + } + + public void setNetworkMode(NetworkMode networkMode) { + this.networkMode = networkMode; + } + @Override public long getId() { return id; @@ -440,8 +472,8 @@ public class NetworkOfferingVO implements NetworkOffering { @Override public String toString() { - StringBuilder buf = new StringBuilder("[Network Offering ["); - return buf.append(id).append("-").append(trafficType).append("-").append(name).append("]").toString(); + return String.format("NetworkOffering %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "trafficType")); } @Override @@ -558,4 +590,21 @@ public class NetworkOfferingVO implements NetworkOffering { public boolean isSupportsVmAutoScaling() { return supportsVmAutoScaling; } + + @Override + public RoutingMode getRoutingMode() { + return routingMode; + } + + public void setRoutingMode(RoutingMode routingMode) { + this.routingMode = routingMode; + } + + public Boolean isSpecifyAsNumber() { + return specifyAsNumber; + } + + public void setSpecifyAsNumber(Boolean specifyAsNumber) { + this.specifyAsNumber = specifyAsNumber; + } } diff --git a/engine/schema/src/main/java/com/cloud/offerings/dao/NetworkOfferingDao.java b/engine/schema/src/main/java/com/cloud/offerings/dao/NetworkOfferingDao.java index 381d2144df1..abb63a10d06 100644 --- a/engine/schema/src/main/java/com/cloud/offerings/dao/NetworkOfferingDao.java +++ b/engine/schema/src/main/java/com/cloud/offerings/dao/NetworkOfferingDao.java @@ -76,4 +76,6 @@ public interface NetworkOfferingDao extends GenericDao NetUtils.InternetProtocol getNetworkOfferingInternetProtocol(long offeringId, NetUtils.InternetProtocol defaultProtocol); boolean isIpv6Supported(long offeringId); + + boolean isRoutedNetwork(long offeringId); } diff --git a/engine/schema/src/main/java/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java b/engine/schema/src/main/java/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java index 823ea36b97f..9bc74b13932 100644 --- a/engine/schema/src/main/java/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/offerings/dao/NetworkOfferingDaoImpl.java @@ -292,4 +292,9 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase ProjectAccountsSearch; final GenericSearchBuilder CountByRoleSearch; - public static final Logger s_logger = Logger.getLogger(ProjectAccountDaoImpl.class.getName()); protected ProjectAccountDaoImpl() { AllFieldsSearch = createSearchBuilder(); @@ -190,7 +188,7 @@ public class ProjectAccountDaoImpl extends GenericDaoBase 0) { - s_logger.debug("Removed account id=" + accountId + " from " + rowsRemoved + " projects"); + logger.debug("Removed account id=" + accountId + " from " + rowsRemoved + " projects"); } } @@ -201,7 +199,7 @@ public class ProjectAccountDaoImpl extends GenericDaoBase 0) { - s_logger.debug(String.format("Removed user [%s] from %s project(s).", userId, removedCount)); + logger.debug(String.format("Removed user [%s] from %s project(s).", userId, removedCount)); } } diff --git a/engine/schema/src/main/java/com/cloud/projects/dao/ProjectDaoImpl.java b/engine/schema/src/main/java/com/cloud/projects/dao/ProjectDaoImpl.java index 5deb8586120..46bf36ae397 100644 --- a/engine/schema/src/main/java/com/cloud/projects/dao/ProjectDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/projects/dao/ProjectDaoImpl.java @@ -20,7 +20,6 @@ import java.util.List; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.projects.Project; @@ -36,7 +35,6 @@ import com.cloud.utils.db.SearchCriteria.Func; @Component public class ProjectDaoImpl extends GenericDaoBase implements ProjectDao { - private static final Logger s_logger = Logger.getLogger(ProjectDaoImpl.class); protected final SearchBuilder AllFieldsSearch; protected GenericSearchBuilder CountByDomain; protected GenericSearchBuilder ProjectAccountSearch; diff --git a/engine/schema/src/main/java/com/cloud/projects/dao/ProjectInvitationDaoImpl.java b/engine/schema/src/main/java/com/cloud/projects/dao/ProjectInvitationDaoImpl.java index f8d153740ab..d30b1c9f1f1 100644 --- a/engine/schema/src/main/java/com/cloud/projects/dao/ProjectInvitationDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/projects/dao/ProjectInvitationDaoImpl.java @@ -19,7 +19,6 @@ package com.cloud.projects.dao; import java.sql.Date; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.projects.ProjectInvitation.State; @@ -31,7 +30,6 @@ import com.cloud.utils.db.SearchCriteria; @Component public class ProjectInvitationDaoImpl extends GenericDaoBase implements ProjectInvitationDao { - private static final Logger s_logger = Logger.getLogger(ProjectInvitationDaoImpl.class); protected final SearchBuilder AllFieldsSearch; protected final SearchBuilder InactiveSearch; protected final SearchBuilder ProjectAccountInviteSearch; @@ -111,7 +109,7 @@ public class ProjectInvitationDaoImpl extends GenericDaoBase copyCmds = customSearch(sc, null); - return copyCmds.size(); + return getCount(sc); + } + + @Override + public int expungeByVmList(List vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getInstanceId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + return batchExpunge(sc, batchSize); } } diff --git a/engine/schema/src/main/java/com/cloud/service/dao/ServiceOfferingDao.java b/engine/schema/src/main/java/com/cloud/service/dao/ServiceOfferingDao.java index 3b6fa8fa103..ceb5b0a4fc1 100644 --- a/engine/schema/src/main/java/com/cloud/service/dao/ServiceOfferingDao.java +++ b/engine/schema/src/main/java/com/cloud/service/dao/ServiceOfferingDao.java @@ -55,4 +55,6 @@ public interface ServiceOfferingDao extends GenericDao List listPublicByCpuAndMemory(Integer cpus, Integer memory); ServiceOfferingVO findServiceOfferingByComputeOnlyDiskOffering(long diskOfferingId, boolean includingRemoved); + + List listIdsByHostTag(String tag); } diff --git a/engine/schema/src/main/java/com/cloud/service/dao/ServiceOfferingDaoImpl.java b/engine/schema/src/main/java/com/cloud/service/dao/ServiceOfferingDaoImpl.java index ef6d4e71989..803522fa6aa 100644 --- a/engine/schema/src/main/java/com/cloud/service/dao/ServiceOfferingDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/service/dao/ServiceOfferingDaoImpl.java @@ -26,7 +26,6 @@ import javax.persistence.EntityExistsException; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.dao.DiskOfferingDao; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.event.UsageEventVO; @@ -35,6 +34,7 @@ import com.cloud.service.ServiceOfferingVO; import com.cloud.storage.Storage.ProvisioningType; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.exception.CloudRuntimeException; @@ -44,7 +44,6 @@ import com.cloud.vm.dao.UserVmDetailsDao; @Component @DB() public class ServiceOfferingDaoImpl extends GenericDaoBase implements ServiceOfferingDao { - protected static final Logger s_logger = Logger.getLogger(ServiceOfferingDaoImpl.class); @Inject protected ServiceOfferingDetailsDao detailsDao; @@ -268,7 +267,7 @@ public class ServiceOfferingDaoImpl extends GenericDaoBase listIdsByHostTag(String tag) { + GenericSearchBuilder sb = createSearchBuilder(Long.class); + sb.selectFields(sb.entity().getId()); + sb.and("tagNotNull", sb.entity().getHostTag(), SearchCriteria.Op.NNULL); + sb.and().op("tagEq", sb.entity().getHostTag(), SearchCriteria.Op.EQ); + sb.or("tagStartLike", sb.entity().getHostTag(), SearchCriteria.Op.LIKE); + sb.or("tagMidLike", sb.entity().getHostTag(), SearchCriteria.Op.LIKE); + sb.or("tagEndLike", sb.entity().getHostTag(), SearchCriteria.Op.LIKE); + sb.cp(); + sb.done(); + SearchCriteria sc = sb.create(); + + sc.setParameters("tagEq", tag); + sc.setParameters("tagStartLike", tag + ",%"); + sc.setParameters("tagMidLike", "%," + tag + ",%"); + sc.setParameters("tagEndLike", "%," + tag); + return customSearch(sc, null); + } } diff --git a/engine/schema/src/main/java/com/cloud/storage/BucketVO.java b/engine/schema/src/main/java/com/cloud/storage/BucketVO.java index 181b02e5a1b..a54c1dd9b08 100644 --- a/engine/schema/src/main/java/com/cloud/storage/BucketVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/BucketVO.java @@ -19,8 +19,7 @@ package com.cloud.storage; import com.cloud.utils.db.GenericDao; import com.google.gson.annotations.Expose; import org.apache.cloudstack.storage.object.Bucket; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import javax.persistence.Column; import javax.persistence.Entity; @@ -97,17 +96,23 @@ public class BucketVO implements Bucket { String uuid; public BucketVO() { + this.uuid = UUID.randomUUID().toString(); + } + + public BucketVO(String name) { + this.uuid = UUID.randomUUID().toString(); + this.name = name; + this.state = State.Allocated; } public BucketVO(long accountId, long domainId, long objectStoreId, String name, Integer quota, boolean versioning, - boolean encryption, boolean objectLock, String policy) - { + boolean encryption, boolean objectLock, String policy) { this.accountId = accountId; this.domainId = domainId; this.objectStoreId = objectStoreId; this.name = name; - state = State.Allocated; - uuid = UUID.randomUUID().toString(); + this.state = State.Allocated; + this.uuid = UUID.randomUUID().toString(); this.quota = quota; this.versioning = versioning; this.encryption = encryption; @@ -251,7 +256,8 @@ public class BucketVO implements Bucket { @Override public String toString() { - return String.format("Bucket %s", new ToStringBuilder(this, ToStringStyle.JSON_STYLE).append("uuid", getUuid()).append("name", getName()) - .append("ObjectStoreId", getObjectStoreId()).toString()); + return String.format("Bucket %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "objectStoreId")); } } diff --git a/engine/schema/src/main/java/com/cloud/storage/DiskOfferingVO.java b/engine/schema/src/main/java/com/cloud/storage/DiskOfferingVO.java index b4f112f98e8..79f5bcb5157 100644 --- a/engine/schema/src/main/java/com/cloud/storage/DiskOfferingVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/DiskOfferingVO.java @@ -34,6 +34,7 @@ import javax.persistence.Transient; import com.cloud.offering.DiskOffering; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "disk_offering") @@ -588,4 +589,11 @@ public class DiskOfferingVO implements DiskOffering { public void setDiskSizeStrictness(boolean diskSizeStrictness) { this.diskSizeStrictness = diskSizeStrictness; } + + @Override + public String toString() { + return String.format("DiskOffering %s.", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); + } } diff --git a/engine/schema/src/main/java/com/cloud/storage/GuestOSHypervisorVO.java b/engine/schema/src/main/java/com/cloud/storage/GuestOSHypervisorVO.java index e900d28a864..cae1e1b7eee 100644 --- a/engine/schema/src/main/java/com/cloud/storage/GuestOSHypervisorVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/GuestOSHypervisorVO.java @@ -20,6 +20,7 @@ import java.util.Date; import java.util.UUID; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; @@ -28,6 +29,7 @@ import javax.persistence.Table; import com.cloud.hypervisor.Hypervisor; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.util.HypervisorTypeConverter; @Entity @Table(name = "guest_os_hypervisor") @@ -44,6 +46,7 @@ public class GuestOSHypervisorVO implements GuestOSHypervisor { String guestOsName; @Column(name = "hypervisor_type") + @Convert(converter = HypervisorTypeConverter.class) String hypervisorType; @Column(name = "hypervisor_version") diff --git a/engine/schema/src/main/java/com/cloud/storage/SnapshotPolicyVO.java b/engine/schema/src/main/java/com/cloud/storage/SnapshotPolicyVO.java index c7848586826..f57d9d3dccf 100644 --- a/engine/schema/src/main/java/com/cloud/storage/SnapshotPolicyVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/SnapshotPolicyVO.java @@ -27,6 +27,7 @@ import javax.persistence.Table; import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.utils.DateUtil.IntervalType; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "snapshot_policy") @@ -76,6 +77,13 @@ public class SnapshotPolicyVO implements SnapshotPolicy { this.uuid = UUID.randomUUID().toString(); } + @Override + public String toString() { + return String.format("SnapshotPolicy %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "volumeId")); + } + @Override public long getId() { return id; diff --git a/engine/schema/src/main/java/com/cloud/storage/SnapshotScheduleVO.java b/engine/schema/src/main/java/com/cloud/storage/SnapshotScheduleVO.java index 80a890aacad..5e013e76d3c 100644 --- a/engine/schema/src/main/java/com/cloud/storage/SnapshotScheduleVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/SnapshotScheduleVO.java @@ -29,6 +29,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.storage.snapshot.SnapshotSchedule; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "snapshot_schedule") @@ -71,6 +72,13 @@ public class SnapshotScheduleVO implements SnapshotSchedule { this.asyncJobId = null; } + @Override + public String toString() { + return String.format("SnapshotSchedule %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "volumeId", "policyId")); + } + @Override public long getId() { return id; diff --git a/engine/schema/src/main/java/com/cloud/storage/SnapshotVO.java b/engine/schema/src/main/java/com/cloud/storage/SnapshotVO.java index e9d6df85c2f..19c67a91e2c 100644 --- a/engine/schema/src/main/java/com/cloud/storage/SnapshotVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/SnapshotVO.java @@ -20,6 +20,7 @@ import java.util.Date; import java.util.UUID; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; @@ -28,12 +29,12 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.cloudstack.util.HypervisorTypeConverter; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.db.GenericDao; import com.google.gson.annotations.Expose; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "snapshots") @@ -89,7 +90,7 @@ public class SnapshotVO implements Snapshot { Date removed; @Column(name = "hypervisor_type") - @Enumerated(value = EnumType.STRING) + @Convert(converter = HypervisorTypeConverter.class) HypervisorType hypervisorType; @Expose @@ -281,7 +282,8 @@ public class SnapshotVO implements Snapshot { @Override public String toString() { - return String.format("Snapshot %s", new ToStringBuilder(this, ToStringStyle.JSON_STYLE).append("uuid", getUuid()).append("name", getName()) - .append("volumeId", getVolumeId()).toString()); + return String.format("Snapshot %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "volumeId", "version")); } } diff --git a/engine/schema/src/main/java/com/cloud/storage/VMTemplateVO.java b/engine/schema/src/main/java/com/cloud/storage/VMTemplateVO.java index 44e4dc920ab..10d08601515 100644 --- a/engine/schema/src/main/java/com/cloud/storage/VMTemplateVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/VMTemplateVO.java @@ -21,6 +21,7 @@ import java.util.Map; import java.util.UUID; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; @@ -31,7 +32,10 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; +import com.cloud.cpu.CPU; import com.cloud.user.UserData; +import org.apache.cloudstack.util.CPUArchConverter; +import org.apache.cloudstack.util.HypervisorTypeConverter; import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import com.cloud.hypervisor.Hypervisor.HypervisorType; @@ -108,7 +112,7 @@ public class VMTemplateVO implements VirtualMachineTemplate { private boolean crossZones = false; @Column(name = "hypervisor_type") - @Enumerated(value = EnumType.STRING) + @Convert(converter = HypervisorTypeConverter.class) private HypervisorType hypervisorType; @Column(name = "extractable") @@ -165,6 +169,10 @@ public class VMTemplateVO implements VirtualMachineTemplate { @Enumerated(value = EnumType.STRING) UserData.UserDataOverridePolicy userDataLinkPolicy; + @Column(name = "arch") + @Convert(converter = CPUArchConverter.class) + private CPU.CPUArch arch; + @Override public String getUniqueName() { return uniqueName; @@ -207,7 +215,7 @@ public class VMTemplateVO implements VirtualMachineTemplate { public VMTemplateVO(long id, String name, ImageFormat format, boolean isPublic, boolean featured, boolean isExtractable, TemplateType type, String url, boolean requiresHvm, int bits, long accountId, String cksum, String displayText, boolean enablePassword, long guestOSId, boolean bootable, HypervisorType hyperType, String templateTag, Map details, boolean sshKeyEnabled, boolean isDynamicallyScalable, boolean directDownload, - boolean deployAsIs) { + boolean deployAsIs, CPU.CPUArch arch) { this(id, name, format, @@ -233,6 +241,7 @@ public class VMTemplateVO implements VirtualMachineTemplate { state = State.Active; this.directDownload = directDownload; this.deployAsIs = deployAsIs; + this.arch = arch; } public static VMTemplateVO createPreHostIso(Long id, String uniqueName, String name, ImageFormat format, boolean isPublic, boolean featured, TemplateType type, @@ -563,7 +572,9 @@ public class VMTemplateVO implements VirtualMachineTemplate { @Override public String toString() { - return String.format("Template %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "uniqueName", "format")); + return String.format("Template %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "uniqueName", "format")); } public void setRemoved(Date removed) { @@ -671,4 +682,13 @@ public class VMTemplateVO implements VirtualMachineTemplate { this.userDataLinkPolicy = userDataLinkPolicy; } + @Override + public CPU.CPUArch getArch() { + return arch; + } + + public void setArch(CPU.CPUArch arch) { + this.arch = arch; + } + } diff --git a/engine/schema/src/main/java/com/cloud/storage/VolumeVO.java b/engine/schema/src/main/java/com/cloud/storage/VolumeVO.java index 5ccbf746b7e..653be54a910 100644 --- a/engine/schema/src/main/java/com/cloud/storage/VolumeVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/VolumeVO.java @@ -20,6 +20,7 @@ import java.util.Date; import java.util.UUID; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; @@ -32,6 +33,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; +import com.cloud.util.StoragePoolTypeConverter; import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import com.cloud.storage.Storage.ProvisioningType; @@ -46,34 +48,34 @@ public class VolumeVO implements Volume { @TableGenerator(name = "volume_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "volume_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.TABLE) @Column(name = "id") - long id; + private long id; @Column(name = "last_id") private long lastId; @Column(name = "name") - String name; + private String name; @Column(name = "pool_id") - Long poolId; + private Long poolId; @Column(name = "last_pool_id") - Long lastPoolId; + private Long lastPoolId; @Column(name = "account_id") - long accountId; + private long accountId; @Column(name = "domain_id") - long domainId; + private long domainId; @Column(name = "instance_id") - Long instanceId = null; + private Long instanceId = null; @Column(name = "device_id") - Long deviceId = null; + private Long deviceId = null; @Column(name = "size") - Long size; + private Long size; @Column(name = "min_iops") private Long minIops; @@ -82,50 +84,50 @@ public class VolumeVO implements Volume { private Long maxIops; @Column(name = "folder") - String folder; + private String folder; @Column(name = "path") - String path; + private String path; @Column(name = "pod_id") - Long podId; + private Long podId; @Column(name = "created") - Date created; + private Date created; @Column(name = "attached") @Temporal(value = TemporalType.TIMESTAMP) - Date attached; + private Date attached; @Column(name = "data_center_id") - long dataCenterId; + private long dataCenterId; @Column(name = "host_ip") - String hostip; + private String hostIp; @Column(name = "disk_offering_id") - long diskOfferingId; + private long diskOfferingId; @Column(name = "template_id") - Long templateId; + private Long templateId; @Column(name = "first_snapshot_backup_uuid") - String firstSnapshotBackupUuid; + private String firstSnapshotBackupUuid; @Column(name = "volume_type") @Enumerated(EnumType.STRING) - Type volumeType = Volume.Type.UNKNOWN; + private Type volumeType = Volume.Type.UNKNOWN; @Column(name = "pool_type") - @Enumerated(EnumType.STRING) - StoragePoolType poolType; + @Convert(converter = StoragePoolTypeConverter.class) + private StoragePoolType poolType; @Column(name = GenericDao.REMOVED_COLUMN) - Date removed; + private Date removed; @Column(name = "updated") @Temporal(value = TemporalType.TIMESTAMP) - Date updated; + private Date updated; @Column(name = "update_count", updatable = true, nullable = false) protected long updatedCount; // This field should be updated everytime the @@ -134,17 +136,17 @@ public class VolumeVO implements Volume { // dao code. @Column(name = "recreatable") - boolean recreatable; + private boolean recreatable; @Column(name = "state") @Enumerated(value = EnumType.STRING) private State state; @Column(name = "chain_info", length = 65535) - String chainInfo; + private String chainInfo; @Column(name = "uuid") - String uuid; + private String uuid; @Column(name = "format") private Storage.ImageFormat format; @@ -169,7 +171,7 @@ public class VolumeVO implements Volume { @Transient // @Column(name="reservation") - String reservationId; + private String reservationId; @Column(name = "hv_ss_reserve") private Integer hypervisorSnapshotReserve; @@ -183,6 +185,10 @@ public class VolumeVO implements Volume { @Column(name = "encrypt_format") private String encryptFormat; + @Column(name = "delete_protection") + private boolean deleteProtection; + + // Real Constructor public VolumeVO(Type type, String name, long dcId, long domainId, long accountId, long diskOfferingId, Storage.ProvisioningType provisioningType, long size, @@ -334,9 +340,7 @@ public class VolumeVO implements Volume { this.poolType = poolType; } - public StoragePoolType getPoolType() { - return poolType; - } + public StoragePoolType getPoolType() { return poolType; } @Override public long getDomainId() { @@ -427,11 +431,11 @@ public class VolumeVO implements Volume { } public String getHostIp() { - return hostip; + return hostIp; } public void setHostIp(String hostip) { - this.hostip = hostip; + this.hostIp = hostip; } public void setPodId(Long podId) { @@ -510,7 +514,9 @@ public class VolumeVO implements Volume { @Override public String toString() { - return new StringBuilder("Vol[").append(id).append("|name=").append(name).append("|vm=").append(instanceId).append("|").append(volumeType).append("]").toString(); + return String.format("Volume %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "volumeType", "instanceId")); } @Override @@ -681,6 +687,15 @@ public class VolumeVO implements Volume { public void setEncryptFormat(String encryptFormat) { this.encryptFormat = encryptFormat; } + @Override + public boolean isDeleteProtection() { + return deleteProtection; + } + + public void setDeleteProtection(boolean deleteProtection) { + this.deleteProtection = deleteProtection; + } + public long getLastId() { return lastId; } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/BucketDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/BucketDaoImpl.java index 83b5f6bdb74..98bef6201a1 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/BucketDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/BucketDaoImpl.java @@ -20,7 +20,6 @@ import com.cloud.storage.BucketVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import javax.naming.ConfigurationException; @@ -29,7 +28,6 @@ import java.util.Map; @Component public class BucketDaoImpl extends GenericDaoBase implements BucketDao { - public static final Logger s_logger = Logger.getLogger(BucketDaoImpl.class.getName()); private SearchBuilder searchFilteringStoreId; private SearchBuilder bucketSearch; diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDao.java b/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDao.java index 5a49d0b5192..f726bca3c5d 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDao.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDao.java @@ -31,5 +31,6 @@ public interface DiskOfferingDao extends GenericDao { List listAllBySizeAndProvisioningType(long size, Storage.ProvisioningType provisioningType); List findCustomDiskOfferings(); + List listByStorageTag(String tag); } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDaoImpl.java index d04353ec480..93e74766277 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDaoImpl.java @@ -146,4 +146,22 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im return update(id, diskOffering); } + + @Override + public List listByStorageTag(String tag) { + SearchBuilder sb = createSearchBuilder(); + sb.and("tagNotNull", sb.entity().getTags(), SearchCriteria.Op.NNULL); + sb.and().op("tagEq", sb.entity().getTags(), SearchCriteria.Op.EQ); + sb.or("tagStartLike", sb.entity().getTags(), SearchCriteria.Op.LIKE); + sb.or("tagMidLike", sb.entity().getTags(), SearchCriteria.Op.LIKE); + sb.or("tagEndLike", sb.entity().getTags(), SearchCriteria.Op.LIKE); + sb.cp(); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("tagEq", tag); + sc.setParameters("tagStartLike", tag + ",%"); + sc.setParameters("tagMidLike", "%," + tag + ",%"); + sc.setParameters("tagEndLike", "%," + tag); + return listBy(sc); + } } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/GuestOSHypervisorDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/GuestOSHypervisorDaoImpl.java index 69f4d4a3ceb..1aaa277a358 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/GuestOSHypervisorDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/GuestOSHypervisorDaoImpl.java @@ -22,7 +22,6 @@ import java.util.List; import org.apache.cloudstack.utils.CloudStackVersion; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.hypervisor.Hypervisor; @@ -35,7 +34,6 @@ import com.cloud.utils.db.SearchCriteria; @Component public class GuestOSHypervisorDaoImpl extends GenericDaoBase implements GuestOSHypervisorDao { - private static final Logger s_logger = Logger.getLogger(GuestOSHypervisorDaoImpl.class); protected final SearchBuilder guestOsSearch; protected final SearchBuilder mappingSearch; @@ -92,14 +90,14 @@ public class GuestOSHypervisorDaoImpl extends GenericDaoBase implements LaunchPermissionDao { - private static final Logger s_logger = Logger.getLogger(LaunchPermissionDaoImpl.class); private static final String REMOVE_LAUNCH_PERMISSION = "DELETE FROM `cloud`.`launch_permission`" + " WHERE template_id = ? AND account_id = ?"; private static final String LIST_PERMITTED_TEMPLATES = @@ -80,7 +78,7 @@ public class LaunchPermissionDaoImpl extends GenericDaoBase, StateDao listByIds(Object... ids); + List searchByVolumes(List volumeIds); } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotDaoImpl.java index f5ebf4bcf3d..f5fc9c47d03 100755 --- a/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotDaoImpl.java @@ -18,12 +18,13 @@ package com.cloud.storage.dao; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; -import org.apache.log4j.Logger; +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; import com.cloud.server.ResourceTag.ResourceObjectType; @@ -51,7 +52,6 @@ import com.cloud.vm.dao.VMInstanceDao; @Component public class SnapshotDaoImpl extends GenericDaoBase implements SnapshotDao { - public static final Logger s_logger = Logger.getLogger(SnapshotDaoImpl.class.getName()); // TODO: we should remove these direct sqls private static final String GET_LAST_SNAPSHOT = "SELECT snapshots.id FROM snapshot_store_ref, snapshots where snapshots.id = snapshot_store_ref.snapshot_id AND snapshosts.volume_id = ? AND snapshot_store_ref.role = ? ORDER BY created DESC"; @@ -197,7 +197,7 @@ public class SnapshotDaoImpl extends GenericDaoBase implements return rs.getLong(1); } } catch (Exception ex) { - s_logger.error("error getting last snapshot", ex); + logger.error("error getting last snapshot", ex); } return 0; } @@ -287,4 +287,16 @@ public class SnapshotDaoImpl extends GenericDaoBase implements sc.setParameters("status", (Object[]) status); return listBy(sc, null); } + + @Override + public List searchByVolumes(List volumeIds) { + if (CollectionUtils.isEmpty(volumeIds)) { + return new ArrayList<>(); + } + SearchBuilder sb = createSearchBuilder(); + sb.and("volumeIds", sb.entity().getVolumeId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("volumeIds", volumeIds.toArray()); + return search(sc, null); + } } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotScheduleDao.java b/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotScheduleDao.java index 7ca0a3915f5..284a42cf9e1 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotScheduleDao.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotScheduleDao.java @@ -27,13 +27,11 @@ import com.cloud.utils.db.GenericDao; */ public interface SnapshotScheduleDao extends GenericDao { - List getCoincidingSnapshotSchedules(long volumeId, Date date); - List getSchedulesToExecute(Date currentTimestamp); - SnapshotScheduleVO getCurrentSchedule(Long volumeId, Long policyId, boolean executing); + List getSchedulesAssignedWithAsyncJob(); - SnapshotScheduleVO findOneByVolume(long volumeId); + SnapshotScheduleVO getCurrentSchedule(Long volumeId, Long policyId, boolean executing); SnapshotScheduleVO findOneByVolumePolicy(long volumeId, long policyId); diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotScheduleDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotScheduleDaoImpl.java index 925d02dd90b..14669ce1d43 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotScheduleDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotScheduleDaoImpl.java @@ -32,7 +32,7 @@ import com.cloud.utils.db.SearchCriteria; public class SnapshotScheduleDaoImpl extends GenericDaoBase implements SnapshotScheduleDao { protected final SearchBuilder executableSchedulesSearch; protected final SearchBuilder coincidingSchedulesSearch; - private final SearchBuilder VolumeIdSearch; + protected final SearchBuilder schedulesAssignedWithAsyncJob; private final SearchBuilder VolumeIdPolicyIdSearch; protected SnapshotScheduleDaoImpl() { @@ -48,36 +48,14 @@ public class SnapshotScheduleDaoImpl extends GenericDaoBase getCoincidingSnapshotSchedules(long volumeId, Date date) { - SearchCriteria sc = coincidingSchedulesSearch.create(); - sc.setParameters("volumeId", volumeId); - sc.setParameters("scheduledTimestamp", date); - // Don't return manual snapshots. They will be executed through another - // code path. - sc.addAnd("policyId", SearchCriteria.Op.NEQ, 1L); - return listBy(sc); - } - - @Override - public SnapshotScheduleVO findOneByVolume(long volumeId) { - SearchCriteria sc = VolumeIdSearch.create(); - sc.setParameters("volumeId", volumeId); - return findOneBy(sc); + schedulesAssignedWithAsyncJob = createSearchBuilder(); + schedulesAssignedWithAsyncJob.and("asyncJobId", schedulesAssignedWithAsyncJob.entity().getAsyncJobId(), SearchCriteria.Op.NNULL); + schedulesAssignedWithAsyncJob.done(); } @Override @@ -98,6 +76,11 @@ public class SnapshotScheduleDaoImpl extends GenericDaoBase getSchedulesAssignedWithAsyncJob() { + return listBy(schedulesAssignedWithAsyncJob.create()); + } + /** * {@inheritDoc} */ diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotZoneDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotZoneDaoImpl.java index 1ed8a547a10..5f8ded6665b 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotZoneDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/SnapshotZoneDaoImpl.java @@ -20,7 +20,6 @@ package com.cloud.storage.dao; import java.util.Date; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.storage.SnapshotZoneVO; import com.cloud.utils.db.GenericDaoBase; @@ -28,7 +27,6 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; public class SnapshotZoneDaoImpl extends GenericDaoBase implements SnapshotZoneDao { - public static final Logger s_logger = Logger.getLogger(SnapshotZoneDaoImpl.class.getName()); protected final SearchBuilder ZoneSnapshotSearch; public SnapshotZoneDaoImpl() { diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolDetailsDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolDetailsDaoImpl.java index 559978ef284..2d9656b5b0a 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolDetailsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolDetailsDaoImpl.java @@ -17,6 +17,10 @@ package com.cloud.storage.dao; +import java.util.List; + +import javax.inject.Inject; + import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.ConfigKey.Scope; import org.apache.cloudstack.framework.config.ScopedConfigStorage; @@ -26,9 +30,6 @@ import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO; import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import javax.inject.Inject; -import java.util.List; - public class StoragePoolDetailsDaoImpl extends ResourceDetailsDaoBase implements StoragePoolDetailsDao, ScopedConfigStorage { @Inject @@ -43,8 +44,8 @@ public class StoragePoolDetailsDaoImpl extends ResourceDetailsDaoBase key) { - StoragePoolDetailVO vo = findDetail(id, key.key()); + public String getConfigValue(long id, String key) { + StoragePoolDetailVO vo = findDetail(id, key); return vo == null ? null : getActualValue(vo); } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolHostDao.java b/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolHostDao.java index 62ef5b7570d..639c2571541 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolHostDao.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolHostDao.java @@ -34,7 +34,7 @@ public interface StoragePoolHostDao extends GenericDao List findHostsConnectedToPools(List poolIds); - List> getDatacenterStoragePoolHostInfo(long dcId, boolean sharedOnly); + boolean hasDatacenterStoragePoolHostInfo(long dcId, boolean sharedOnly); public void deletePrimaryRecordsForHost(long hostId); diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolHostDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolHostDaoImpl.java index 03da0405142..5a466af348c 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolHostDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolHostDaoImpl.java @@ -26,7 +26,6 @@ import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.host.HostVO; @@ -42,7 +41,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class StoragePoolHostDaoImpl extends GenericDaoBase implements StoragePoolHostDao { - public static final Logger s_logger = Logger.getLogger(StoragePoolHostDaoImpl.class.getName()); protected final SearchBuilder PoolSearch; protected final SearchBuilder HostSearch; @@ -57,11 +55,11 @@ public class StoragePoolHostDaoImpl extends GenericDaoBase> getDatacenterStoragePoolHostInfo(long dcId, boolean sharedOnly) { - ArrayList> l = new ArrayList>(); + public boolean hasDatacenterStoragePoolHostInfo(long dcId, boolean sharedOnly) { + Long poolCount = 0L; String sql = sharedOnly ? SHARED_STORAGE_POOL_HOST_INFO : STORAGE_POOL_HOST_INFO; TransactionLegacy txn = TransactionLegacy.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql); + try (PreparedStatement pstmt = txn.prepareAutoCloseStatement(sql)) { pstmt.setLong(1, dcId); - ResultSet rs = pstmt.executeQuery(); while (rs.next()) { - l.add(new Pair(rs.getLong(1), rs.getInt(2))); + poolCount = rs.getLong(1); + if (poolCount > 0) { + return true; + } } } catch (SQLException e) { - s_logger.debug("SQLException: ", e); + logger.debug("SQLException: ", e); } - return l; + return false; } /** diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolTagsDao.java b/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolTagsDao.java index 9352ee21858..a4b87ef025f 100755 --- a/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolTagsDao.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolTagsDao.java @@ -34,5 +34,6 @@ public interface StoragePoolTagsDao extends GenericDao { StorageTagResponse newStorageTagResponse(StoragePoolTagVO tag); List findStoragePoolTags(long poolId); + List listPoolIdsByTag(String tag); } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolTagsDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolTagsDaoImpl.java index c01c66763af..c4d7ed88607 100755 --- a/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolTagsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/StoragePoolTagsDaoImpl.java @@ -18,12 +18,10 @@ package com.cloud.storage.dao; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; import javax.inject.Inject; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallbackNoReturn; -import com.cloud.utils.db.TransactionStatus; import org.apache.cloudstack.api.response.StorageTagResponse; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; @@ -31,7 +29,10 @@ import com.cloud.storage.StoragePoolTagVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.TransactionLegacy; +import com.cloud.utils.db.TransactionStatus; public class StoragePoolTagsDaoImpl extends GenericDaoBase implements StoragePoolTagsDao { @@ -178,4 +179,15 @@ public class StoragePoolTagsDaoImpl extends GenericDaoBase listPoolIdsByTag(String tag) { + SearchBuilder sb = createSearchBuilder(); + sb.and("tag", sb.entity().getTag(), SearchCriteria.Op.EQ); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("tag", tag); + List poolRefs = search(sc, null); + return poolRefs.stream().map(StoragePoolTagVO::getPoolId).collect(Collectors.toList()); + } + } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/UploadDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/UploadDaoImpl.java index fb296be4d35..8ee4a21a3c0 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/UploadDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/UploadDaoImpl.java @@ -19,7 +19,6 @@ package com.cloud.storage.dao; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.storage.Upload.Mode; @@ -31,7 +30,6 @@ import com.cloud.utils.db.SearchCriteria; @Component public class UploadDaoImpl extends GenericDaoBase implements UploadDao { - public static final Logger s_logger = Logger.getLogger(UploadDaoImpl.class.getName()); protected final SearchBuilder typeUploadStatusSearch; protected final SearchBuilder typeHostAndUploadStatusSearch; protected final SearchBuilder typeModeAndStatusSearch; diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateDao.java b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateDao.java index 708a77a8f9e..c751f81f927 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateDao.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateDao.java @@ -19,6 +19,7 @@ package com.cloud.storage.dao; import java.util.List; import java.util.Map; +import com.cloud.cpu.CPU; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.Storage; import com.cloud.storage.VMTemplateVO; @@ -67,13 +68,19 @@ public interface VMTemplateDao extends GenericDao, StateDao< public List userIsoSearch(boolean listRemoved); + List listAllReadySystemVMTemplates(Long zoneId); + VMTemplateVO findSystemVMTemplate(long zoneId); - VMTemplateVO findSystemVMReadyTemplate(long zoneId, HypervisorType hypervisorType); + VMTemplateVO findSystemVMReadyTemplate(long zoneId, HypervisorType hypervisorType, String preferredArch); + + List findSystemVMReadyTemplates(long zoneId, HypervisorType hypervisorType, String preferredArch); VMTemplateVO findRoutingTemplate(HypervisorType type, String templateName); - VMTemplateVO findLatestTemplateByTypeAndHypervisor(HypervisorType hypervisorType, Storage.TemplateType type); + List findRoutingTemplates(HypervisorType type, String templateName, String preferredArch); + + VMTemplateVO findLatestTemplateByTypeAndHypervisorAndArch(HypervisorType hypervisorType, CPU.CPUArch arch, Storage.TemplateType type); public Long countTemplatesForAccount(long accountId); @@ -85,9 +92,11 @@ public interface VMTemplateDao extends GenericDao, StateDao< List listByParentTemplatetId(long parentTemplatetId); - VMTemplateVO findLatestTemplateByName(String name); + VMTemplateVO findLatestTemplateByName(String name, CPU.CPUArch arch); List findTemplatesLinkedToUserdata(long userdataId); List listByIds(List ids); + + List listIdsByTemplateTag(String tag); } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateDaoImpl.java index 031bcb3af7b..b6796cf8f9d 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateDaoImpl.java @@ -18,9 +18,12 @@ package com.cloud.storage.dao; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import javax.inject.Inject; import javax.naming.ConfigurationException; @@ -28,9 +31,10 @@ import javax.naming.ConfigurationException; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; +import com.cloud.cpu.CPU; import com.cloud.dc.dao.DataCenterDao; import com.cloud.domain.dao.DomainDao; import com.cloud.host.Host; @@ -48,6 +52,7 @@ import com.cloud.storage.VMTemplateZoneVO; import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.template.VirtualMachineTemplate; +import com.cloud.utils.Pair; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; @@ -62,7 +67,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class VMTemplateDaoImpl extends GenericDaoBase implements VMTemplateDao { - private static final Logger s_logger = Logger.getLogger(VMTemplateDaoImpl.class); @Inject VMTemplateZoneDao _templateZoneDao; @@ -113,6 +117,7 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem LatestTemplateByHypervisorTypeSearch = createSearchBuilder(); LatestTemplateByHypervisorTypeSearch.and("hypervisorType", LatestTemplateByHypervisorTypeSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ); LatestTemplateByHypervisorTypeSearch.and("templateType", LatestTemplateByHypervisorTypeSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); + LatestTemplateByHypervisorTypeSearch.and("arch", LatestTemplateByHypervisorTypeSearch.entity().getArch(), SearchCriteria.Op.EQ); LatestTemplateByHypervisorTypeSearch.and("removed", LatestTemplateByHypervisorTypeSearch.entity().getRemoved(), SearchCriteria.Op.NULL); } @@ -240,10 +245,16 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem @Override - public VMTemplateVO findLatestTemplateByName(String name) { - SearchCriteria sc = createSearchCriteria(); - sc.addAnd("name", SearchCriteria.Op.EQ, name); - sc.addAnd("removed", SearchCriteria.Op.NULL); + public VMTemplateVO findLatestTemplateByName(String name, CPU.CPUArch arch) { + SearchBuilder sb = createSearchBuilder(); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); + sb.and("arch", sb.entity().getArch(), SearchCriteria.Op.EQ); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("name", name); + if (arch != null) { + sc.setParameters("arch", arch); + } Filter filter = new Filter(VMTemplateVO.class, "id", false, null, 1L); List templates = listBy(sc, filter); if ((templates != null) && !templates.isEmpty()) { @@ -293,7 +304,7 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem routerTmpltName = (String)params.get("routing.uniquename"); - s_logger.debug("Found parameter routing unique name " + routerTmpltName); + logger.debug("Found parameter routing unique name " + routerTmpltName); if (routerTmpltName == null) { routerTmpltName = "routing"; } @@ -302,8 +313,8 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem if (consoleProxyTmpltName == null) { consoleProxyTmpltName = "routing"; } - if (s_logger.isDebugEnabled()) { - s_logger.debug("Use console proxy template : " + consoleProxyTmpltName); + if (logger.isDebugEnabled()) { + logger.debug("Use console proxy template : " + consoleProxyTmpltName); } UniqueNameSearch = createSearchBuilder(); @@ -346,19 +357,12 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem readySystemTemplateSearch = createSearchBuilder(); readySystemTemplateSearch.and("state", readySystemTemplateSearch.entity().getState(), SearchCriteria.Op.EQ); readySystemTemplateSearch.and("templateType", readySystemTemplateSearch.entity().getTemplateType(), SearchCriteria.Op.EQ); + readySystemTemplateSearch.and("hypervisorType", readySystemTemplateSearch.entity().getHypervisorType(), SearchCriteria.Op.IN); SearchBuilder templateDownloadSearch = _templateDataStoreDao.createSearchBuilder(); templateDownloadSearch.and("downloadState", templateDownloadSearch.entity().getDownloadState(), SearchCriteria.Op.IN); readySystemTemplateSearch.join("vmTemplateJoinTemplateStoreRef", templateDownloadSearch, templateDownloadSearch.entity().getTemplateId(), readySystemTemplateSearch.entity().getId(), JoinBuilder.JoinType.INNER); - SearchBuilder hostHyperSearch2 = _hostDao.createSearchBuilder(); - hostHyperSearch2.and("type", hostHyperSearch2.entity().getType(), SearchCriteria.Op.EQ); - hostHyperSearch2.and("zoneId", hostHyperSearch2.entity().getDataCenterId(), SearchCriteria.Op.EQ); - hostHyperSearch2.and("removed", hostHyperSearch2.entity().getRemoved(), SearchCriteria.Op.NULL); - hostHyperSearch2.groupBy(hostHyperSearch2.entity().getHypervisorType()); - - readySystemTemplateSearch.join("tmplHyper", hostHyperSearch2, hostHyperSearch2.entity().getHypervisorType(), readySystemTemplateSearch.entity() - .getHypervisorType(), JoinBuilder.JoinType.INNER); - hostHyperSearch2.done(); + readySystemTemplateSearch.groupBy(readySystemTemplateSearch.entity().getId()); readySystemTemplateSearch.done(); tmpltTypeHyperSearch2 = createSearchBuilder(); @@ -558,29 +562,96 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem } @Override - public VMTemplateVO findSystemVMReadyTemplate(long zoneId, HypervisorType hypervisorType) { + public List listAllReadySystemVMTemplates(Long zoneId) { + List availableHypervisors = _hostDao.listDistinctHypervisorTypes(zoneId); + if (CollectionUtils.isEmpty(availableHypervisors)) { + return Collections.emptyList(); + } SearchCriteria sc = readySystemTemplateSearch.create(); sc.setParameters("templateType", Storage.TemplateType.SYSTEM); sc.setParameters("state", VirtualMachineTemplate.State.Active); - sc.setJoinParameters("tmplHyper", "type", Host.Type.Routing); - sc.setJoinParameters("tmplHyper", "zoneId", zoneId); - sc.setJoinParameters("vmTemplateJoinTemplateStoreRef", "downloadState", new VMTemplateStorageResourceAssoc.Status[] {VMTemplateStorageResourceAssoc.Status.DOWNLOADED, VMTemplateStorageResourceAssoc.Status.BYPASSED}); - + sc.setParameters("hypervisorType", availableHypervisors.toArray()); + sc.setJoinParameters("vmTemplateJoinTemplateStoreRef", "downloadState", + List.of(VMTemplateStorageResourceAssoc.Status.DOWNLOADED, + VMTemplateStorageResourceAssoc.Status.BYPASSED).toArray()); // order by descending order of id - List tmplts = listBy(sc, new Filter(VMTemplateVO.class, "id", false, null, null)); - - if (tmplts.size() > 0) { - if (hypervisorType == HypervisorType.Any) { - return tmplts.get(0); - } - for (VMTemplateVO tmplt : tmplts) { - if (tmplt.getHypervisorType() == hypervisorType) { - return tmplt; - } - } + return listBy(sc, new Filter(VMTemplateVO.class, "id", false, null, null)); + } + @Override + public VMTemplateVO findSystemVMReadyTemplate(long zoneId, HypervisorType hypervisorType, String preferredArch) { + List templates = listAllReadySystemVMTemplates(zoneId); + if (CollectionUtils.isEmpty(templates)) { + return null; } - return null; + if (StringUtils.isNotBlank(preferredArch)) { + // Sort the templates by preferred architecture first + templates = templates.stream() + .sorted(Comparator.comparing( + x -> !x.getArch().getType().equalsIgnoreCase(preferredArch) + )) + .collect(Collectors.toList()); + } + if (hypervisorType == HypervisorType.Any) { + return templates.get(0); + } + return templates.stream() + .filter(t -> t.getHypervisorType() == hypervisorType) + .findFirst() + .orElse(null); + } + + protected List getSortedTemplatesListWithPreferredArch( + Map, VMTemplateVO> uniqueTemplates, String preferredArch) { + List result = new ArrayList<>(uniqueTemplates.values()); + if (StringUtils.isNotBlank(preferredArch)) { + result.sort((t1, t2) -> { + boolean t1Preferred = t1.getArch().getType().equalsIgnoreCase(preferredArch); + boolean t2Preferred = t2.getArch().getType().equalsIgnoreCase(preferredArch); + if (t1Preferred && !t2Preferred) { + return -1; // t1 comes before t2 + } else if (!t1Preferred && t2Preferred) { + return 1; // t2 comes before t1 + } else { + // Both are either preferred or not preferred; use template id as a secondary sorting key. + return Long.compare(t1.getId(), t2.getId()); + } + }); + } else { + result.sort(Comparator.comparing(VMTemplateVO::getId).reversed()); + } + return result; + } + + @Override + public List findSystemVMReadyTemplates(long zoneId, HypervisorType hypervisorType, + String preferredArch) { + List> availableHypervisors = _hostDao.listDistinctHypervisorArchTypes(zoneId); + if (CollectionUtils.isEmpty(availableHypervisors)) { + return Collections.emptyList(); + } + SearchCriteria sc = readySystemTemplateSearch.create(); + sc.setParameters("templateType", Storage.TemplateType.SYSTEM); + sc.setParameters("state", VirtualMachineTemplate.State.Active); + if (hypervisorType != null && !HypervisorType.Any.equals(hypervisorType)) { + sc.setParameters("hypervisorType", List.of(hypervisorType).toArray()); + } else { + sc.setParameters("hypervisorType", + availableHypervisors.stream().map(Pair::first).distinct().toArray()); + } + sc.setJoinParameters("vmTemplateJoinTemplateStoreRef", "downloadState", + List.of(VMTemplateStorageResourceAssoc.Status.DOWNLOADED, + VMTemplateStorageResourceAssoc.Status.BYPASSED).toArray()); + // order by descending order of id + List templates = listBy(sc, new Filter(VMTemplateVO.class, "id", false, null, null)); + Map, VMTemplateVO> uniqueTemplates = new HashMap<>(); + for (VMTemplateVO template : templates) { + Pair key = new Pair<>(template.getHypervisorType(), template.getArch()); + if (availableHypervisors.contains(key) && !uniqueTemplates.containsKey(key)) { + uniqueTemplates.put(key, template); + } + } + return getSortedTemplatesListWithPreferredArch(uniqueTemplates, preferredArch); } @Override @@ -621,10 +692,43 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem } @Override - public VMTemplateVO findLatestTemplateByTypeAndHypervisor(HypervisorType hypervisorType, TemplateType type) { + public List findRoutingTemplates(HypervisorType hType, String templateName, String preferredArch) { + SearchCriteria sc = tmpltTypeHyperSearch2.create(); + sc.setParameters("templateType", TemplateType.ROUTING); + sc.setParameters("hypervisorType", hType); + sc.setParameters("state", VirtualMachineTemplate.State.Active.toString()); + if (templateName != null) { + sc.setParameters("templateName", templateName); + } + List templates = listBy(sc, new Filter(VMTemplateVO.class, "id", false, null, 1L)); + if (CollectionUtils.isEmpty(templates)) { + sc = tmpltTypeHyperSearch2.create(); + sc.setParameters("templateType", TemplateType.SYSTEM); + sc.setParameters("hypervisorType", hType); + sc.setParameters("state", VirtualMachineTemplate.State.Active.toString()); + if (templateName != null) { + sc.setParameters("templateName", templateName); + } + templates = listBy(sc, new Filter(VMTemplateVO.class, "id", false, null, 1L)); + } + Map, VMTemplateVO> uniqueTemplates = new HashMap<>(); + for (VMTemplateVO template : templates) { + Pair key = new Pair<>(template.getHypervisorType(), template.getArch()); + if (!uniqueTemplates.containsKey(key)) { + uniqueTemplates.put(key, template); + } + } + return getSortedTemplatesListWithPreferredArch(uniqueTemplates, preferredArch); + } + + @Override + public VMTemplateVO findLatestTemplateByTypeAndHypervisorAndArch(HypervisorType hypervisorType, CPU.CPUArch arch, TemplateType type) { SearchCriteria sc = LatestTemplateByHypervisorTypeSearch.create(); sc.setParameters("hypervisorType", hypervisorType); sc.setParameters("templateType", type); + if (arch != null) { + sc.setParameters("arch", arch); + } Filter filter = new Filter(VMTemplateVO.class, "id", false, null, 1L); List templates = listBy(sc, filter); if (templates != null && !templates.isEmpty()) { @@ -688,6 +792,17 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem return result; } + @Override + public List listIdsByTemplateTag(String tag) { + GenericSearchBuilder sb = createSearchBuilder(Long.class); + sb.selectFields(sb.entity().getId()); + sb.and("tag", sb.entity().getTemplateTag(), SearchCriteria.Op.EQ); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("tag", tag); + return customSearchIncludingRemoved(sc, null); + } + @Override public boolean updateState( com.cloud.template.VirtualMachineTemplate.State currentState, @@ -710,7 +825,7 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem builder.set(vo, "updated", new Date()); int rows = update((VMTemplateVO)vo, sc); - if (rows == 0 && s_logger.isDebugEnabled()) { + if (rows == 0 && logger.isDebugEnabled()) { VMTemplateVO dbTemplate = findByIdIncludingRemoved(vo.getId()); if (dbTemplate != null) { StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); @@ -743,7 +858,7 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem .append("; updatedTime=") .append(oldUpdatedTime); } else { - s_logger.debug("Unable to update template: id=" + vo.getId() + ", as no such template exists in the database anymore"); + logger.debug("Unable to update template: id=" + vo.getId() + ", as no such template exists in the database anymore"); } } return rows > 0; diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDao.java b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDao.java index a3ce03a74c3..a208590e23a 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDao.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDao.java @@ -35,6 +35,8 @@ public interface VMTemplatePoolDao extends GenericDao listByPoolIdAndState(long poolId, ObjectInDataStoreStateMachine.State state); + List listByPoolIdsAndTemplate(List poolIds, Long templateId); + List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState); List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState, long poolId); diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java index d938bebb18e..5dfc138d8e1 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java @@ -31,7 +31,6 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; @@ -49,7 +48,6 @@ import com.cloud.utils.db.UpdateBuilder; @Component public class VMTemplatePoolDaoImpl extends GenericDaoBase implements VMTemplatePoolDao { - public static final Logger s_logger = Logger.getLogger(VMTemplatePoolDaoImpl.class.getName()); @Inject DataStoreManager dataStoreManager; @@ -152,6 +150,16 @@ public class VMTemplatePoolDaoImpl extends GenericDaoBase listByPoolIdsAndTemplate(List poolIds, Long templateId) { + SearchCriteria sc = PoolTemplateSearch.create(); + if (CollectionUtils.isNotEmpty(poolIds)) { + sc.setParameters("pool_id", poolIds.toArray()); + } + sc.setParameters("template_id", templateId); + return listBy(sc); + } + @Override public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState) { SearchCriteria sc = TemplateStatusSearch.create(); @@ -193,7 +201,7 @@ public class VMTemplatePoolDaoImpl extends GenericDaoBase 0; diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java index 489ac130eaf..12835d184ea 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplateZoneDaoImpl.java @@ -19,7 +19,6 @@ package com.cloud.storage.dao; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.storage.VMTemplateZoneVO; @@ -30,7 +29,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class VMTemplateZoneDaoImpl extends GenericDaoBase implements VMTemplateZoneDao { - public static final Logger s_logger = Logger.getLogger(VMTemplateZoneDaoImpl.class.getName()); protected final SearchBuilder ZoneSearch; protected final SearchBuilder TemplateSearch; diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDao.java b/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDao.java index 8e3bbf68dea..e6ffca06f9e 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDao.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDao.java @@ -157,5 +157,9 @@ public interface VolumeDao extends GenericDao, StateDao listByIds(List ids); + List listAllocatedVolumesForAccountDiskOfferingIdsAndNotForVms(long accountId, List diskOfferingIds, List vmIds); + + List searchRemovedByVms(List vmIds, Long batchSize); + VolumeVO findOneByIScsiName(String iScsiName); } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDaoImpl.java index 9907af76769..750dbf2bee0 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDaoImpl.java @@ -23,13 +23,16 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; +import java.util.stream.Collectors; import javax.inject.Inject; +import org.apache.cloudstack.reservation.ReservationVO; +import org.apache.cloudstack.reservation.dao.ReservationDao; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; +import com.cloud.configuration.Resource; import com.cloud.exception.InvalidParameterValueException; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.server.ResourceTag.ResourceObjectType; @@ -43,19 +46,21 @@ import com.cloud.storage.VolumeVO; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.utils.Pair; import com.cloud.utils.db.DB; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallback; import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.db.UpdateBuilder; import com.cloud.utils.exception.CloudRuntimeException; @Component public class VolumeDaoImpl extends GenericDaoBase implements VolumeDao { - private static final Logger s_logger = Logger.getLogger(VolumeDaoImpl.class); protected final SearchBuilder DetachedAccountIdSearch; protected final SearchBuilder TemplateZoneSearch; protected final GenericSearchBuilder TotalSizeByPoolSearch; @@ -73,6 +78,8 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol protected GenericSearchBuilder secondaryStorageSearch; private final SearchBuilder poolAndPathSearch; + @Inject + ReservationDao reservationDao; @Inject ResourceTagDao tagsDao; @@ -337,7 +344,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol } else if (scope == ScopeType.ZONE) { sql = SELECT_HYPERTYPE_FROM_ZONE_VOLUME; } else { - s_logger.error("Unhandled scope type '" + scope + "' when running getHypervisorType on volume id " + volumeId); + logger.error("Unhandled scope type '" + scope + "' when running getHypervisorType on volume id " + volumeId); } pstmt = txn.prepareAutoCloseStatement(sql); @@ -367,7 +374,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol } else if (type.equals(HypervisorType.VMware)) { return ImageFormat.OVA; } else { - s_logger.warn("Do not support hypervisor " + type.toString()); + logger.warn("Do not support hypervisor " + type.toString()); return null; } } @@ -446,6 +453,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN); CountByAccount.and("displayVolume", CountByAccount.entity().isDisplayVolume(), Op.EQ); + CountByAccount.and("idNIN", CountByAccount.entity().getId(), Op.NIN); CountByAccount.done(); primaryStorageSearch = createSearchBuilder(SumCount.class); @@ -457,6 +465,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol primaryStorageSearch.and("displayVolume", primaryStorageSearch.entity().isDisplayVolume(), Op.EQ); primaryStorageSearch.and("isRemoved", primaryStorageSearch.entity().getRemoved(), Op.NULL); primaryStorageSearch.and("NotCountStates", primaryStorageSearch.entity().getState(), Op.NIN); + primaryStorageSearch.and("idNIN", primaryStorageSearch.entity().getId(), Op.NIN); primaryStorageSearch.done(); primaryStorageSearch2 = createSearchBuilder(SumCount.class); @@ -471,6 +480,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol primaryStorageSearch2.and("displayVolume", primaryStorageSearch2.entity().isDisplayVolume(), Op.EQ); primaryStorageSearch2.and("isRemoved", primaryStorageSearch2.entity().getRemoved(), Op.NULL); primaryStorageSearch2.and("NotCountStates", primaryStorageSearch2.entity().getState(), Op.NIN); + primaryStorageSearch2.and("idNIN", primaryStorageSearch2.entity().getId(), Op.NIN); primaryStorageSearch2.done(); secondaryStorageSearch = createSearchBuilder(SumCount.class); @@ -508,15 +518,24 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol @Override public Long countAllocatedVolumesForAccount(long accountId) { + List reservations = reservationDao.getReservationsForAccount(accountId, Resource.ResourceType.volume, null); + List reservedResourceIds = reservations.stream().filter(reservation -> reservation.getReservedAmount() > 0).map(ReservationVO::getResourceId).collect(Collectors.toList()); + SearchCriteria sc = CountByAccount.create(); sc.setParameters("account", accountId); - sc.setParameters("state", Volume.State.Destroy, Volume.State.Expunged); + sc.setParameters("state", State.Destroy, State.Expunged); sc.setParameters("displayVolume", 1); + if (CollectionUtils.isNotEmpty(reservedResourceIds)) { + sc.setParameters("idNIN", reservedResourceIds.toArray()); + } return customSearch(sc, null).get(0); } @Override public long primaryStorageUsedForAccount(long accountId, List virtualRouters) { + List reservations = reservationDao.getReservationsForAccount(accountId, Resource.ResourceType.volume, null); + List reservedResourceIds = reservations.stream().filter(reservation -> reservation.getReservedAmount() > 0).map(ReservationVO::getResourceId).collect(Collectors.toList()); + SearchCriteria sc; if (!virtualRouters.isEmpty()) { sc = primaryStorageSearch2.create(); @@ -528,6 +547,9 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol sc.setParameters("states", State.Allocated); sc.setParameters("NotCountStates", State.Destroy, State.Expunged); sc.setParameters("displayVolume", 1); + if (CollectionUtils.isNotEmpty(reservedResourceIds)) { + sc.setParameters("idNIN", reservedResourceIds.toArray()); + } List storageSpace = customSearch(sc, null); if (storageSpace != null) { return storageSpace.get(0).sum; @@ -549,14 +571,6 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol } } - public static class SumCount { - public long sum; - public long count; - - public SumCount() { - } - } - @Override public List listVolumesToBeDestroyed() { SearchCriteria sc = AllFieldsSearch.create(); @@ -592,7 +606,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol builder.set(vo, "updated", new Date()); int rows = update((VolumeVO)vo, sc); - if (rows == 0 && s_logger.isDebugEnabled()) { + if (rows == 0 && logger.isDebugEnabled()) { VolumeVO dbVol = findByIdIncludingRemoved(vo.getId()); if (dbVol != null) { StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); @@ -603,7 +617,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated) .append("; updatedTime=").append(oldUpdatedTime); } else { - s_logger.debug("Unable to update volume: id=" + vo.getId() + ", as there is no such volume exists in the database anymore"); + logger.debug("Unable to update volume: id=" + vo.getId() + ", as there is no such volume exists in the database anymore"); } } return rows > 0; @@ -641,10 +655,10 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol } return result; } catch (SQLException e) { - s_logger.debug("DB Exception on: " + sql.toString(), e); + logger.debug("DB Exception on: " + sql.toString(), e); throw new CloudRuntimeException(e); } catch (Throwable e) { - s_logger.debug("Caught: " + sql.toString(), e); + logger.debug("Caught: " + sql.toString(), e); throw new CloudRuntimeException(e); } } @@ -716,7 +730,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol public boolean remove(Long id) { TransactionLegacy txn = TransactionLegacy.currentTxn(); txn.start(); - s_logger.debug(String.format("Removing volume %s from DB", id)); + logger.debug(String.format("Removing volume %s from DB", id)); VolumeVO entry = findById(id); if (entry != null) { tagsDao.removeByIdAndType(id, ResourceObjectType.Volume); @@ -842,6 +856,54 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol return listBy(sc, null); } + @Override + public List listAllocatedVolumesForAccountDiskOfferingIdsAndNotForVms(long accountId, List diskOfferingIds, List vmIds) { + SearchBuilder sb = createSearchBuilder(); + sb.and("account", sb.entity().getAccountId(), SearchCriteria.Op.EQ); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.NIN); + sb.and("diskOfferingIds", sb.entity().getDiskOfferingId(), SearchCriteria.Op.IN); + sb.and("displayVolume", sb.entity().isDisplayVolume(), Op.EQ); + if (CollectionUtils.isNotEmpty(vmIds)) { + sb.and().op("instanceId", sb.entity().getInstanceId(), Op.NULL); + sb.or("notVmIds", sb.entity().getInstanceId(), Op.NIN); + sb.cp(); + } + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("account", accountId); + sc.setParameters("state", Volume.State.Destroy, Volume.State.Expunged); + sc.setParameters("diskOfferingIds", diskOfferingIds.toArray()); + sc.setParameters("displayVolume", 1); + if (CollectionUtils.isNotEmpty(vmIds)) { + sc.setParameters("notVmIds", vmIds.toArray()); + } + return listBy(sc); + } + + @Override + public VolumeVO persist(VolumeVO entity) { + return Transaction.execute((TransactionCallback) status -> { + VolumeVO volume = super.persist(entity); + reservationDao.setResourceId(Resource.ResourceType.volume, volume.getId()); + reservationDao.setResourceId(Resource.ResourceType.primary_storage, volume.getId()); + return volume; + }); + } + + @Override + public List searchRemovedByVms(List vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return new ArrayList<>(); + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getInstanceId(), SearchCriteria.Op.IN); + sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.NNULL); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + Filter filter = new Filter(VolumeVO.class, "id", true, 0L, batchSize); + return searchIncludingRemoved(sc, filter, null, false); + } + public VolumeVO findOneByIScsiName(String iScsiName) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("iScsiName", iScsiName); diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VolumeStatsDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/VolumeStatsDaoImpl.java index 002310125af..e4c19fd1666 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VolumeStatsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VolumeStatsDaoImpl.java @@ -21,7 +21,8 @@ import java.util.List; import javax.annotation.PostConstruct; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.Filter; @@ -34,7 +35,7 @@ import com.cloud.storage.VolumeStatsVO; @Component public class VolumeStatsDaoImpl extends GenericDaoBase implements VolumeStatsDao { - protected Logger logger = Logger.getLogger(getClass()); + protected Logger logger = LogManager.getLogger(getClass()); protected SearchBuilder volumeIdSearch; protected SearchBuilder volumeIdTimestampGreaterThanEqualSearch; @@ -125,14 +126,7 @@ public class VolumeStatsDaoImpl extends GenericDaoBase impl logger.debug(String.format("Starting to remove all volume_stats rows older than [%s].", limitDate)); - long totalRemoved = 0; - long removed; - - do { - removed = expunge(sc, limitPerQuery); - totalRemoved += removed; - logger.trace(String.format("Removed [%s] volume_stats rows on the last update and a sum of [%s] volume_stats rows older than [%s] until now.", removed, totalRemoved, limitDate)); - } while (limitPerQuery > 0 && removed >= limitPerQuery); + long totalRemoved = batchExpunge(sc, limitPerQuery); logger.info(String.format("Removed a total of [%s] volume_stats rows older than [%s].", totalRemoved, limitDate)); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/ConfigurationGroupsAggregator.java b/engine/schema/src/main/java/com/cloud/upgrade/ConfigurationGroupsAggregator.java index 34de1bccb82..03857137ded 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/ConfigurationGroupsAggregator.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/ConfigurationGroupsAggregator.java @@ -30,13 +30,14 @@ import org.apache.cloudstack.framework.config.impl.ConfigurationSubGroupVO; import org.apache.cloudstack.framework.config.impl.ConfigurationVO; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.utils.Pair; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class ConfigurationGroupsAggregator { - static final Logger LOG = Logger.getLogger(ConfigurationGroupsAggregator.class); + protected Logger LOG = LogManager.getLogger(getClass()); @Inject ConfigurationDao configDao; diff --git a/engine/schema/src/main/java/com/cloud/upgrade/DatabaseCreator.java b/engine/schema/src/main/java/com/cloud/upgrade/DatabaseCreator.java index 154a8d11887..384826227af 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/DatabaseCreator.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/DatabaseCreator.java @@ -116,10 +116,6 @@ public class DatabaseCreator { } public static void main(String[] args) { - - ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {"/com/cloud/upgrade/databaseCreatorContext.xml"}); - appContext.getBean(ComponentContext.class); - String dbPropsFile = ""; List sqlFiles = new ArrayList(); List upgradeClasses = new ArrayList(); @@ -166,13 +162,17 @@ public class DatabaseCreator { System.exit(1); } + initDB(dbPropsFile, rootPassword, databases, dryRun); + + ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {"/com/cloud/upgrade/databaseCreatorContext.xml"}); + appContext.getBean(ComponentContext.class); + try { TransactionLegacy.initDataSource(dbPropsFile); } catch (IOException e) { e.printStackTrace(); System.exit(1); } - initDB(dbPropsFile, rootPassword, databases, dryRun); // Process sql files for (String sqlFile : sqlFiles) { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/DatabaseIntegrityChecker.java b/engine/schema/src/main/java/com/cloud/upgrade/DatabaseIntegrityChecker.java index 1fc8b7e3d84..e7ea6025ad7 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/DatabaseIntegrityChecker.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/DatabaseIntegrityChecker.java @@ -23,7 +23,6 @@ import java.sql.SQLException; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.apache.cloudstack.utils.CloudStackVersion; @@ -38,7 +37,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class DatabaseIntegrityChecker extends AdapterBase implements SystemIntegrityChecker { - private static final Logger s_logger = Logger.getLogger(DatabaseIntegrityChecker.class); @Inject VersionDao _dao; @@ -102,32 +100,32 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg } catch (Exception e) { - s_logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage()); + logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage()); throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage(),e); } } catch (Exception e) { - s_logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage()); + logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage()); throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage(),e); } } if (noDuplicate) { - s_logger.debug("No duplicate hosts with the same local storage found in database"); + logger.debug("No duplicate hosts with the same local storage found in database"); } else { - s_logger.error(helpInfo.toString()); + logger.error(helpInfo.toString()); } txn.commit(); return noDuplicate; }catch (Exception e) { - s_logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage()); + logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage()); throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage(),e); } } catch (Exception e) { - s_logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage()); + logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage()); throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage: Exception :" + e.getMessage(),e); } finally @@ -138,7 +136,7 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg } }catch(Exception e) { - s_logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception:"+ e.getMessage()); + logger.error("checkDuplicateHostWithTheSameLocalStorage: Exception:"+ e.getMessage()); } } } @@ -151,7 +149,7 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg String tableName = rs.getString(1); if (tableName.equalsIgnoreCase("usage_event") || tableName.equalsIgnoreCase("usage_port_forwarding") || tableName.equalsIgnoreCase("usage_network_offering")) { num++; - s_logger.debug("Checking 21to22PremiumUprage table " + tableName + " found"); + logger.debug("Checking 21to22PremiumUprage table " + tableName + " found"); } if (num == 3) { return true; @@ -167,7 +165,7 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg boolean found = false; while (rs.next()) { if (column.equalsIgnoreCase(rs.getString(1))) { - s_logger.debug(String.format("Column %1$s.%2$s.%3$s found", dbName, tableName, column)); + logger.debug(String.format("Column %1$s.%2$s.%3$s found", dbName, tableName, column)); found = true; break; } @@ -224,33 +222,33 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg } } if (!hasUsage) { - s_logger.debug("No cloud_usage found in database, no need to check missed premium upgrade"); + logger.debug("No cloud_usage found in database, no need to check missed premium upgrade"); txn.commit(); return true; } if (!check21to22PremiumUprage(conn)) { - s_logger.error("21to22 premium upgrade missed"); + logger.error("21to22 premium upgrade missed"); txn.commit(); return false; } if (!check221to222PremiumUprage(conn)) { - s_logger.error("221to222 premium upgrade missed"); + logger.error("221to222 premium upgrade missed"); txn.commit(); return false; } if (!check222to224PremiumUpgrade(conn)) { - s_logger.error("222to224 premium upgrade missed"); + logger.error("222to224 premium upgrade missed"); txn.commit(); return false; } txn.commit(); return true; } catch (Exception e) { - s_logger.error("checkMissedPremiumUpgradeFor228: Exception:" + e.getMessage()); + logger.error("checkMissedPremiumUpgradeFor228: Exception:" + e.getMessage()); throw new CloudRuntimeException("checkMissedPremiumUpgradeFor228: Exception:" + e.getMessage(), e); } }catch (Exception e) { - s_logger.error("checkMissedPremiumUpgradeFor228: Exception:"+ e.getMessage()); + logger.error("checkMissedPremiumUpgradeFor228: Exception:"+ e.getMessage()); throw new CloudRuntimeException("checkMissedPremiumUpgradeFor228: Exception:" + e.getMessage(),e); } finally @@ -261,7 +259,7 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg } }catch(Exception e) { - s_logger.error("checkMissedPremiumUpgradeFor228: Exception:"+ e.getMessage()); + logger.error("checkMissedPremiumUpgradeFor228: Exception:"+ e.getMessage()); } } } @@ -270,19 +268,19 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg public void check() { GlobalLock lock = GlobalLock.getInternLock("DatabaseIntegrity"); try { - s_logger.info("Grabbing lock to check for database integrity."); + logger.info("Grabbing lock to check for database integrity."); if (!lock.lock(20 * 60)) { throw new CloudRuntimeException("Unable to acquire lock to check for database integrity."); } try { - s_logger.info("Performing database integrity check"); + logger.info("Performing database integrity check"); if (!checkDuplicateHostWithTheSameLocalStorage()) { throw new CloudRuntimeException("checkDuplicateHostWithTheSameLocalStorage detected error"); } if (!checkMissedPremiumUpgradeFor228()) { - s_logger.error("Your current database version is 2.2.8, management server detected some missed premium upgrade, please contact CloudStack support and attach log file. Thank you!"); + logger.error("Your current database version is 2.2.8, management server detected some missed premium upgrade, please contact CloudStack support and attach log file. Thank you!"); throw new CloudRuntimeException("Detected missed premium upgrade"); } } finally { @@ -298,7 +296,7 @@ public class DatabaseIntegrityChecker extends AdapterBase implements SystemInteg try { check(); } catch (Exception e) { - s_logger.error("System integrity check exception", e); + logger.error("System integrity check exception", e); System.exit(1); } return true; diff --git a/engine/schema/src/main/java/com/cloud/upgrade/DatabaseUpgradeChecker.java b/engine/schema/src/main/java/com/cloud/upgrade/DatabaseUpgradeChecker.java index aecf4cc0590..abf86043937 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/DatabaseUpgradeChecker.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/DatabaseUpgradeChecker.java @@ -33,11 +33,11 @@ import java.util.List; import javax.inject.Inject; -import com.cloud.upgrade.dao.Upgrade41910to41920; import com.cloud.utils.FileUtil; import org.apache.cloudstack.utils.CloudStackVersion; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.upgrade.dao.DbUpgrade; import com.cloud.upgrade.dao.DbUpgradeSystemVmTemplate; @@ -87,6 +87,8 @@ import com.cloud.upgrade.dao.Upgrade41720to41800; import com.cloud.upgrade.dao.Upgrade41800to41810; import com.cloud.upgrade.dao.Upgrade41810to41900; import com.cloud.upgrade.dao.Upgrade41900to41910; +import com.cloud.upgrade.dao.Upgrade41910to42000; +import com.cloud.upgrade.dao.Upgrade42000to42010; import com.cloud.upgrade.dao.Upgrade420to421; import com.cloud.upgrade.dao.Upgrade421to430; import com.cloud.upgrade.dao.Upgrade430to440; @@ -126,7 +128,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.google.common.annotations.VisibleForTesting; public class DatabaseUpgradeChecker implements SystemIntegrityChecker { - private static final Logger s_logger = Logger.getLogger(DatabaseUpgradeChecker.class); + protected static Logger LOGGER = LogManager.getLogger(DatabaseUpgradeChecker.class); private final DatabaseVersionHierarchy hierarchy; private static final String VIEWS_DIRECTORY = Paths.get("META-INF", "db", "views").toString(); private static final String PROCEDURES_DIRECTORY = Paths.get("META-INF", "db", "procedures").toString(); @@ -228,7 +230,8 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { .next("4.18.0.0", new Upgrade41800to41810()) .next("4.18.1.0", new Upgrade41810to41900()) .next("4.19.0.0", new Upgrade41900to41910()) - .next("4.19.1.0", new Upgrade41910to41920()) + .next("4.19.1.0", new Upgrade41910to42000()) + .next("4.20.0.0", new Upgrade42000to42010()) .build(); } @@ -238,10 +241,10 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { ScriptRunner runner = new ScriptRunner(conn, false, true); runner.runScript(reader); } catch (IOException e) { - s_logger.error("Unable to read upgrade script", e); + LOGGER.error("Unable to read upgrade script", e); throw new CloudRuntimeException("Unable to read upgrade script", e); } catch (SQLException e) { - s_logger.error("Unable to execute upgrade script", e); + LOGGER.error("Unable to execute upgrade script", e); throw new CloudRuntimeException("Unable to execute upgrade script", e); } @@ -280,7 +283,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { conn = txn.getConnection(); } catch (SQLException e) { String errorMessage = "Unable to upgrade the database"; - s_logger.error(errorMessage, e); + LOGGER.error(errorMessage, e); throw new CloudRuntimeException(errorMessage, e); } ((DbUpgradeSystemVmTemplate)upgrade).updateSystemVmTemplates(conn); @@ -288,7 +291,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { break; } catch (CloudRuntimeException e) { String errorMessage = "Unable to upgrade the database"; - s_logger.error(errorMessage, e); + LOGGER.error(errorMessage, e); throw new CloudRuntimeException(errorMessage, e); } finally { txn.close(); @@ -306,29 +309,29 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { } protected void executeProcedureScripts() { - s_logger.info(String.format("Executing Stored Procedure scripts that are under resource directory [%s].", PROCEDURES_DIRECTORY)); + LOGGER.info(String.format("Executing Stored Procedure scripts that are under resource directory [%s].", PROCEDURES_DIRECTORY)); List filesPathUnderViewsDirectory = FileUtil.getFilesPathsUnderResourceDirectory(PROCEDURES_DIRECTORY); try (TransactionLegacy txn = TransactionLegacy.open("execute-procedure-scripts")) { Connection conn = txn.getConnection(); for (String filePath : filesPathUnderViewsDirectory) { - s_logger.debug(String.format("Executing PROCEDURE script [%s].", filePath)); + LOGGER.debug(String.format("Executing PROCEDURE script [%s].", filePath)); InputStream viewScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath); runScript(conn, viewScript); } - s_logger.info(String.format("Finished execution of PROCEDURE scripts that are under resource directory [%s].", PROCEDURES_DIRECTORY)); + LOGGER.info(String.format("Finished execution of PROCEDURE scripts that are under resource directory [%s].", PROCEDURES_DIRECTORY)); } catch (SQLException e) { String message = String.format("Unable to execute PROCEDURE scripts due to [%s].", e.getMessage()); - s_logger.error(message, e); + LOGGER.error(message, e); throw new CloudRuntimeException(message, e); } } private DbUpgrade[] executeUpgrades(CloudStackVersion dbVersion, CloudStackVersion currentVersion) { - s_logger.info("Database upgrade must be performed from " + dbVersion + " to " + currentVersion); + LOGGER.info("Database upgrade must be performed from " + dbVersion + " to " + currentVersion); final DbUpgrade[] upgrades = calculateUpgradePath(dbVersion, currentVersion); @@ -341,7 +344,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { private VersionVO executeUpgrade(DbUpgrade upgrade) { VersionVO version; - s_logger.debug("Running upgrade " + upgrade.getClass().getSimpleName() + " to upgrade from " + upgrade.getUpgradableVersionRange()[0] + "-" + upgrade + LOGGER.debug("Running upgrade " + upgrade.getClass().getSimpleName() + " to upgrade from " + upgrade.getUpgradableVersionRange()[0] + "-" + upgrade .getUpgradableVersionRange()[1] + " to " + upgrade.getUpgradedVersion()); TransactionLegacy txn = TransactionLegacy.open("Upgrade"); txn.start(); @@ -351,7 +354,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { conn = txn.getConnection(); } catch (SQLException e) { String errorMessage = "Unable to upgrade the database"; - s_logger.error(errorMessage, e); + LOGGER.error(errorMessage, e); throw new CloudRuntimeException(errorMessage, e); } InputStream[] scripts = upgrade.getPrepareScripts(); @@ -369,7 +372,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { txn.commit(); } catch (CloudRuntimeException e) { String errorMessage = "Unable to upgrade the database"; - s_logger.error(errorMessage, e); + LOGGER.error(errorMessage, e); throw new CloudRuntimeException(errorMessage, e); } finally { txn.close(); @@ -382,7 +385,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { // Run the corresponding '-cleanup.sql' script txn = TransactionLegacy.open("Cleanup"); try { - s_logger.info("Cleanup upgrade " + upgrade.getClass().getSimpleName() + " to upgrade from " + upgrade.getUpgradableVersionRange()[0] + "-" + upgrade + LOGGER.info("Cleanup upgrade " + upgrade.getClass().getSimpleName() + " to upgrade from " + upgrade.getUpgradableVersionRange()[0] + "-" + upgrade .getUpgradableVersionRange()[1] + " to " + upgrade.getUpgradedVersion()); txn.start(); @@ -390,7 +393,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { try { conn = txn.getConnection(); } catch (SQLException e) { - s_logger.error("Unable to cleanup the database", e); + LOGGER.error("Unable to cleanup the database", e); throw new CloudRuntimeException("Unable to cleanup the database", e); } @@ -398,7 +401,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { if (scripts != null) { for (InputStream script : scripts) { runScript(conn, script); - s_logger.debug("Cleanup script " + upgrade.getClass().getSimpleName() + " is executed successfully"); + LOGGER.debug("Cleanup script " + upgrade.getClass().getSimpleName() + " is executed successfully"); } } txn.commit(); @@ -408,30 +411,30 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { version.setUpdated(new Date()); _dao.update(version.getId(), version); txn.commit(); - s_logger.debug("Upgrade completed for version " + version.getVersion()); + LOGGER.debug("Upgrade completed for version " + version.getVersion()); } finally { txn.close(); } } protected void executeViewScripts() { - s_logger.info(String.format("Executing VIEW scripts that are under resource directory [%s].", VIEWS_DIRECTORY)); + LOGGER.info(String.format("Executing VIEW scripts that are under resource directory [%s].", VIEWS_DIRECTORY)); List filesPathUnderViewsDirectory = FileUtil.getFilesPathsUnderResourceDirectory(VIEWS_DIRECTORY); try (TransactionLegacy txn = TransactionLegacy.open("execute-view-scripts")) { Connection conn = txn.getConnection(); for (String filePath : filesPathUnderViewsDirectory) { - s_logger.debug(String.format("Executing VIEW script [%s].", filePath)); + LOGGER.debug(String.format("Executing VIEW script [%s].", filePath)); InputStream viewScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath); runScript(conn, viewScript); } - s_logger.info(String.format("Finished execution of VIEW scripts that are under resource directory [%s].", VIEWS_DIRECTORY)); + LOGGER.info(String.format("Finished execution of VIEW scripts that are under resource directory [%s].", VIEWS_DIRECTORY)); } catch (SQLException e) { String message = String.format("Unable to execute VIEW scripts due to [%s].", e.getMessage()); - s_logger.error(message, e); + LOGGER.error(message, e); throw new CloudRuntimeException(message, e); } } @@ -440,7 +443,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { public void check() { GlobalLock lock = GlobalLock.getInternLock("DatabaseUpgrade"); try { - s_logger.info("Grabbing lock to check for database upgrade."); + LOGGER.info("Grabbing lock to check for database upgrade."); if (!lock.lock(20 * 60)) { throw new CloudRuntimeException("Unable to acquire lock to check for database integrity."); } @@ -461,14 +464,14 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { SystemVmTemplateRegistration.CS_MAJOR_VERSION = String.valueOf(sysVmVersion.getMajorRelease()) + "." + String.valueOf(sysVmVersion.getMinorRelease()); SystemVmTemplateRegistration.CS_TINY_VERSION = String.valueOf(sysVmVersion.getPatchRelease()); - s_logger.info("DB version = " + dbVersion + " Code Version = " + currentVersion); + LOGGER.info("DB version = " + dbVersion + " Code Version = " + currentVersion); if (dbVersion.compareTo(currentVersion) > 0) { throw new CloudRuntimeException("Database version " + dbVersion + " is higher than management software version " + currentVersionValue); } if (dbVersion.compareTo(currentVersion) == 0) { - s_logger.info("DB version and code version matches so no upgrade needed."); + LOGGER.info("DB version and code version matches so no upgrade needed."); return; } @@ -491,13 +494,13 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { decryptInit(conn); txn.commit(); } catch (CloudRuntimeException e) { - s_logger.error(e.getMessage()); + LOGGER.error(e.getMessage()); errorMessage = String.format("Unable to initialize the database encryptors due to %s. " + "Please check if database encryption key and database encryptor version are correct.", errorMessage); - s_logger.error(errorMessage); + LOGGER.error(errorMessage); throw new CloudRuntimeException(errorMessage, e); } catch (SQLException e) { - s_logger.error(errorMessage, e); + LOGGER.error(errorMessage, e); throw new CloudRuntimeException(errorMessage, e); } finally { txn.close(); @@ -510,7 +513,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { ResultSet result = pstmt.executeQuery()) { if (result.next()) { String init = result.getString(1); - s_logger.info("init = " + DBEncryptionUtil.decrypt(init)); + LOGGER.info("init = " + DBEncryptionUtil.decrypt(init)); } } } @@ -567,7 +570,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { @Override public void updateSystemVmTemplates(Connection conn) { - s_logger.debug("Updating System Vm template IDs"); + LOGGER.debug("Updating System Vm template IDs"); initSystemVmTemplateRegistration(); try { systemVmTemplateRegistration.updateSystemVmTemplates(conn); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/GuestOsMapper.java b/engine/schema/src/main/java/com/cloud/upgrade/GuestOsMapper.java index 4aabaa3e182..abb0d7f7669 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/GuestOsMapper.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/GuestOsMapper.java @@ -18,7 +18,8 @@ package com.cloud.upgrade; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import java.sql.Connection; import java.sql.PreparedStatement; @@ -40,7 +41,7 @@ import com.cloud.storage.dao.GuestOSHypervisorDaoImpl; public class GuestOsMapper { - final static Logger LOG = Logger.getLogger(GuestOsMapper.class); + protected Logger logger = LogManager.getLogger(getClass()); @Inject GuestOSHypervisorDao guestOSHypervisorDao; @@ -56,15 +57,15 @@ public class GuestOsMapper { } public void mergeDuplicates() { - LOG.info("merging duplicate guest osses"); + logger.info("merging duplicate guest osses"); Set> duplicates = findDuplicates(); - LOG.debug(String.format("merging %d sets of duplicates", duplicates.size())); + logger.debug(String.format("merging %d sets of duplicates", duplicates.size())); for (Set setOfGuestOSes : duplicates) { // decide which to (mark as) remove(d) // # highest/lowest id // # or is user_defined == false GuestOSVO guestOSVO = highestIdFrom(setOfGuestOSes); - LOG.info(String.format("merging %d duplicates for %s ", setOfGuestOSes.size(), guestOSVO.getDisplayName())); + logger.info(String.format("merging %d duplicates for %s ", setOfGuestOSes.size(), guestOSVO.getDisplayName())); makeNormative(guestOSVO, setOfGuestOSes); } @@ -144,7 +145,7 @@ public class GuestOsMapper { if (guestOS != null) { id = guestOS.getId(); } else { - LOG.warn(String.format("Unable to find the guest OS details with category id: %d and display name: %s", + categoryId, displayName)); + logger.warn(String.format("Unable to find the guest OS details with category id: %d and display name: %s", + categoryId, displayName)); } return id; } @@ -155,7 +156,7 @@ public class GuestOsMapper { if (guestOSHypervisorVO != null) { id = guestOSHypervisorVO.getGuestOsId(); } else { - LOG.warn(String.format("Unable to find the guest OS hypervisor mapping details for %s", mapping.toString())); + logger.warn(String.format("Unable to find the guest OS hypervisor mapping details for %s", mapping.toString())); } return id; } @@ -163,9 +164,9 @@ public class GuestOsMapper { public void addGuestOsAndHypervisorMappings(long categoryId, String displayName, List mappings) { long guestOsId = getGuestOsId(categoryId, displayName); if (guestOsId == 0) { - LOG.debug("No guest OS found with category id: " + categoryId + " and display name: " + displayName); + logger.debug("No guest OS found with category id: " + categoryId + " and display name: " + displayName); if (!addGuestOs(categoryId, displayName)) { - LOG.warn("Couldn't add the guest OS with category id: " + categoryId + " and display name: " + displayName); + logger.warn("Couldn't add the guest OS with category id: " + categoryId + " and display name: " + displayName); return; } guestOsId = getGuestOsId(categoryId, displayName); @@ -189,7 +190,7 @@ public class GuestOsMapper { } public boolean addGuestOs(long categoryId, String displayName) { - LOG.debug("Adding guest OS with category id: " + categoryId + " and display name: " + displayName); + logger.debug("Adding guest OS with category id: " + categoryId + " and display name: " + displayName); GuestOSVO guestOS = new GuestOSVO(); guestOS.setCategoryId(categoryId); guestOS.setDisplayName(displayName); @@ -199,7 +200,7 @@ public class GuestOsMapper { public void addGuestOsHypervisorMapping(GuestOSHypervisorMapping mapping, long category, String displayName) { long guestOsId = getGuestOsId(category, displayName); if (guestOsId == 0) { - LOG.error(String.format("no guest os found for category %d and name %s, skipping mapping it to %s/%s", guestOsId, displayName, mapping.getHypervisorType(), mapping.getHypervisorVersion())); + logger.error(String.format("no guest os found for category %d and name %s, skipping mapping it to %s/%s", guestOsId, displayName, mapping.getHypervisorType(), mapping.getHypervisorVersion())); } else { addGuestOsHypervisorMapping(mapping, guestOsId); } @@ -210,7 +211,7 @@ public class GuestOsMapper { return; } - LOG.debug("Adding guest OS hypervisor mapping - " + mapping.toString() + ", for guest OS with id - " + guestOsId); + logger.debug("Adding guest OS hypervisor mapping - " + mapping.toString() + ", for guest OS with id - " + guestOsId); GuestOSHypervisorVO guestOsMapping = new GuestOSHypervisorVO(); guestOsMapping.setHypervisorType(mapping.getHypervisorType()); guestOsMapping.setHypervisorVersion(mapping.getHypervisorVersion()); @@ -222,7 +223,7 @@ public class GuestOsMapper { public void updateGuestOsName(long categoryId, String oldDisplayName, String newDisplayName) { GuestOSVO guestOS = guestOSDao.findByCategoryIdAndDisplayNameOrderByCreatedDesc(categoryId, oldDisplayName); if (guestOS == null) { - LOG.debug("Unable to update guest OS name, as there is no guest OS with category id: " + categoryId + " and display name: " + oldDisplayName); + logger.debug("Unable to update guest OS name, as there is no guest OS with category id: " + categoryId + " and display name: " + oldDisplayName); return; } @@ -237,7 +238,7 @@ public class GuestOsMapper { GuestOSHypervisorVO guestOSHypervisorVO = guestOSHypervisorDao.findByOsNameAndHypervisorOrderByCreatedDesc(mapping.getGuestOsName(), mapping.getHypervisorType(), mapping.getHypervisorVersion()); if (guestOSHypervisorVO == null) { - LOG.debug("Unable to update guest OS name, as there is no guest os hypervisor mapping"); + logger.debug("Unable to update guest OS name, as there is no guest os hypervisor mapping"); return; } @@ -256,13 +257,13 @@ public class GuestOsMapper { long oldGuestOsId = getGuestOsIdFromHypervisorMapping(mapping); if (oldGuestOsId == 0) { - LOG.debug("Unable to update guest OS in hypervisor mapping, as there is no guest os hypervisor mapping - " + mapping.toString()); + logger.debug("Unable to update guest OS in hypervisor mapping, as there is no guest os hypervisor mapping - " + mapping.toString()); return; } long newGuestOsId = getGuestOsId(categoryId, displayName); if (newGuestOsId == 0) { - LOG.debug("Unable to update guest OS id in hypervisor mapping, as there is no guest OS with category id: " + categoryId + " and display name: " + displayName); + logger.debug("Unable to update guest OS id in hypervisor mapping, as there is no guest OS with category id: " + categoryId + " and display name: " + displayName); return; } @@ -270,7 +271,7 @@ public class GuestOsMapper { } private void updateGuestOsIdInMapping(Connection conn, long oldGuestOsId, long newGuestOsId, GuestOSHypervisorMapping mapping) { - LOG.debug("Updating guest os id: " + oldGuestOsId + " to id: " + newGuestOsId + " in hypervisor mapping - " + mapping.toString()); + logger.debug("Updating guest os id: " + oldGuestOsId + " to id: " + newGuestOsId + " in hypervisor mapping - " + mapping.toString()); try { PreparedStatement pstmt = conn.prepareStatement(updateGuestOsHypervisorSql); pstmt.setLong(1, newGuestOsId); @@ -280,7 +281,7 @@ public class GuestOsMapper { pstmt.setString(5, mapping.getGuestOsName()); pstmt.executeUpdate(); } catch (SQLException e) { - LOG.error("Failed to update guest OS id in hypervisor mapping due to: " + e.getMessage(), e); + logger.error("Failed to update guest OS id in hypervisor mapping due to: " + e.getMessage(), e); } } @@ -289,7 +290,7 @@ public class GuestOsMapper { return true; } - LOG.warn("Invalid Guest OS hypervisor mapping"); + logger.warn("Invalid Guest OS hypervisor mapping"); return false; } @@ -299,22 +300,22 @@ public class GuestOsMapper { */ public boolean copyGuestOSHypervisorMappings(HypervisorType hypervisorType, String srcVersion, String destVersion) { if (hypervisorType == HypervisorType.None || hypervisorType == HypervisorType.Any) { - LOG.warn("Unable to copy, invalid hypervisor"); + logger.warn("Unable to copy, invalid hypervisor"); return false; } if (StringUtils.isAnyBlank(srcVersion, destVersion)) { - LOG.warn("Unable to copy, invalid hypervisor version details"); + logger.warn("Unable to copy, invalid hypervisor version details"); return false; } List guestOSHypervisorMappingsForSrcVersion = guestOSHypervisorDao.listByHypervisorTypeAndVersion(hypervisorType.toString(), srcVersion); if (CollectionUtils.isEmpty(guestOSHypervisorMappingsForSrcVersion)) { - LOG.warn(String.format("Unable to copy, couldn't find guest OS mappings for hypervisor: %s and src version: %s", hypervisorType.toString(), srcVersion)); + logger.warn(String.format("Unable to copy, couldn't find guest OS mappings for hypervisor: %s and src version: %s", hypervisorType.toString(), srcVersion)); return false; } - LOG.debug(String.format("Adding guest OS mappings for hypervisor: %s and version: %s, from version: %s ", hypervisorType.toString(), destVersion, srcVersion)); + logger.debug(String.format("Adding guest OS mappings for hypervisor: %s and version: %s, from version: %s ", hypervisorType.toString(), destVersion, srcVersion)); for (GuestOSHypervisorVO guestOSHypervisorMapping : guestOSHypervisorMappingsForSrcVersion) { GuestOSHypervisorMapping mapping = new GuestOSHypervisorMapping(hypervisorType.toString(), destVersion, guestOSHypervisorMapping.getGuestOsName()); addGuestOsHypervisorMapping(mapping, guestOSHypervisorMapping.getGuestOsId()); @@ -329,7 +330,7 @@ public class GuestOsMapper { long guestOsId = getGuestOsId(categoryId, displayName); if (guestOsId == 0) { - LOG.error(String.format("no guest os found for category %d and name %s, skipping mapping it to %s/%s", guestOsId, displayName, mapping.getHypervisorType(), mapping.getHypervisorVersion())); + logger.error(String.format("no guest os found for category %d and name %s, skipping mapping it to %s/%s", guestOsId, displayName, mapping.getHypervisorType(), mapping.getHypervisorVersion())); return; } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/RolePermissionChecker.java b/engine/schema/src/main/java/com/cloud/upgrade/RolePermissionChecker.java index 6d434cda755..370b85e37be 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/RolePermissionChecker.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/RolePermissionChecker.java @@ -16,7 +16,8 @@ // under the License. package com.cloud.upgrade; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import java.sql.Connection; import java.sql.PreparedStatement; @@ -25,7 +26,7 @@ import java.sql.SQLException; public class RolePermissionChecker { - final static Logger LOG = Logger.getLogger(RolePermissionChecker.class); + protected Logger logger = LogManager.getLogger(getClass()); private static final String checkAnnotationRulesPermissionPreparedStatement = "SELECT permission FROM `cloud`.`role_permissions` WHERE role_id = ? AND rule = ?"; @@ -43,7 +44,7 @@ public class RolePermissionChecker { ResultSet rs = pstmt.executeQuery(); return rs != null && rs.next(); } catch (SQLException e) { - LOG.error("Error on existsRolePermissionByRoleIdAndRule: " + e.getMessage(), e); + logger.error("Error on existsRolePermissionByRoleIdAndRule: " + e.getMessage(), e); return false; } } @@ -55,7 +56,7 @@ public class RolePermissionChecker { pstmt.setString(2, rule); pstmt.executeUpdate(); } catch (SQLException e) { - LOG.error("Error on insertAnnotationRulePermission: " + e.getMessage(), e); + logger.error("Error on insertAnnotationRulePermission: " + e.getMessage(), e); } } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/SystemVmTemplateRegistration.java b/engine/schema/src/main/java/com/cloud/upgrade/SystemVmTemplateRegistration.java index ec6ebf1680d..26b033c8d79 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/SystemVmTemplateRegistration.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/SystemVmTemplateRegistration.java @@ -16,36 +16,29 @@ // under the License. package com.cloud.upgrade; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.ClusterDaoImpl; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.DataCenterDaoImpl; -import com.cloud.hypervisor.Hypervisor; -import com.cloud.storage.DataStoreRole; -import com.cloud.storage.Storage; -import com.cloud.storage.Storage.ImageFormat; -import com.cloud.storage.VMTemplateStorageResourceAssoc; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.VMTemplateZoneVO; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.storage.dao.VMTemplateDaoImpl; -import com.cloud.storage.dao.VMTemplateZoneDao; -import com.cloud.storage.dao.VMTemplateZoneDaoImpl; -import com.cloud.template.VirtualMachineTemplate; -import com.cloud.upgrade.dao.BasicTemplateDataStoreDaoImpl; -import com.cloud.user.Account; -import com.cloud.utils.DateUtil; -import com.cloud.utils.Pair; -import com.cloud.utils.UriUtils; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallbackNoReturn; -import com.cloud.utils.db.TransactionStatus; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.script.Script; -import com.cloud.vm.dao.VMInstanceDao; -import com.cloud.vm.dao.VMInstanceDaoImpl; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.Date; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.stream.Collectors; + +import javax.inject.Inject; + import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.config.dao.ConfigurationDaoImpl; @@ -59,33 +52,49 @@ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; import org.apache.cloudstack.utils.security.DigestHelper; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.ini4j.Ini; -import javax.inject.Inject; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.net.URI; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.Connection; -import java.sql.Date; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; +import com.cloud.cpu.CPU; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.ClusterDao; +import com.cloud.dc.dao.ClusterDaoImpl; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.dc.dao.DataCenterDaoImpl; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.storage.DataStoreRole; +import com.cloud.storage.GuestOSVO; +import com.cloud.storage.Storage; +import com.cloud.storage.Storage.ImageFormat; +import com.cloud.storage.VMTemplateStorageResourceAssoc; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.VMTemplateZoneVO; +import com.cloud.storage.dao.GuestOSDao; +import com.cloud.storage.dao.GuestOSDaoImpl; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.storage.dao.VMTemplateDaoImpl; +import com.cloud.storage.dao.VMTemplateZoneDao; +import com.cloud.storage.dao.VMTemplateZoneDaoImpl; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.upgrade.dao.BasicTemplateDataStoreDaoImpl; +import com.cloud.user.Account; +import com.cloud.utils.DateUtil; +import com.cloud.utils.HttpUtils; +import com.cloud.utils.Pair; +import com.cloud.utils.UriUtils; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallbackNoReturn; +import com.cloud.utils.db.TransactionStatus; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.script.Script; +import com.cloud.vm.dao.VMInstanceDao; +import com.cloud.vm.dao.VMInstanceDaoImpl; public class SystemVmTemplateRegistration { - private static final Logger LOGGER = Logger.getLogger(SystemVmTemplateRegistration.class); + protected static Logger LOGGER = LogManager.getLogger(SystemVmTemplateRegistration.class); + private static final String MOUNT_COMMAND_BASE = "sudo mount -t nfs"; private static final String UMOUNT_COMMAND = "sudo umount %s"; private static final String RELATIVE_TEMPLATE_PATH = "./engine/schema/dist/systemvm-templates/"; private static final String ABSOLUTE_TEMPLATE_PATH = "/usr/share/cloudstack-management/templates/systemvm/"; @@ -96,11 +105,12 @@ public class SystemVmTemplateRegistration { private static final String PARTIAL_TEMPLATE_FOLDER = String.format("/template/tmpl/%d/", Account.ACCOUNT_ID_SYSTEM); private static final String storageScriptsDir = "scripts/storage/secondary"; private static final Integer OTHER_LINUX_ID = 99; - private static final Integer LINUX_5_ID = 15; - private static final Integer LINUX_7_ID = 183; + private static Integer LINUX_12_ID = 363; private static final Integer SCRIPT_TIMEOUT = 1800000; private static final Integer LOCK_WAIT_TIMEOUT = 1200; - + protected static final List DOWNLOADABLE_TEMPLATE_ARCH_TYPES = Arrays.asList( + CPU.CPUArch.arm64 + ); public static String CS_MAJOR_VERSION = null; public static String CS_TINY_VERSION = null; @@ -123,9 +133,13 @@ public class SystemVmTemplateRegistration { ClusterDao clusterDao; @Inject ConfigurationDao configurationDao; + @Inject + private GuestOSDao guestOSDao; private String systemVmTemplateVersion; + private final File tempDownloadDir; + public SystemVmTemplateRegistration() { dataCenterDao = new DataCenterDaoImpl(); vmTemplateDao = new VMTemplateDaoImpl(); @@ -136,6 +150,8 @@ public class SystemVmTemplateRegistration { imageStoreDetailsDao = new ImageStoreDetailsDaoImpl(); clusterDao = new ClusterDaoImpl(); configurationDao = new ConfigurationDaoImpl(); + guestOSDao = new GuestOSDaoImpl(); + tempDownloadDir = new File(System.getProperty("java.io.tmpdir")); } /** @@ -147,7 +163,7 @@ public class SystemVmTemplateRegistration { } public static String getMountCommand(String nfsVersion, String device, String dir) { - String cmd = "sudo mount -t nfs"; + String cmd = MOUNT_COMMAND_BASE; if (StringUtils.isNotBlank(nfsVersion)) { cmd = String.format("%s -o vers=%s", cmd, nfsVersion); } @@ -161,6 +177,10 @@ public class SystemVmTemplateRegistration { return systemVmTemplateVersion; } + public File getTempDownloadDir() { + return tempDownloadDir; + } + private static class SystemVMTemplateDetails { Long id; String uuid; @@ -172,6 +192,7 @@ public class SystemVmTemplateRegistration { ImageFormat format; Integer guestOsId; Hypervisor.HypervisorType hypervisorType; + CPU.CPUArch arch; Long storeId; Long size; Long physicalSize; @@ -181,7 +202,7 @@ public class SystemVmTemplateRegistration { SystemVMTemplateDetails(String uuid, String name, Date created, String url, String checksum, ImageFormat format, Integer guestOsId, Hypervisor.HypervisorType hypervisorType, - Long storeId) { + CPU.CPUArch arch, Long storeId) { this.uuid = uuid; this.name = name; this.created = created; @@ -190,6 +211,7 @@ public class SystemVmTemplateRegistration { this.format = format; this.guestOsId = guestOsId; this.hypervisorType = hypervisorType; + this.arch = arch; this.storeId = storeId; } @@ -233,6 +255,10 @@ public class SystemVmTemplateRegistration { return hypervisorType; } + public CPU.CPUArch getArch() { + return arch; + } + public Long getStoreId() { return storeId; } @@ -286,20 +312,19 @@ public class SystemVmTemplateRegistration { } } - public static final List hypervisorList = Arrays.asList(Hypervisor.HypervisorType.KVM, - Hypervisor.HypervisorType.VMware, - Hypervisor.HypervisorType.XenServer, - Hypervisor.HypervisorType.Hyperv, - Hypervisor.HypervisorType.LXC, - Hypervisor.HypervisorType.Ovm3 + public static final List> hypervisorList = Arrays.asList( + new Pair<>(Hypervisor.HypervisorType.KVM, CPU.CPUArch.amd64), + new Pair<>(Hypervisor.HypervisorType.KVM, CPU.CPUArch.arm64), + new Pair<>(Hypervisor.HypervisorType.VMware, null), + new Pair<>(Hypervisor.HypervisorType.XenServer, null), + new Pair<>(Hypervisor.HypervisorType.Hyperv, null), + new Pair<>(Hypervisor.HypervisorType.LXC, null), + new Pair<>(Hypervisor.HypervisorType.Ovm3, null) ); - public static final Map NewTemplateNameList = new HashMap(); - public static final Map FileNames = new HashMap(); - public static final Map NewTemplateUrl = new HashMap(); - public static final Map NewTemplateChecksum = new HashMap(); + public static final Map NewTemplateMap = new HashMap<>(); - public static final Map RouterTemplateConfigurationNames = new HashMap() { + public static final Map RouterTemplateConfigurationNames = new HashMap<>() { { put(Hypervisor.HypervisorType.KVM, "router.template.kvm"); put(Hypervisor.HypervisorType.VMware, "router.template.vmware"); @@ -310,14 +335,14 @@ public class SystemVmTemplateRegistration { } }; - public static final Map hypervisorGuestOsMap = new HashMap() { + public static Map hypervisorGuestOsMap = new HashMap<>() { { - put(Hypervisor.HypervisorType.KVM, LINUX_5_ID); + put(Hypervisor.HypervisorType.KVM, LINUX_12_ID); put(Hypervisor.HypervisorType.XenServer, OTHER_LINUX_ID); put(Hypervisor.HypervisorType.VMware, OTHER_LINUX_ID); - put(Hypervisor.HypervisorType.Hyperv, LINUX_5_ID); - put(Hypervisor.HypervisorType.LXC, LINUX_5_ID); - put(Hypervisor.HypervisorType.Ovm3, LINUX_7_ID); + put(Hypervisor.HypervisorType.Hyperv, LINUX_12_ID); + put(Hypervisor.HypervisorType.LXC, LINUX_12_ID); + put(Hypervisor.HypervisorType.Ovm3, LINUX_12_ID); } }; @@ -366,55 +391,73 @@ public class SystemVmTemplateRegistration { } } - public Long getRegisteredTemplateId(Pair hypervisorAndTemplateName) { - VMTemplateVO vmTemplate = vmTemplateDao.findLatestTemplateByName(hypervisorAndTemplateName.second()); - Long templateId = null; - if (vmTemplate != null) { - templateId = vmTemplate.getId(); + private static String getHypervisorArchLog(Hypervisor.HypervisorType hypervisorType, CPU.CPUArch arch) { + StringBuilder sb = new StringBuilder("hypervisor: ").append(hypervisorType.name()); + if (Hypervisor.HypervisorType.KVM.equals(hypervisorType)) { + sb.append(", arch: ").append(arch == null ? CPU.CPUArch.amd64.getType() : arch.getType()); } - return templateId; + return sb.toString(); } - private static String fetchTemplatesPath() { - String filePath = RELATIVE_TEMPLATE_PATH + METADATA_FILE_NAME; - LOGGER.debug(String.format("Looking for file [ %s ] in the classpath.", filePath)); - File metaFile = new File(filePath); - String templatePath = null; - if (metaFile.exists()) { - templatePath = RELATIVE_TEMPLATE_PATH; + protected static String getHypervisorArchKey(Hypervisor.HypervisorType hypervisorType, CPU.CPUArch arch) { + if (Hypervisor.HypervisorType.KVM.equals(hypervisorType)) { + return String.format("%s-%s", hypervisorType.name().toLowerCase(), + arch == null ? CPU.CPUArch.amd64.getType() : arch.getType()); } - if (templatePath == null) { - filePath = ABSOLUTE_TEMPLATE_PATH + METADATA_FILE_NAME; - metaFile = new File(filePath); - templatePath = ABSOLUTE_TEMPLATE_PATH; - LOGGER.debug(String.format("Looking for file [ %s ] in the classpath.", filePath)); - if (!metaFile.exists()) { - String errMsg = String.format("Unable to locate metadata file in your setup at %s", filePath.toString()); - LOGGER.error(errMsg); - throw new CloudRuntimeException(errMsg); + return hypervisorType.name().toLowerCase(); + } + + protected static MetadataTemplateDetails getMetadataTemplateDetails(Hypervisor.HypervisorType hypervisorType, + CPU.CPUArch arch) { + return NewTemplateMap.get(getHypervisorArchKey(hypervisorType, arch)); + } + + public VMTemplateVO getRegisteredTemplate(String templateName, CPU.CPUArch arch) { + return vmTemplateDao.findLatestTemplateByName(templateName, arch); + } + + private static boolean isRunningInTest() { + return "true".equalsIgnoreCase(System.getProperty("test.mode")); + } + + /** + * Attempts to determine the templates directory path by locating the metadata file. + *

+ * This method checks if the application is running in a test environment by invoking + * {@code isRunningInTest()}. If so, it immediately returns the {@code RELATIVE_TEMPLATE_PATH}. + *

+ *

+ * Otherwise, it creates a list of candidate paths (typically including both relative and absolute + * template paths) and iterates through them. For each candidate, it constructs the metadata file + * path by appending {@code METADATA_FILE_NAME} to {@code RELATIVE_TEMPLATE_PATH} (note: the candidate + * path is not used in the file path construction in this implementation) and checks if that file exists. + * If the metadata file exists, the candidate path is returned. + *

+ *

+ * If none of the candidate paths contain the metadata file, the method logs an error and throws a + * {@link CloudRuntimeException}. + *

+ * + * @return the path to the templates directory if the metadata file is found, or {@code RELATIVE_TEMPLATE_PATH} + * when running in a test environment. + * @throws CloudRuntimeException if the metadata file cannot be located in any of the candidate paths. + */ + private static String fetchTemplatesPath() { + if (isRunningInTest()) { + return RELATIVE_TEMPLATE_PATH; + } + List paths = Arrays.asList(RELATIVE_TEMPLATE_PATH, ABSOLUTE_TEMPLATE_PATH); + for (String path : paths) { + String filePath = path + METADATA_FILE_NAME; + LOGGER.debug("Looking for file [ {} ] in the classpath.", filePath); + File metaFile = new File(filePath); + if (metaFile.exists()) { + return path; } } - return templatePath; - } - - private String getHypervisorName(String name) { - if (name.equals("xenserver")) { - return "xen"; - } - if (name.equals("ovm3")) { - return "ovm"; - } - return name; - - } - - private Hypervisor.HypervisorType getHypervisorType(String hypervisor) { - if (hypervisor.equalsIgnoreCase("xen")) { - hypervisor = "xenserver"; - } else if (hypervisor.equalsIgnoreCase("ovm")) { - hypervisor = "ovm3"; - } - return Hypervisor.HypervisorType.getType(hypervisor); + String errMsg = String.format("Unable to locate metadata file in your setup at %s", StringUtils.join(paths)); + LOGGER.error(errMsg); + throw new CloudRuntimeException(errMsg); } private List getEligibleZoneIds() { @@ -428,28 +471,28 @@ public class SystemVmTemplateRegistration { return zoneIds; } - private Pair getNfsStoreInZone(Long zoneId) { - String url = null; - Long storeId = null; + protected Pair getNfsStoreInZone(Long zoneId) { ImageStoreVO storeVO = imageStoreDao.findOneByZoneAndProtocol(zoneId, "nfs"); if (storeVO == null) { - String errMsg = String.format("Failed to fetch NFS store in zone = %s for SystemVM template registration", zoneId); + String errMsg = String.format("Failed to fetch NFS store in zone = %s for SystemVM template registration", + zoneId); LOGGER.error(errMsg); throw new CloudRuntimeException(errMsg); } - url = storeVO.getUrl(); - storeId = storeVO.getId(); + String url = storeVO.getUrl(); + Long storeId = storeVO.getId(); return new Pair<>(url, storeId); } public static void mountStore(String storeUrl, String path, String nfsVersion) { try { - if (storeUrl != null) { - URI uri = new URI(UriUtils.encodeURIComponent(storeUrl)); - String host = uri.getHost(); - String mountPath = uri.getPath(); - Script.runSimpleBashScript(getMountCommand(nfsVersion, host + ":" + mountPath, path)); + if (storeUrl == null) { + return; } + URI uri = new URI(UriUtils.encodeURIComponent(storeUrl)); + String host = uri.getHost(); + String mountPath = uri.getPath(); + Script.runSimpleBashScript(getMountCommand(nfsVersion, host + ":" + mountPath, path)); } catch (Exception e) { String msg = "NFS Store URL is not in the correct format"; LOGGER.error(msg, e); @@ -457,13 +500,6 @@ public class SystemVmTemplateRegistration { } } - private List fetchAllHypervisors(Long zoneId) { - List hypervisorList = new ArrayList<>(); - List hypervisorTypes = clusterDao.getAvailableHypervisorInZone(zoneId); - hypervisorList = hypervisorTypes.stream().distinct().map(Enum::name).collect(Collectors.toList()); - return hypervisorList; - } - private VMTemplateVO createTemplateObjectInDB(SystemVMTemplateDetails details) { Long templateId = vmTemplateDao.getNextInSequence(Long.class, "id"); VMTemplateVO template = new VMTemplateVO(); @@ -484,6 +520,7 @@ public class SystemVmTemplateRegistration { template.setGuestOSId(details.getGuestOsId()); template.setCrossZones(true); template.setHypervisorType(details.getHypervisorType()); + template.setArch(details.getArch()); template.setState(VirtualMachineTemplate.State.Inactive); template.setDeployAsIs(false); template = vmTemplateDao.persist(template); @@ -562,6 +599,23 @@ public class SystemVmTemplateRegistration { vmInstanceDao.updateSystemVmTemplateId(templateId, hypervisorType); } + private void updateSystemVmTemplateGuestOsId() { + String systemVmGuestOsName = "Debian GNU/Linux 12 (64-bit)"; // default + try { + GuestOSVO guestOS = guestOSDao.findOneByDisplayName(systemVmGuestOsName); + if (guestOS != null) { + LOGGER.debug("Updating SystemVM Template Guest OS [{}] id", systemVmGuestOsName); + SystemVmTemplateRegistration.LINUX_12_ID = Math.toIntExact(guestOS.getId()); + hypervisorGuestOsMap.put(Hypervisor.HypervisorType.KVM, LINUX_12_ID); + hypervisorGuestOsMap.put(Hypervisor.HypervisorType.Hyperv, LINUX_12_ID); + hypervisorGuestOsMap.put(Hypervisor.HypervisorType.LXC, LINUX_12_ID); + hypervisorGuestOsMap.put(Hypervisor.HypervisorType.Ovm3, LINUX_12_ID); + } + } catch (Exception e) { + LOGGER.warn("Couldn't update SystemVM Template Guest OS id, due to {}", e.getMessage()); + } + } + public void updateConfigurationParams(Map configParams) { for (Map.Entry config : configParams.entrySet()) { boolean updated = configurationDao.update(config.getKey(), config.getValue()); @@ -625,16 +679,20 @@ public class SystemVmTemplateRegistration { } } - private void setupTemplate(String templateName, Pair hypervisorAndTemplateName, - String destTempFolder) throws CloudRuntimeException { + private void setupTemplate(String templateName, Hypervisor.HypervisorType hypervisor, CPU.CPUArch arch, + String destTempFolder) throws CloudRuntimeException { String setupTmpltScript = Script.findScript(storageScriptsDir, "setup-sysvm-tmplt"); if (setupTmpltScript == null) { throw new CloudRuntimeException("Unable to find the createtmplt.sh"); } Script scr = new Script(setupTmpltScript, SCRIPT_TIMEOUT, LOGGER); scr.add("-u", templateName); - scr.add("-f", TEMPLATES_PATH + FileNames.get(hypervisorAndTemplateName.first())); - scr.add("-h", hypervisorAndTemplateName.first().name().toLowerCase(Locale.ROOT)); + MetadataTemplateDetails templateDetails = NewTemplateMap.get(getHypervisorArchKey(hypervisor, arch)); + String filePath = StringUtils.isNotBlank(templateDetails.getDownloadedFilePath()) ? + templateDetails.getDownloadedFilePath() : + templateDetails.getDefaultFilePath(); + scr.add("-f", filePath); + scr.add("-h", hypervisor.name().toLowerCase(Locale.ROOT)); scr.add("-d", destTempFolder); String result = scr.execute(); if (result != null) { @@ -642,17 +700,15 @@ public class SystemVmTemplateRegistration { LOGGER.error(errMsg); throw new CloudRuntimeException(errMsg); } - } - private Long performTemplateRegistrationOperations(Pair hypervisorAndTemplateName, - String url, String checksum, ImageFormat format, long guestOsId, - Long storeId, Long templateId, String filePath, TemplateDataStoreVO templateDataStoreVO) { - Hypervisor.HypervisorType hypervisor = hypervisorAndTemplateName.first(); + private Long performTemplateRegistrationOperations(Hypervisor.HypervisorType hypervisor, + String name, CPU.CPUArch arch, String url, String checksum, ImageFormat format, long guestOsId, + Long storeId, Long templateId, String filePath, TemplateDataStoreVO templateDataStoreVO) { String templateName = UUID.randomUUID().toString(); Date created = new Date(DateUtil.currentGMTTime().getTime()); - SystemVMTemplateDetails details = new SystemVMTemplateDetails(templateName, hypervisorAndTemplateName.second(), created, - url, checksum, format, (int) guestOsId, hypervisor, storeId); + SystemVMTemplateDetails details = new SystemVMTemplateDetails(templateName, name, created, + url, checksum, format, (int) guestOsId, hypervisor, arch, storeId); if (templateId == null) { VMTemplateVO template = createTemplateObjectInDB(details); if (template == null) { @@ -669,23 +725,44 @@ public class SystemVmTemplateRegistration { if (templateDataStoreVO == null) { createTemplateStoreRefEntry(details); } - setupTemplate(templateName, hypervisorAndTemplateName, destTempFolder); + setupTemplate(templateName, hypervisor, arch, destTempFolder); readTemplateProperties(destTempFolder + "/template.properties", details); details.setUpdated(new Date(DateUtil.currentGMTTime().getTime())); updateTemplateDetails(details); return templateId; } - public void registerTemplate(Pair hypervisorAndTemplateName, - Pair storeUrlAndId, VMTemplateVO templateVO, - TemplateDataStoreVO templateDataStoreVO, String filePath) { + public void registerTemplate(Hypervisor.HypervisorType hypervisor, String name, Long storeId, + VMTemplateVO templateVO, TemplateDataStoreVO templateDataStoreVO, String filePath) { + try { + performTemplateRegistrationOperations(hypervisor, name, templateVO.getArch(), templateVO.getUrl(), + templateVO.getChecksum(), templateVO.getFormat(), templateVO.getGuestOSId(), storeId, + templateVO.getId(), filePath, templateDataStoreVO); + } catch (Exception e) { + String errMsg = String.format("Failed to register template for hypervisor: %s", hypervisor); + LOGGER.error(errMsg, e); + updateTemplateTablesOnFailure(templateVO.getId()); + cleanupStore(templateVO.getId(), filePath); + throw new CloudRuntimeException(errMsg, e); + } + } + + public void registerTemplateForNonExistingEntries(Hypervisor.HypervisorType hypervisor, CPU.CPUArch arch, + String name, Pair storeUrlAndId, String filePath) { Long templateId = null; try { - templateId = templateVO.getId(); - performTemplateRegistrationOperations(hypervisorAndTemplateName, templateVO.getUrl(), templateVO.getChecksum(), - templateVO.getFormat(), templateVO.getGuestOSId(), storeUrlAndId.second(), templateId, filePath, templateDataStoreVO); + MetadataTemplateDetails templateDetails = getMetadataTemplateDetails(hypervisor, arch); + templateId = performTemplateRegistrationOperations(hypervisor, name, + templateDetails.getArch(), templateDetails.getUrl(), + templateDetails.getChecksum(), hypervisorImageFormat.get(hypervisor), + hypervisorGuestOsMap.get(hypervisor), storeUrlAndId.second(), null, filePath, null); + Map configParams = new HashMap<>(); + configParams.put(RouterTemplateConfigurationNames.get(hypervisor), templateDetails.getName()); + configParams.put("minreq.sysvmtemplate.version", getSystemVmTemplateVersion()); + updateConfigurationParams(configParams); + updateSystemVMEntries(templateId, hypervisor); } catch (Exception e) { - String errMsg = String.format("Failed to register template for hypervisor: %s", hypervisorAndTemplateName.first()); + String errMsg = String.format("Failed to register template for hypervisor: %s", hypervisor); LOGGER.error(errMsg, e); if (templateId != null) { updateTemplateTablesOnFailure(templateId); @@ -695,26 +772,31 @@ public class SystemVmTemplateRegistration { } } - public void registerTemplate(Pair hypervisorAndTemplateName, Pair storeUrlAndId, String filePath) { - Long templateId = null; - try { - Hypervisor.HypervisorType hypervisor = hypervisorAndTemplateName.first(); - templateId = performTemplateRegistrationOperations(hypervisorAndTemplateName, NewTemplateUrl.get(hypervisor), NewTemplateChecksum.get(hypervisor), - hypervisorImageFormat.get(hypervisor), hypervisorGuestOsMap.get(hypervisor), storeUrlAndId.second(), null, filePath, null); - Map configParams = new HashMap<>(); - configParams.put(RouterTemplateConfigurationNames.get(hypervisorAndTemplateName.first()), hypervisorAndTemplateName.second()); - configParams.put("minreq.sysvmtemplate.version", getSystemVmTemplateVersion()); - updateConfigurationParams(configParams); - updateSystemVMEntries(templateId, hypervisorAndTemplateName.first()); - } catch (Exception e) { - String errMsg = String.format("Failed to register template for hypervisor: %s", hypervisorAndTemplateName.first()); - LOGGER.error(errMsg, e); - if (templateId != null) { - updateTemplateTablesOnFailure(templateId); - cleanupStore(templateId, filePath); - } - throw new CloudRuntimeException(errMsg, e); + protected void validateTemplateFileForHypervisorAndArch(Hypervisor.HypervisorType hypervisor, CPU.CPUArch arch) { + MetadataTemplateDetails templateDetails = getMetadataTemplateDetails(hypervisor, arch); + File templateFile = getTemplateFile(templateDetails); + if (templateFile == null) { + throw new CloudRuntimeException("Failed to find local template file"); } + if (isTemplateFileChecksumDifferent(templateDetails, templateFile)) { + throw new CloudRuntimeException("Checksum failed for local template file"); + } + } + + public void validateAndRegisterTemplate(Hypervisor.HypervisorType hypervisor, String name, Long storeId, + VMTemplateVO templateVO, TemplateDataStoreVO templateDataStoreVO, String filePath) { + validateTemplateFileForHypervisorAndArch(hypervisor, templateVO.getArch()); + registerTemplate(hypervisor, name, storeId, templateVO, templateDataStoreVO, filePath); + } + + public void validateAndRegisterTemplateForNonExistingEntries(Hypervisor.HypervisorType hypervisor, + CPU.CPUArch arch, String name, Pair storeUrlAndId, String filePath) { + validateTemplateFileForHypervisorAndArch(hypervisor, arch); + registerTemplateForNonExistingEntries(hypervisor, arch, name, storeUrlAndId, filePath); + } + + protected static String getMetadataFilePath() { + return METADATA_FILE; } /** @@ -724,26 +806,42 @@ public class SystemVmTemplateRegistration { * exist a template corresponding to the current code version. */ public static String parseMetadataFile() { - try { - Ini ini = new Ini(); - ini.load(new FileReader(METADATA_FILE)); - for (Hypervisor.HypervisorType hypervisorType : hypervisorList) { - String hypervisor = hypervisorType.name().toLowerCase(Locale.ROOT); - Ini.Section section = ini.get(hypervisor); - NewTemplateNameList.put(hypervisorType, section.get("templatename")); - FileNames.put(hypervisorType, section.get("filename")); - NewTemplateChecksum.put(hypervisorType, section.get("checksum")); - NewTemplateUrl.put(hypervisorType, section.get("downloadurl")); - } - Ini.Section section = ini.get("default"); - return section.get("version"); - } catch (Exception e) { - String errMsg = String.format("Failed to parse systemVM template metadata file: %s", METADATA_FILE); + String metadataFilePath = getMetadataFilePath(); + String errMsg = String.format("Failed to parse systemVM template metadata file: %s", metadataFilePath); + final Ini ini = new Ini(); + try (FileReader reader = new FileReader(metadataFilePath)) { + ini.load(reader); + } catch (IOException e) { LOGGER.error(errMsg, e); throw new CloudRuntimeException(errMsg, e); } + if (!ini.containsKey("default")) { + errMsg = String.format("%s as unable to default section", errMsg); + LOGGER.error(errMsg); + throw new CloudRuntimeException(errMsg); + } + for (Pair hypervisorType : hypervisorList) { + String key = getHypervisorArchKey(hypervisorType.first(), hypervisorType.second()); + Ini.Section section = ini.get(key); + if (section == null) { + LOGGER.error("Failed to find details for {} in template metadata file: {}", + key, metadataFilePath); + continue; + } + NewTemplateMap.put(key, new MetadataTemplateDetails( + hypervisorType.first(), + section.get("templatename"), + section.get("filename"), + section.get("downloadurl"), + section.get("checksum"), + hypervisorType.second(), + section.get("guestos"))); + } + Ini.Section defaultSection = ini.get("default"); + return defaultSection.get("version").trim(); } + private static void cleanupStore(Long templateId, String filePath) { String destTempFolder = filePath + PARTIAL_TEMPLATE_FOLDER + String.valueOf(templateId); try { @@ -753,31 +851,60 @@ public class SystemVmTemplateRegistration { } } - private void validateTemplates(Set hypervisorsInUse) { - Set hypervisors = hypervisorsInUse.stream().map(Enum::name). - map(name -> name.toLowerCase(Locale.ROOT)).map(this::getHypervisorName).collect(Collectors.toSet()); - List templates = new ArrayList<>(); - for (Hypervisor.HypervisorType hypervisorType : hypervisorsInUse) { - templates.add(FileNames.get(hypervisorType)); + protected File getTemplateFile(MetadataTemplateDetails templateDetails) { + File templateFile = new File(templateDetails.getDefaultFilePath()); + if (templateFile.exists()) { + return templateFile; } + LOGGER.debug("{} is not present", templateFile.getAbsolutePath()); + if (DOWNLOADABLE_TEMPLATE_ARCH_TYPES.contains(templateDetails.getArch()) && + StringUtils.isNotBlank(templateDetails.getUrl())) { + LOGGER.debug("Downloading the template file {} for {}", + templateDetails.getUrl(), templateDetails.getHypervisorArchLog()); + Path path = Path.of(TEMPLATES_PATH); + if (!Files.isWritable(path)) { + templateFile = new File(tempDownloadDir, templateDetails.getFilename()); + } + if (!templateFile.exists() && + !HttpUtils.downloadFileWithProgress(templateDetails.getUrl(), templateFile.getAbsolutePath(), + LOGGER)) { + return null; + } + templateDetails.setDownloadedFilePath(templateFile.getAbsolutePath()); + } + return templateFile; + } + protected boolean isTemplateFileChecksumDifferent(MetadataTemplateDetails templateDetails, File templateFile) { + String templateChecksum = DigestHelper.calculateChecksum(templateFile); + if (!templateChecksum.equals(templateDetails.getChecksum())) { + LOGGER.error("Checksum {} for file {} does not match checksum {} from metadata", + templateChecksum, templateFile, templateDetails.getChecksum()); + return true; + } + return false; + } + + protected void validateTemplates(List> hypervisorsArchInUse) { boolean templatesFound = true; - for (String hypervisor : hypervisors) { - String matchedTemplate = templates.stream().filter(x -> x.contains(hypervisor)).findAny().orElse(null); + for (Pair hypervisorArch : hypervisorsArchInUse) { + MetadataTemplateDetails matchedTemplate = getMetadataTemplateDetails(hypervisorArch.first(), + hypervisorArch.second()); if (matchedTemplate == null) { templatesFound = false; break; } - - File tempFile = new File(TEMPLATES_PATH + matchedTemplate); - String templateChecksum = DigestHelper.calculateChecksum(tempFile); - if (!templateChecksum.equals(NewTemplateChecksum.get(getHypervisorType(hypervisor)))) { - LOGGER.error(String.format("Checksum mismatch: %s != %s ", templateChecksum, NewTemplateChecksum.get(getHypervisorType(hypervisor)))); + File tempFile = getTemplateFile(matchedTemplate); + if (tempFile == null) { + LOGGER.warn("Failed to download template for {}, moving ahead", + matchedTemplate.getHypervisorArchLog()); + continue; + } + if (isTemplateFileChecksumDifferent(matchedTemplate, tempFile)) { templatesFound = false; break; } } - if (!templatesFound) { String errMsg = "SystemVm template not found. Cannot upgrade system Vms"; LOGGER.error(errMsg); @@ -785,7 +912,40 @@ public class SystemVmTemplateRegistration { } } - public void registerTemplates(Set hypervisorsInUse) { + protected void registerTemplatesForZone(long zoneId, String filePath) { + Pair storeUrlAndId = getNfsStoreInZone(zoneId); + String nfsVersion = getNfsVersion(storeUrlAndId.second()); + mountStore(storeUrlAndId.first(), filePath, nfsVersion); + List> hypervisorArchList = + clusterDao.listDistinctHypervisorsArchAcrossClusters(zoneId); + for (Pair hypervisorArch : hypervisorArchList) { + Hypervisor.HypervisorType hypervisorType = hypervisorArch.first(); + MetadataTemplateDetails templateDetails = getMetadataTemplateDetails(hypervisorType, + hypervisorArch.second()); + if (templateDetails == null) { + continue; + } + VMTemplateVO templateVO = getRegisteredTemplate(templateDetails.getName(), templateDetails.getArch()); + if (templateVO != null) { + TemplateDataStoreVO templateDataStoreVO = + templateDataStoreDao.findByStoreTemplate(storeUrlAndId.second(), templateVO.getId()); + if (templateDataStoreVO != null) { + String installPath = templateDataStoreVO.getInstallPath(); + if (validateIfSeeded(templateDataStoreVO, storeUrlAndId.first(), installPath, nfsVersion)) { + continue; + } + } + registerTemplate(hypervisorType, templateDetails.getName(), storeUrlAndId.second(), templateVO, + templateDataStoreVO, filePath); + updateRegisteredTemplateDetails(templateVO.getId(), templateDetails); + continue; + } + registerTemplateForNonExistingEntries(hypervisorType, templateDetails.getArch(), templateDetails.getName(), + storeUrlAndId, filePath); + } + } + + public void registerTemplates(List> hypervisorsArchInUse) { GlobalLock lock = GlobalLock.getInternLock("UpgradeDatabase-Lock"); try { LOGGER.info("Grabbing lock to register templates."); @@ -793,7 +953,7 @@ public class SystemVmTemplateRegistration { throw new CloudRuntimeException("Unable to acquire lock to register SystemVM template."); } try { - validateTemplates(hypervisorsInUse); + validateTemplates(hypervisorsArchInUse); // Perform Registration if templates not already registered Transaction.execute(new TransactionCallbackNoReturn() { @Override @@ -806,32 +966,7 @@ public class SystemVmTemplateRegistration { if (filePath == null) { throw new CloudRuntimeException("Failed to create temporary file path to mount the store"); } - Pair storeUrlAndId = getNfsStoreInZone(zoneId); - String nfsVersion = getNfsVersion(storeUrlAndId.second()); - mountStore(storeUrlAndId.first(), filePath, nfsVersion); - List hypervisorList = fetchAllHypervisors(zoneId); - for (String hypervisor : hypervisorList) { - Hypervisor.HypervisorType name = Hypervisor.HypervisorType.getType(hypervisor); - String templateName = NewTemplateNameList.get(name); - Pair hypervisorAndTemplateName = new Pair(name, templateName); - Long templateId = getRegisteredTemplateId(hypervisorAndTemplateName); - if (templateId != null) { - VMTemplateVO templateVO = vmTemplateDao.findById(templateId); - TemplateDataStoreVO templateDataStoreVO = templateDataStoreDao.findByStoreTemplate(storeUrlAndId.second(), templateId); - if (templateDataStoreVO != null) { - String installPath = templateDataStoreVO.getInstallPath(); - if (validateIfSeeded(templateDataStoreVO, storeUrlAndId.first(), installPath, nfsVersion)) { - continue; - } - } - if (templateVO != null) { - registerTemplate(hypervisorAndTemplateName, storeUrlAndId, templateVO, templateDataStoreVO, filePath); - updateRegisteredTemplateDetails(templateId, hypervisorAndTemplateName); - continue; - } - } - registerTemplate(hypervisorAndTemplateName, storeUrlAndId, filePath); - } + registerTemplatesForZone(zoneId, filePath); unmountStore(filePath); } catch (Exception e) { unmountStore(filePath); @@ -849,82 +984,99 @@ public class SystemVmTemplateRegistration { } } - private void updateRegisteredTemplateDetails(Long templateId, Map.Entry hypervisorAndTemplateName) { - Pair entry = new Pair<>(hypervisorAndTemplateName.getKey(), hypervisorAndTemplateName.getValue()); - updateRegisteredTemplateDetails(templateId, entry); - } - - private void updateRegisteredTemplateDetails(Long templateId, Pair hypervisorAndTemplateName) { + private void updateRegisteredTemplateDetails(Long templateId, MetadataTemplateDetails templateDetails) { VMTemplateVO templateVO = vmTemplateDao.findById(templateId); templateVO.setTemplateType(Storage.TemplateType.SYSTEM); + GuestOSVO guestOS = guestOSDao.findOneByDisplayName(templateDetails.getGuestOs()); + if (guestOS != null) { + templateVO.setGuestOSId(guestOS.getId()); + } boolean updated = vmTemplateDao.update(templateVO.getId(), templateVO); if (!updated) { String errMsg = String.format("updateSystemVmTemplates:Exception while updating template with id %s to be marked as 'system'", templateId); LOGGER.error(errMsg); throw new CloudRuntimeException(errMsg); } - - updateSystemVMEntries(templateId, hypervisorAndTemplateName.first()); - + Hypervisor.HypervisorType hypervisorType = templateDetails.getHypervisorType(); + updateSystemVMEntries(templateId, hypervisorType); // Change value of global configuration parameter router.template.* for the corresponding hypervisor and minreq.sysvmtemplate.version for the ACS version Map configParams = new HashMap<>(); - configParams.put(RouterTemplateConfigurationNames.get(hypervisorAndTemplateName.first()), hypervisorAndTemplateName.second()); + configParams.put(RouterTemplateConfigurationNames.get(hypervisorType), templateDetails.getName()); configParams.put("minreq.sysvmtemplate.version", getSystemVmTemplateVersion()); updateConfigurationParams(configParams); } - private void updateTemplateUrlAndChecksum(VMTemplateVO templateVO, Map.Entry hypervisorAndTemplateName) { - templateVO.setUrl(NewTemplateUrl.get(hypervisorAndTemplateName.getKey())); - templateVO.setChecksum(NewTemplateChecksum.get(hypervisorAndTemplateName.getKey())); + private void updateTemplateUrlChecksumAndGuestOsId(VMTemplateVO templateVO, MetadataTemplateDetails templateDetails) { + templateVO.setUrl(templateDetails.getUrl()); + templateVO.setChecksum(templateDetails.getChecksum()); + GuestOSVO guestOS = guestOSDao.findOneByDisplayName(templateDetails.getGuestOs()); + if (guestOS != null) { + templateVO.setGuestOSId(guestOS.getId()); + } boolean updated = vmTemplateDao.update(templateVO.getId(), templateVO); if (!updated) { - String errMsg = String.format("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type %s", hypervisorAndTemplateName.getKey().name()); + String errMsg = String.format("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type %s", templateDetails.getHypervisorType()); LOGGER.error(errMsg); throw new CloudRuntimeException(errMsg); } } + protected boolean registerOrUpdateSystemVmTemplate(MetadataTemplateDetails templateDetails, + List> hypervisorsInUse) { + LOGGER.debug("Updating System VM template for {}", templateDetails.getHypervisorArchLog()); + VMTemplateVO registeredTemplate = getRegisteredTemplate(templateDetails.getName(), templateDetails.getArch()); + // change template type to SYSTEM + if (registeredTemplate != null) { + updateRegisteredTemplateDetails(registeredTemplate.getId(), templateDetails); + } else { + boolean isHypervisorArchMatchMetadata = hypervisorsInUse.stream() + .anyMatch(p -> p.first().equals(templateDetails.getHypervisorType()) + && Objects.equals(p.second(), templateDetails.getArch())); + if (isHypervisorArchMatchMetadata) { + try { + registerTemplates(hypervisorsInUse); + return true; + } catch (final Exception e) { + throw new CloudRuntimeException(String.format("Failed to register %s templates for hypervisors: [%s]. " + + "Cannot upgrade system VMs", + getSystemVmTemplateVersion(), + StringUtils.join(hypervisorsInUse.stream() + .map(x -> getHypervisorArchKey(x.first(), x.second())) + .collect(Collectors.toList()), ",")), e); + } + } else { + LOGGER.warn("Cannot upgrade {} system VM template for {} as it is not used, not failing upgrade", + getSystemVmTemplateVersion(), templateDetails.getHypervisorArchLog()); + VMTemplateVO templateVO = vmTemplateDao.findLatestTemplateByTypeAndHypervisorAndArch( + templateDetails.getHypervisorType(), templateDetails.getArch(), Storage.TemplateType.SYSTEM); + if (templateVO != null) { + updateTemplateUrlChecksumAndGuestOsId(templateVO, templateDetails); + } + } + } + return false; + } + public void updateSystemVmTemplates(final Connection conn) { LOGGER.debug("Updating System Vm template IDs"); + updateSystemVmTemplateGuestOsId(); Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(final TransactionStatus status) { - Set hypervisorsListInUse = new HashSet(); + List> hypervisorsInUse; try { - hypervisorsListInUse = clusterDao.getDistictAvailableHypervisorsAcrossClusters(); - + hypervisorsInUse = clusterDao.listDistinctHypervisorsArchAcrossClusters(null); } catch (final Exception e) { - LOGGER.error("updateSystemVmTemplates: Exception caught while getting hypervisor types from clusters: " + e.getMessage()); - throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting hypervisor types from clusters", e); + throw new CloudRuntimeException("Exception while getting hypervisor types from clusters", e); } - - for (final Map.Entry hypervisorAndTemplateName : NewTemplateNameList.entrySet()) { - LOGGER.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms"); - Long templateId = getRegisteredTemplateId(new Pair<>(hypervisorAndTemplateName.getKey(), hypervisorAndTemplateName.getValue())); + Collection templateEntries = NewTemplateMap.values(); + for (MetadataTemplateDetails templateDetails : templateEntries) { try { - // change template type to SYSTEM - if (templateId != null) { - updateRegisteredTemplateDetails(templateId, hypervisorAndTemplateName); - } else { - if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())) { - try { - registerTemplates(hypervisorsListInUse); - break; - } catch (final Exception e) { - throw new CloudRuntimeException(String.format("%s %s SystemVm template not found. Cannot upgrade system Vms", getSystemVmTemplateVersion(), hypervisorAndTemplateName.getKey())); - } - } else { - LOGGER.warn(String.format("%s %s SystemVm template not found. Cannot upgrade system Vms hypervisor is not used, so not failing upgrade", - getSystemVmTemplateVersion(), hypervisorAndTemplateName.getKey())); - // Update the latest template URLs for corresponding hypervisor - VMTemplateVO templateVO = vmTemplateDao.findLatestTemplateByTypeAndHypervisor(hypervisorAndTemplateName.getKey(), Storage.TemplateType.SYSTEM); - if (templateVO != null) { - updateTemplateUrlAndChecksum(templateVO, hypervisorAndTemplateName); - } - } + if (registerOrUpdateSystemVmTemplate(templateDetails, hypervisorsInUse)) { + break; } } catch (final Exception e) { - String errMsg = "updateSystemVmTemplates:Exception while getting ids of templates"; + String errMsg = "Exception while registering/updating system VM templates for hypervisors in metadata"; LOGGER.error(errMsg, e); throw new CloudRuntimeException(errMsg, e); } @@ -946,4 +1098,70 @@ public class SystemVmTemplateRegistration { } return null; } + + protected static class MetadataTemplateDetails { + private final Hypervisor.HypervisorType hypervisorType; + private final String name; + private final String filename; + private final String url; + private final String checksum; + private final CPU.CPUArch arch; + private String downloadedFilePath; + private final String guestOs; + + MetadataTemplateDetails(Hypervisor.HypervisorType hypervisorType, String name, String filename, String url, + String checksum, CPU.CPUArch arch, String guestOs) { + this.hypervisorType = hypervisorType; + this.name = name; + this.filename = filename; + this.url = url; + this.checksum = checksum; + this.arch = arch; + this.guestOs = guestOs; + } + + public Hypervisor.HypervisorType getHypervisorType() { + return hypervisorType; + } + + public String getName() { + return name; + } + + public String getFilename() { + return filename; + } + + public String getUrl() { + return url; + } + + public String getChecksum() { + return checksum; + } + + public CPU.CPUArch getArch() { + return arch; + } + + public String getGuestOs() { + return guestOs; + } + + public String getDownloadedFilePath() { + return downloadedFilePath; + } + + public void setDownloadedFilePath(String downloadedFilePath) { + this.downloadedFilePath = downloadedFilePath; + } + + public String getDefaultFilePath() { + return TEMPLATES_PATH + filename; + } + + public String getHypervisorArchLog() { + return SystemVmTemplateRegistration.getHypervisorArchLog(hypervisorType, arch); + } + } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/DatabaseAccessObject.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/DatabaseAccessObject.java index de161afea07..0b973d195de 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/DatabaseAccessObject.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/DatabaseAccessObject.java @@ -22,20 +22,21 @@ import java.sql.ResultSet; import java.sql.SQLException; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; public class DatabaseAccessObject { - private static Logger s_logger = Logger.getLogger(DatabaseAccessObject.class); + protected Logger logger = LogManager.getLogger(DatabaseAccessObject.class); public void addForeignKey(Connection conn, String tableName, String tableColumn, String foreignTableName, String foreignColumnName) { String addForeignKeyStmt = String.format("ALTER TABLE `cloud`.`%s` ADD CONSTRAINT `fk_%s__%s` FOREIGN KEY `fk_%s__%s`(`%s`) REFERENCES `%s`(`%s`)", tableName, tableName, tableColumn, tableName, tableColumn, tableColumn, foreignTableName, foreignColumnName); try(PreparedStatement pstmt = conn.prepareStatement(addForeignKeyStmt);) { pstmt.executeUpdate(); - s_logger.debug(String.format("Foreign key is added successfully from the table %s", tableName)); + logger.debug(String.format("Foreign key is added successfully from the table %s", tableName)); } catch (SQLException e) { - s_logger.error("Ignored SQL Exception when trying to add foreign key on table " + tableName + " exception: " + e.getMessage()); + logger.error("Ignored SQL Exception when trying to add foreign key on table " + tableName + " exception: " + e.getMessage()); } } @@ -50,9 +51,9 @@ public class DatabaseAccessObject { try(PreparedStatement pstmt = conn.prepareStatement(alter_sql_str);) { pstmt.executeUpdate(); - s_logger.debug("Key " + key + " is dropped successfully from the table " + tableName); + logger.debug("Key " + key + " is dropped successfully from the table " + tableName); } catch (SQLException e) { - s_logger.debug("Ignored SQL Exception when trying to drop " + (isForeignKey ? "foreign " : "") + "key " + key + " on table " + tableName + " exception: " + e.getMessage()); + logger.debug("Ignored SQL Exception when trying to drop " + (isForeignKey ? "foreign " : "") + "key " + key + " on table " + tableName + " exception: " + e.getMessage()); } } @@ -60,18 +61,18 @@ public class DatabaseAccessObject { public void dropPrimaryKey(Connection conn, String tableName) { try(PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP PRIMARY KEY ");) { pstmt.executeUpdate(); - s_logger.debug("Primary key is dropped successfully from the table " + tableName); + logger.debug("Primary key is dropped successfully from the table " + tableName); } catch (SQLException e) { - s_logger.debug("Ignored SQL Exception when trying to drop primary key on table " + tableName + " exception: " + e.getMessage()); + logger.debug("Ignored SQL Exception when trying to drop primary key on table " + tableName + " exception: " + e.getMessage()); } } public void dropColumn(Connection conn, String tableName, String columnName) { try (PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP COLUMN " + columnName);){ pstmt.executeUpdate(); - s_logger.debug("Column " + columnName + " is dropped successfully from the table " + tableName); + logger.debug("Column " + columnName + " is dropped successfully from the table " + tableName); } catch (SQLException e) { - s_logger.warn("Unable to drop column " + columnName + " due to exception", e); + logger.warn("Unable to drop column " + columnName + " due to exception", e); } } @@ -81,7 +82,7 @@ public class DatabaseAccessObject { pstmt.executeQuery(); columnExists = true; } catch (SQLException e) { - s_logger.debug("Field " + columnName + " doesn't exist in " + tableName + " ignoring exception: " + e.getMessage()); + logger.debug("Field " + columnName + " doesn't exist in " + tableName + " ignoring exception: " + e.getMessage()); } return columnExists; } @@ -97,29 +98,40 @@ public class DatabaseAccessObject { return true; } } catch (SQLException e) { - s_logger.debug(String.format("Index %s doesn't exist, ignoring exception:", indexName, e.getMessage())); + logger.debug(String.format("Index %s doesn't exist, ignoring exception:", indexName, e.getMessage())); } return false; } public void createIndex(Connection conn, String tableName, String indexName, String... columnNames) { String stmt = String.format("CREATE INDEX %s ON %s (%s)", indexName, tableName, StringUtils.join(columnNames, ", ")); - s_logger.debug("Statement: " + stmt); + logger.debug("Statement: " + stmt); try (PreparedStatement pstmt = conn.prepareStatement(stmt)) { pstmt.execute(); - s_logger.debug(String.format("Created index %s", indexName)); + logger.debug(String.format("Created index %s", indexName)); } catch (SQLException e) { - s_logger.warn(String.format("Unable to create index %s", indexName), e); + logger.warn(String.format("Unable to create index %s", indexName), e); } } - protected static void closePreparedStatement(PreparedStatement pstmt, String errorMessage) { + public void renameIndex(Connection conn, String tableName, String oldName, String newName) { + String stmt = String.format("ALTER TABLE %s RENAME INDEX %s TO %s", tableName, oldName, newName); + logger.debug("Statement: {}", stmt); + try (PreparedStatement pstmt = conn.prepareStatement(stmt)) { + pstmt.execute(); + logger.debug("Renamed index {} to {}", oldName, newName); + } catch (SQLException e) { + logger.warn("Unable to rename index {} to {}", oldName, newName, e); + } + } + + protected void closePreparedStatement(PreparedStatement pstmt, String errorMessage) { try { if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { - s_logger.warn(errorMessage, e); + logger.warn(errorMessage, e); } } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/DbUpgradeAbstractImpl.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/DbUpgradeAbstractImpl.java new file mode 100644 index 00000000000..c96365dd6f5 --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/DbUpgradeAbstractImpl.java @@ -0,0 +1,24 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.upgrade.dao; + +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; + +public abstract class DbUpgradeAbstractImpl implements DbUpgrade { + protected Logger logger = LogManager.getLogger(getClass()); +} diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/DbUpgradeUtils.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/DbUpgradeUtils.java index 51e6ac7b9a1..2f90422adf8 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/DbUpgradeUtils.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/DbUpgradeUtils.java @@ -31,6 +31,12 @@ public class DbUpgradeUtils { } } + public static void renameIndexIfNeeded(Connection conn, String tableName, String oldName, String newName) { + if (!dao.indexExists(conn, tableName, oldName)) { + dao.renameIndex(conn, tableName, oldName, newName); + } + } + public static void addForeignKey(Connection conn, String tableName, String tableColumn, String foreignTableName, String foreignColumnName) { dao.addForeignKey(conn, tableName, tableColumn, foreignTableName, foreignColumnName); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/LegacyDbUpgrade.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/LegacyDbUpgrade.java index d058943f439..2a64ff496a2 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/LegacyDbUpgrade.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/LegacyDbUpgrade.java @@ -16,11 +16,9 @@ // under the License. package com.cloud.upgrade.dao; -import org.apache.log4j.Logger; -public abstract class LegacyDbUpgrade implements DbUpgrade{ +public abstract class LegacyDbUpgrade extends DbUpgradeAbstractImpl{ - final static Logger s_logger = Logger.getLogger(LegacyDbUpgrade.class); public LegacyDbUpgrade() { super(); @@ -34,7 +32,7 @@ public abstract class LegacyDbUpgrade implements DbUpgrade{ try { closable.close(); } catch (Exception e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade217to218.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade217to218.java index 2ca4e794fb8..5441f8fb02f 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade217to218.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade217to218.java @@ -21,7 +21,7 @@ import java.sql.Connection; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade217to218 implements DbUpgrade { +public class Upgrade217to218 extends DbUpgradeAbstractImpl { @Override public InputStream[] getPrepareScripts() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to22.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to22.java index bc58794e8bd..171357578ee 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to22.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to22.java @@ -34,7 +34,6 @@ import java.util.Properties; import java.util.TimeZone; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.configuration.Resource.ResourceType; import com.cloud.event.EventTypes; @@ -45,8 +44,7 @@ import com.cloud.utils.NumbersUtil; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; -public class Upgrade218to22 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade218to22.class); +public class Upgrade218to22 extends DbUpgradeAbstractImpl { boolean _basicZone; @Override @@ -212,7 +210,7 @@ public class Upgrade218to22 implements DbUpgrade { protected void upgradeDomR(Connection conn, long dcId, long domrId, Long publicNetworkId, long guestNetworkId, long controlNetworkId, String zoneType, String vnet) throws SQLException { - s_logger.debug("Upgrading domR" + domrId); + logger.debug("Upgrading domR" + domrId); try ( PreparedStatement pstmt = conn.prepareStatement("SELECT vm_instance.id, vm_instance.state, vm_instance.private_mac_address, vm_instance.private_ip_address, vm_instance.private_netmask, domain_router.public_mac_address, domain_router.public_ip_address, domain_router.public_netmask, domain_router.guest_mac_address, domain_router.guest_ip_address, domain_router.guest_netmask, domain_router.vnet, domain_router.gateway FROM vm_instance INNER JOIN domain_router ON vm_instance.id=domain_router.id WHERE vm_instance.removed is NULL AND vm_instance.id=?"); @@ -274,7 +272,7 @@ public class Upgrade218to22 implements DbUpgrade { protected void upgradeSsvm(Connection conn, long dataCenterId, long publicNetworkId, long managementNetworkId, long controlNetworkId, String zoneType) throws SQLException { - s_logger.debug("Upgrading ssvm in " + dataCenterId); + logger.debug("Upgrading ssvm in " + dataCenterId); //select instance try ( PreparedStatement selectInstance = @@ -284,7 +282,7 @@ public class Upgrade218to22 implements DbUpgrade { try (ResultSet instanceResult = selectInstance.executeQuery();) { if (!instanceResult.next()) { - s_logger.debug("Unable to find ssvm in data center " + dataCenterId); + logger.debug("Unable to find ssvm in data center " + dataCenterId); return; } @@ -309,7 +307,7 @@ public class Upgrade218to22 implements DbUpgrade { try (ResultSet hostResult = selectHost.executeQuery();) { if (!hostResult.next()) { - s_logger.debug("Unable to find ssvm in data center " + dataCenterId); + logger.debug("Unable to find ssvm in data center " + dataCenterId); return; } @@ -365,7 +363,7 @@ public class Upgrade218to22 implements DbUpgrade { protected void upgradeConsoleProxy(Connection conn, long dcId, long cpId, long publicNetworkId, long managementNetworkId, long controlNetworkId, String zoneType) throws SQLException { - s_logger.debug("Upgrading cp" + cpId); + logger.debug("Upgrading cp" + cpId); try (PreparedStatement pstmt = conn.prepareStatement("SELECT vm_instance.id, vm_instance.state, vm_instance.private_mac_address, vm_instance.private_ip_address, vm_instance.private_netmask, console_proxy.public_mac_address, console_proxy.public_ip_address, console_proxy.public_netmask, console_proxy.guest_mac_address, console_proxy.guest_ip_address, console_proxy.guest_netmask, console_proxy.gateway, vm_instance.type FROM vm_instance INNER JOIN console_proxy ON vm_instance.id=console_proxy.id WHERE vm_instance.removed is NULL AND vm_instance.id=?");) { pstmt.setLong(1, cpId); @@ -466,7 +464,7 @@ public class Upgrade218to22 implements DbUpgrade { vm[4] = rs.getString(5); // vm state vms.add(vm); } - s_logger.debug("Upgrading " + vms.size() + " vms for router " + domainRouterId); + logger.debug("Upgrading " + vms.size() + " vms for router " + domainRouterId); for (Object[] vm : vms) { String state = (String)vm[4]; @@ -617,7 +615,7 @@ public class Upgrade218to22 implements DbUpgrade { } protected void upgradeDirectUserIpAddress(Connection conn, long dcId, long networkId, String vlanType) throws SQLException { - s_logger.debug("Upgrading user ip address for data center " + dcId + " network " + networkId + " vlan type " + vlanType); + logger.debug("Upgrading user ip address for data center " + dcId + " network " + networkId + " vlan type " + vlanType); try (PreparedStatement pstmt = conn.prepareStatement("UPDATE user_ip_address INNER JOIN vlan ON user_ip_address.vlan_db_id=vlan.id SET user_ip_address.source_network_id=vlan.network_id WHERE user_ip_address.data_center_id=? AND vlan.vlan_type=?");) { pstmt.setLong(1, dcId); @@ -638,8 +636,8 @@ public class Upgrade218to22 implements DbUpgrade { ip[3] = rs.getDate(4); // allocated allocatedIps.add(ip); } - s_logger.debug("Marking " + allocatedIps.size() + " ip addresses to belong to network " + networkId); - s_logger.debug("Updating mac addresses for data center id=" + dcId + ". Found " + allocatedIps.size() + " ip addresses to update"); + logger.debug("Marking " + allocatedIps.size() + " ip addresses to belong to network " + networkId); + logger.debug("Updating mac addresses for data center id=" + dcId + ". Found " + allocatedIps.size() + " ip addresses to update"); for (Object[] allocatedIp : allocatedIps) { try (PreparedStatement selectMacAddresses = conn.prepareStatement("SELECT mac_address FROM data_center WHERE id = ?");) { selectMacAddresses.setLong(1, dcId); @@ -665,7 +663,7 @@ public class Upgrade218to22 implements DbUpgrade { } protected void upgradePublicUserIpAddress(Connection conn, long dcId, long networkId, String vlanType) throws SQLException { - s_logger.debug("Upgrading user ip address for data center " + dcId + " network " + networkId + " vlan type " + vlanType); + logger.debug("Upgrading user ip address for data center " + dcId + " network " + networkId + " vlan type " + vlanType); try (PreparedStatement pstmt = conn.prepareStatement("UPDATE user_ip_address INNER JOIN vlan ON user_ip_address.vlan_db_id=vlan.id SET source_network_id=? WHERE user_ip_address.data_center_id=? AND vlan.vlan_type=?");) { pstmt.setLong(1, networkId); @@ -763,7 +761,7 @@ public class Upgrade218to22 implements DbUpgrade { } } catch (SQLException e) { - s_logger.error("Can't update data center ", e); + logger.error("Can't update data center ", e); throw new CloudRuntimeException("Can't update data center ", e); } } @@ -832,7 +830,7 @@ public class Upgrade218to22 implements DbUpgrade { pstmt.setString(1, type); try (ResultSet rs = pstmt.executeQuery();) { if (!rs.next()) { - s_logger.error("Unable to find the network offering for networktype '" + type + "'"); + logger.error("Unable to find the network offering for networktype '" + type + "'"); throw new CloudRuntimeException("Unable to find the storage network offering."); } networkOfferingId = rs.getLong(1); @@ -970,7 +968,7 @@ public class Upgrade218to22 implements DbUpgrade { private void updateRouters(Connection conn, Long dcId, long controlNetworkId, long basicDefaultDirectNetworkId, ArrayList routers) throws SQLException { for (Object[] router : routers) { - s_logger.debug("Updating domR with network id in basic zone id=" + dcId); + logger.debug("Updating domR with network id in basic zone id=" + dcId); updateNetworkForRouter(conn, router, basicDefaultDirectNetworkId); upgradeUserVms(conn, (Long)router[0], basicDefaultDirectNetworkId, (String)router[1], "untagged", "DirectPodBasedNetworkGuru", "Create"); upgradeDomR(conn, dcId, (Long)router[0], null, basicDefaultDirectNetworkId, controlNetworkId, "Basic", "untagged"); @@ -1007,7 +1005,7 @@ public class Upgrade218to22 implements DbUpgrade { updateDomainRouter.setLong(2, (Long)router[0]); updateDomainRouter.executeUpdate(); } - s_logger.debug("Network inserted for " + router[0] + " id = " + virtualNetworkId); + logger.debug("Network inserted for " + router[0] + " id = " + virtualNetworkId); } private void createDirectNetworks(Connection conn, Object[] dc, Long dcId) throws SQLException { @@ -1029,7 +1027,7 @@ public class Upgrade218to22 implements DbUpgrade { updateNetworkInVlanTableforTag(conn, vlanNetworkMap, vlanId, tag); upgradeDirectUserIpAddress(conn, dcId, vlanNetworkMap.get(tag), "DirectAttached"); - s_logger.debug("Created Direct networks and upgraded Direct ip addresses"); + logger.debug("Created Direct networks and upgraded Direct ip addresses"); } } } @@ -1118,11 +1116,11 @@ public class Upgrade218to22 implements DbUpgrade { String gateway = retrieveGateway(conn, directNetworkId); updateDomainRouter(conn, routerId, directNetworkId); - s_logger.debug("NetworkId updated for router id=" + routerId + "with network id = " + directNetworkId); + logger.debug("NetworkId updated for router id=" + routerId + "with network id = " + directNetworkId); upgradeUserVms(conn, routerId, directNetworkId, gateway, vnet, "DirectNetworkGuru", "Create"); - s_logger.debug("Upgraded Direct vms in Advance zone id=" + dcId); + logger.debug("Upgraded Direct vms in Advance zone id=" + dcId); upgradeDomR(conn, dcId, routerId, null, directNetworkId, controlNetworkId, "Advanced", vnet); - s_logger.debug("Upgraded Direct domRs in Advance zone id=" + dcId); + logger.debug("Upgraded Direct domRs in Advance zone id=" + dcId); } } } @@ -1166,7 +1164,7 @@ public class Upgrade218to22 implements DbUpgrade { PreparedStatement pstmt = conn.prepareStatement("UPDATE user_statistics SET device_type='DomainRouter'"); ){ pstmt.executeUpdate(); - s_logger.debug("Upgraded userStatistcis with device_type=DomainRouter"); + logger.debug("Upgraded userStatistcis with device_type=DomainRouter"); // update device_id information try ( @@ -1182,7 +1180,7 @@ public class Upgrade218to22 implements DbUpgrade { selectNetworkType.setLong(1, dataCenterId); try (ResultSet dcSet = selectNetworkType.executeQuery();) { if (!dcSet.next()) { - s_logger.error("Unable to get data_center information as a part of user_statistics update"); + logger.error("Unable to get data_center information as a part of user_statistics update"); throw new CloudRuntimeException("Unable to get data_center information as a part of user_statistics update"); } String dataCenterType = dcSet.getString(1); @@ -1204,7 +1202,7 @@ public class Upgrade218to22 implements DbUpgrade { selectnonRemovedVms.setLong(2, dataCenterId); try (ResultSet nonRemovedVms = selectnonRemovedVms.executeQuery();) { if (nonRemovedVms.next()) { - s_logger.warn("Failed to find domR for account id=" + accountId + " in zone id=" + dataCenterId + + logger.warn("Failed to find domR for account id=" + accountId + " in zone id=" + dataCenterId + "; will try to locate domR based on user_vm info"); //try to get domR information from the user_vm belonging to the account try (PreparedStatement selectNetworkType = @@ -1213,14 +1211,14 @@ public class Upgrade218to22 implements DbUpgrade { selectNetworkType.setLong(2, dataCenterId); try (ResultSet userVmSet = selectNetworkType.executeQuery();) { if (!userVmSet.next()) { - s_logger.warn("Skipping user_statistics upgrade for account id=" + accountId + " in datacenter id=" + dataCenterId); + logger.warn("Skipping user_statistics upgrade for account id=" + accountId + " in datacenter id=" + dataCenterId); continue; } deviceId = userVmSet.getLong(1); } } } else { - s_logger.debug("Account id=" + accountId + " doesn't own any user vms and domRs, so skipping user_statistics update"); + logger.debug("Account id=" + accountId + " doesn't own any user vms and domRs, so skipping user_statistics update"); continue; } } @@ -1237,7 +1235,7 @@ public class Upgrade218to22 implements DbUpgrade { } } } - s_logger.debug("Upgraded userStatistcis with deviceId(s)"); + logger.debug("Upgraded userStatistcis with deviceId(s)"); } catch (Exception e) { throw new CloudRuntimeException("Failed to migrate usage events: ", e); @@ -1263,7 +1261,7 @@ public class Upgrade218to22 implements DbUpgrade { } if (!rules.isEmpty()) { - s_logger.debug("Found " + rules.size() + " port forwarding rules to upgrade"); + logger.debug("Found " + rules.size() + " port forwarding rules to upgrade"); for (Object[] rule : rules) { long id = (Long)rule[0]; String sourcePort = (String)rule[2]; @@ -1275,7 +1273,7 @@ public class Upgrade218to22 implements DbUpgrade { try (ResultSet userIpAddressData = selectUserIpAddressData.executeQuery();) { if (!userIpAddressData.next()) { - s_logger.error("Unable to find public IP address " + publicIp); + logger.error("Unable to find public IP address " + publicIp); throw new CloudRuntimeException("Unable to find public IP address " + publicIp); } int ipAddressId = userIpAddressData.getInt(1); @@ -1285,7 +1283,7 @@ public class Upgrade218to22 implements DbUpgrade { String privateIp = (String)rule[3]; // update port_forwarding_rules table - s_logger.trace("Updating port_forwarding_rules table..."); + logger.trace("Updating port_forwarding_rules table..."); try (PreparedStatement selectInstanceId = conn.prepareStatement("SELECT instance_id FROM nics where network_id=? AND ip4_address=?");) { selectInstanceId.setLong(1, networkId); selectInstanceId.setString(2, privateIp); @@ -1293,14 +1291,14 @@ public class Upgrade218to22 implements DbUpgrade { if (!selectedInstanceId.next()) { // the vm might be expunged already...so just give the warning - s_logger.warn("Unable to find vmId for private ip address " + privateIp + " for account id=" + accountId + "; assume that the vm is expunged"); + logger.warn("Unable to find vmId for private ip address " + privateIp + " for account id=" + accountId + "; assume that the vm is expunged"); // throw new CloudRuntimeException("Unable to find vmId for private ip address " + privateIp + // " for account id=" + accountId); } else { long instanceId = selectedInstanceId.getLong(1); - s_logger.debug("Instance id is " + instanceId); + logger.debug("Instance id is " + instanceId); // update firewall_rules table - s_logger.trace("Updating firewall_rules table as a part of PF rules upgrade..."); + logger.trace("Updating firewall_rules table as a part of PF rules upgrade..."); try ( PreparedStatement insertFirewallRules = conn.prepareStatement("INSERT INTO firewall_rules (id, ip_address_id, start_port, end_port, state, protocol, purpose, account_id, domain_id, network_id, xid, is_static_nat, created) VALUES (?, ?, ?, ?, 'Active', ?, 'PortForwarding', ?, ?, ?, ?, 0, now())"); @@ -1315,7 +1313,7 @@ public class Upgrade218to22 implements DbUpgrade { insertFirewallRules.setLong(8, networkId); insertFirewallRules.setString(9, UUID.randomUUID().toString()); insertFirewallRules.executeUpdate(); - s_logger.trace("firewall_rules table is updated as a part of PF rules upgrade"); + logger.trace("firewall_rules table is updated as a part of PF rules upgrade"); } String privatePort = (String)rule[4]; try (PreparedStatement insertPortForwardingRules = conn.prepareStatement("INSERT INTO port_forwarding_rules VALUES (?, ?, ?, ?, ?)");) { @@ -1326,7 +1324,7 @@ public class Upgrade218to22 implements DbUpgrade { insertPortForwardingRules.setInt(5, Integer.parseInt(privatePort.trim())); insertPortForwardingRules.executeUpdate(); } - s_logger.trace("port_forwarding_rules table is updated"); + logger.trace("port_forwarding_rules table is updated"); } } } @@ -1334,7 +1332,7 @@ public class Upgrade218to22 implements DbUpgrade { } } } - s_logger.debug("Port forwarding rules are updated"); + logger.debug("Port forwarding rules are updated"); } catch (SQLException e) { throw new CloudRuntimeException("Can't update port forwarding rules ", e); } @@ -1358,7 +1356,7 @@ public class Upgrade218to22 implements DbUpgrade { } if (!lbs.isEmpty()) { - s_logger.debug("Found " + lbs.size() + " lb rules to upgrade"); + logger.debug("Found " + lbs.size() + " lb rules to upgrade"); long newLbId = 0; try ( PreparedStatement selectFWRules = conn.prepareStatement("SELECT max(id) FROM firewall_rules order by id"); @@ -1382,7 +1380,7 @@ public class Upgrade218to22 implements DbUpgrade { try (ResultSet ipData = selectIpData.executeQuery();) { if (!ipData.next()) { - s_logger.warn("Unable to find public IP address " + publicIp + "; skipping lb rule id=" + originalLbId + + logger.warn("Unable to find public IP address " + publicIp + "; skipping lb rule id=" + originalLbId + " from update. Cleaning it up from load_balancer_vm_map and load_balancer table"); try (PreparedStatement deleteLbVmMap = conn.prepareStatement("DELETE from load_balancer_vm_map where load_balancer_id=?");) { deleteLbVmMap.setLong(1, originalLbId); @@ -1399,7 +1397,7 @@ public class Upgrade218to22 implements DbUpgrade { long domainId = ipData.getLong(3); long networkId = ipData.getLong(4); // update firewall_rules table - s_logger.trace("Updating firewall_rules table as a part of LB rules upgrade..."); + logger.trace("Updating firewall_rules table as a part of LB rules upgrade..."); try (PreparedStatement insertFirewallRules = conn.prepareStatement("INSERT INTO firewall_rules (id, ip_address_id, start_port, end_port, state, protocol, purpose, account_id, domain_id, network_id, xid, is_static_nat, created) VALUES (?, ?, ?, ?, 'Active', ?, 'LoadBalancing', ?, ?, ?, ?, 0, now())");) { insertFirewallRules.setLong(1, newLbId); @@ -1413,13 +1411,13 @@ public class Upgrade218to22 implements DbUpgrade { insertFirewallRules.setString(9, UUID.randomUUID().toString()); insertFirewallRules.executeUpdate(); } - s_logger.trace("firewall_rules table is updated as a part of LB rules upgrade"); + logger.trace("firewall_rules table is updated as a part of LB rules upgrade"); } } // update load_balancing_rules - s_logger.trace("Updating load_balancing_rules table as a part of LB rules upgrade..."); + logger.trace("Updating load_balancing_rules table as a part of LB rules upgrade..."); try (PreparedStatement insertLoadBalancer = conn.prepareStatement("INSERT INTO load_balancing_rules VALUES (?, ?, NULL, ?, ?, ?)");) { insertLoadBalancer.setLong(1, newLbId); insertLoadBalancer.setString(2, name); @@ -1428,10 +1426,10 @@ public class Upgrade218to22 implements DbUpgrade { insertLoadBalancer.setString(5, algorithm); insertLoadBalancer.executeUpdate(); } - s_logger.trace("load_balancing_rules table is updated as a part of LB rules upgrade"); + logger.trace("load_balancing_rules table is updated as a part of LB rules upgrade"); // update load_balancer_vm_map table - s_logger.trace("Updating load_balancer_vm_map table as a part of LB rules upgrade..."); + logger.trace("Updating load_balancer_vm_map table as a part of LB rules upgrade..."); try ( PreparedStatement selectInstance = conn.prepareStatement("SELECT instance_id FROM load_balancer_vm_map WHERE load_balancer_id=?"); ) { @@ -1451,10 +1449,10 @@ public class Upgrade218to22 implements DbUpgrade { updateLoadBalancer.setLong(2, originalLbId); updateLoadBalancer.executeUpdate(); } - s_logger.trace("load_balancer_vm_map table is updated as a part of LB rules upgrade"); + logger.trace("load_balancer_vm_map table is updated as a part of LB rules upgrade"); } } - s_logger.debug("LB rules are upgraded"); + logger.debug("LB rules are upgraded"); } catch (SQLException e) { throw new CloudRuntimeException("Can't update LB rules ", e); } @@ -1724,7 +1722,7 @@ public class Upgrade218to22 implements DbUpgrade { ResultSet rs1 = pstmt1.executeQuery(); ) { if (!rs1.next()) { - s_logger.debug("cloud_usage db doesn't exist. Skipping events migration"); + logger.debug("cloud_usage db doesn't exist. Skipping events migration"); return; } @@ -1734,7 +1732,7 @@ public class Upgrade218to22 implements DbUpgrade { String sql = "SELECT type, description, user_id, account_id, created, level, parameters FROM cloud.event vmevt WHERE vmevt.id > ? and vmevt.state = 'Completed' "; if (lastProcessedEvent == null) { - s_logger.trace("no events are processed earlier, copying all events"); + logger.trace("no events are processed earlier, copying all events"); sql = "SELECT type, description, user_id, account_id, created, level, parameters FROM cloud.event vmevt WHERE vmevt.state = 'Completed' "; } @@ -1744,7 +1742,7 @@ public class Upgrade218to22 implements DbUpgrade { pstmt.setLong(i++, lastProcessedEvent); } try (ResultSet rs = pstmt.executeQuery();) { - s_logger.debug("Begin Migrating events"); + logger.debug("Begin Migrating events"); while (rs.next()) { EventVO event = new EventVO(); event.setType(rs.getString(1)); @@ -1758,7 +1756,7 @@ public class Upgrade218to22 implements DbUpgrade { } } } - s_logger.debug("Migrating events completed"); + logger.debug("Migrating events completed"); } catch (Exception e) { throw new CloudRuntimeException("Failed to migrate usage events: ", e); } @@ -2142,7 +2140,7 @@ public class Upgrade218to22 implements DbUpgrade { cleanupLbVmMaps(conn); } catch (SQLException e) { - s_logger.error("Can't perform data migration ", e); + logger.error("Can't perform data migration ", e); throw new CloudRuntimeException("Can't perform data migration ", e); } @@ -2180,7 +2178,7 @@ public class Upgrade218to22 implements DbUpgrade { ResultSet rs = selectStoragePoolRef.executeQuery(); ) { if (!rs.next()) { - s_logger.debug("No records in template_spool_ref, skipping this upgrade part"); + logger.debug("No records in template_spool_ref, skipping this upgrade part"); return; } while (rs.next()) { @@ -2192,7 +2190,7 @@ public class Upgrade218to22 implements DbUpgrade { try (ResultSet selectedStoragePool = selectStoragePool.executeQuery();) { if (!selectedStoragePool.next()) { - s_logger.debug("Orphaned template_spool_ref record is found (storage pool doesn't exist any more0) id=" + id + "; so removing the record"); + logger.debug("Orphaned template_spool_ref record is found (storage pool doesn't exist any more0) id=" + id + "; so removing the record"); try (PreparedStatement delete = conn.prepareStatement("DELETE FROM template_spool_ref where id=?");) { delete.setLong(1, id); delete.executeUpdate(); @@ -2201,9 +2199,9 @@ public class Upgrade218to22 implements DbUpgrade { } } } - s_logger.debug("Finished deleting orphaned template_spool_ref(s)"); + logger.debug("Finished deleting orphaned template_spool_ref(s)"); } catch (Exception e) { - s_logger.error("Failed to delete orphaned template_spool_ref(s): ", e); + logger.error("Failed to delete orphaned template_spool_ref(s): ", e); throw new CloudRuntimeException("Failed to delete orphaned template_spool_ref(s): ", e); } } @@ -2215,7 +2213,7 @@ public class Upgrade218to22 implements DbUpgrade { ){ while (selectedVolumes.next()) { Long id = selectedVolumes.getLong(1); - s_logger.debug("Volume id is " + id); + logger.debug("Volume id is " + id); Long instanceId = selectedVolumes.getLong(2); Long accountId = selectedVolumes.getLong(3); @@ -2245,15 +2243,15 @@ public class Upgrade218to22 implements DbUpgrade { try(PreparedStatement pstmt = conn.prepareStatement("UPDATE volumes SET state='Destroy' WHERE id=?");) { pstmt.setLong(1, id); pstmt.executeUpdate(); - s_logger.debug("Volume with id=" + id + " is marked with Destroy state as a part of volume cleanup (it's Destroyed had 127 value)"); + logger.debug("Volume with id=" + id + " is marked with Destroy state as a part of volume cleanup (it's Destroyed had 127 value)"); } } } } } - s_logger.debug("Finished cleaning up volumes with incorrect Destroyed field (127)"); + logger.debug("Finished cleaning up volumes with incorrect Destroyed field (127)"); } catch (Exception e) { - s_logger.error("Failed to cleanup volumes with incorrect Destroyed field (127):", e); + logger.error("Failed to cleanup volumes with incorrect Destroyed field (127):", e); throw new CloudRuntimeException("Failed to cleanup volumes with incorrect Destroyed field (127):", e); } } @@ -2267,7 +2265,7 @@ public class Upgrade218to22 implements DbUpgrade { if (result__index.next()) { try (PreparedStatement alterTable = conn.prepareStatement("ALTER TABLE `cloud`.`security_group` DROP INDEX `fk_network_group__account_id`");) { alterTable.executeUpdate(); - s_logger.debug("Unique key 'fk_network_group__account_id' is removed successfully"); + logger.debug("Unique key 'fk_network_group__account_id' is removed successfully"); } } @@ -2278,7 +2276,7 @@ public class Upgrade218to22 implements DbUpgrade { if (result___index.next()) { try (PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`security_group` DROP INDEX `fk_network_group___account_id`");) { pstmt.executeUpdate(); - s_logger.debug("Unique key 'fk_network_group___account_id' is removed successfully"); + logger.debug("Unique key 'fk_network_group___account_id' is removed successfully"); } } } @@ -2310,7 +2308,7 @@ public class Upgrade218to22 implements DbUpgrade { ResultSet rs2 = pstmt2.executeQuery(); ) { if (!rs1.next() && rs2.next()) { - s_logger.debug("Removing load balancer vm mappings for lb id=" + lbId + " as a part of cleanup"); + logger.debug("Removing load balancer vm mappings for lb id=" + lbId + " as a part of cleanup"); try (PreparedStatement delete = conn.prepareStatement("DELETE FROM load_balancer_vm_map where load_balancer_id=?");) { delete.setLong(1, lbId); delete.executeUpdate(); @@ -2329,7 +2327,7 @@ public class Upgrade218to22 implements DbUpgrade { * Create usage events for existing port forwarding rules */ private void createPortForwardingEvents(Connection conn) { - s_logger.debug("Creating Port Forwarding usage events"); + logger.debug("Creating Port Forwarding usage events"); try ( PreparedStatement pstmt = conn.prepareStatement("SELECT fw.account_id, ip.data_center_id, fw.id FROM firewall_rules fw, user_ip_address ip where purpose = 'PortForwarding' and " @@ -2354,7 +2352,7 @@ public class Upgrade218to22 implements DbUpgrade { pstmt1.executeUpdate(); } } - s_logger.debug("Completed creating Port Forwarding usage events"); + logger.debug("Completed creating Port Forwarding usage events"); } catch (SQLException e) { throw new CloudRuntimeException("Failed to add port forwarding usage events due to:", e); } @@ -2364,7 +2362,7 @@ public class Upgrade218to22 implements DbUpgrade { * Create usage events for existing load balancer rules */ private void createLoadBalancerEvents(Connection conn) { - s_logger.debug("Creating load balancer usage events"); + logger.debug("Creating load balancer usage events"); try ( PreparedStatement pstmt = conn.prepareStatement("SELECT fw.account_id, ip.data_center_id, fw.id FROM firewall_rules fw, user_ip_address ip where purpose = 'LoadBalancing' and " @@ -2389,7 +2387,7 @@ public class Upgrade218to22 implements DbUpgrade { pstmt1.executeUpdate(); } } - s_logger.debug("Completed creating load balancer usage events"); + logger.debug("Completed creating load balancer usage events"); } catch (SQLException e) { throw new CloudRuntimeException("Failed to add Load Balancer usage events due to:", e); } @@ -2399,7 +2397,7 @@ public class Upgrade218to22 implements DbUpgrade { * Create usage events for network offerings */ private void createNetworkOfferingEvents(Connection conn) { - s_logger.debug("Creating network offering usage events"); + logger.debug("Creating network offering usage events"); try ( PreparedStatement pstmt = conn.prepareStatement("SELECT vm.account_id, vm.data_center_id, ni.instance_id, vm.name, nw.network_offering_id, nw.is_default FROM nics ni, " @@ -2429,7 +2427,7 @@ public class Upgrade218to22 implements DbUpgrade { pstmt1.executeUpdate(); } } - s_logger.debug("Completed creating network offering usage events"); + logger.debug("Completed creating network offering usage events"); } catch (SQLException e) { throw new CloudRuntimeException("Failed to add network offering usage events due to:", e); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to224DomainVlans.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to224DomainVlans.java index 5f66728e6d9..65a71993e91 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to224DomainVlans.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to224DomainVlans.java @@ -23,12 +23,10 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade218to224DomainVlans implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade218to224DomainVlans.class); +public class Upgrade218to224DomainVlans extends DbUpgradeAbstractImpl { @Override public InputStream[] getPrepareScripts() { @@ -42,7 +40,7 @@ public class Upgrade218to224DomainVlans implements DbUpgrade { try { PreparedStatement pstmt = conn.prepareStatement("SELECT id FROM networks WHERE shared=1 AND traffic_type='Guest' AND guest_type='Direct'"); ResultSet rs = pstmt.executeQuery(); - s_logger.debug("query is " + pstmt); + logger.debug("query is " + pstmt); while (rs.next()) { Long networkId = rs.getLong(1); Long vlanId = null; @@ -50,7 +48,7 @@ public class Upgrade218to224DomainVlans implements DbUpgrade { pstmt = conn.prepareStatement("SELECT id FROM vlan WHERE network_id=? LIMIT 0,1"); pstmt.setLong(1, networkId); - s_logger.debug("query is " + pstmt); + logger.debug("query is " + pstmt); rs = pstmt.executeQuery(); while (rs.next()) { @@ -60,7 +58,7 @@ public class Upgrade218to224DomainVlans implements DbUpgrade { if (vlanId != null) { pstmt = conn.prepareStatement("SELECT domain_id FROM account_vlan_map WHERE domain_id IS NOT NULL AND vlan_db_id=? LIMIT 0,1"); pstmt.setLong(1, vlanId); - s_logger.debug("query is " + pstmt); + logger.debug("query is " + pstmt); rs = pstmt.executeQuery(); while (rs.next()) { @@ -118,7 +116,7 @@ public class Upgrade218to224DomainVlans implements DbUpgrade { try { pstmt.executeQuery(); } catch (SQLException e) { - s_logger.debug("Assuming that domain_id field doesn't exist in account_vlan_map table, no need to upgrade"); + logger.debug("Assuming that domain_id field doesn't exist in account_vlan_map table, no need to upgrade"); return; } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to22Premium.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to22Premium.java index d21d1ce4e66..d5106925e99 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to22Premium.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade218to22Premium.java @@ -52,7 +52,7 @@ public class Upgrade218to22Premium extends Upgrade218to22 { ) { pstmt.executeUpdate(); - s_logger.debug("Upgraded cloud_usage user_statistics with deviceId"); + logger.debug("Upgraded cloud_usage user_statistics with deviceId"); } catch (Exception e) { throw new CloudRuntimeException("Failed to upgrade user stats: ", e); } @@ -64,7 +64,7 @@ public class Upgrade218to22Premium extends Upgrade218to22 { ) { pstmt1.executeUpdate(); - s_logger.debug("Upgraded cloud_usage usage_network with hostId"); + logger.debug("Upgraded cloud_usage usage_network with hostId"); } catch (Exception e) { throw new CloudRuntimeException("Failed to upgrade network usage stats: ", e); } @@ -78,7 +78,7 @@ public class Upgrade218to22Premium extends Upgrade218to22 { ) { pstmt.executeUpdate(); - s_logger.debug("Upgraded cloud_usage usage_ip_address with Id"); + logger.debug("Upgraded cloud_usage usage_ip_address with Id"); } catch (Exception e) { throw new CloudRuntimeException("Failed to upgrade usage_ip_address: ", e); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2210to2211.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2210to2211.java index db145227080..ba456a62953 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2210to2211.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2210to2211.java @@ -21,7 +21,7 @@ import java.sql.Connection; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade2210to2211 implements DbUpgrade { +public class Upgrade2210to2211 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2211to2212.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2211to2212.java index f8175386df5..1c4868d61b0 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2211to2212.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2211to2212.java @@ -24,12 +24,10 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade2211to2212 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade2211to2212.class); +public class Upgrade2211to2212 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -68,7 +66,7 @@ public class Upgrade2211to2212 implements DbUpgrade { } private void createResourceCount(Connection conn) { - s_logger.debug("Creating missing resource_count records as a part of 2.2.11-2.2.12 upgrade"); + logger.debug("Creating missing resource_count records as a part of 2.2.11-2.2.12 upgrade"); try { //Get all non removed accounts @@ -99,7 +97,7 @@ public class Upgrade2211to2212 implements DbUpgrade { pstmt.setLong(2, accountId); rs = pstmt.executeQuery(); if (!rs.next()) { - s_logger.debug("Inserting resource_count record of type " + resourceType + " for account id=" + accountId); + logger.debug("Inserting resource_count record of type " + resourceType + " for account id=" + accountId); pstmt = conn.prepareStatement("INSERT INTO resource_count (account_id, domain_id, type, count) VALUES (?, null, ?, 0)"); pstmt.setLong(1, accountId); pstmt.setString(2, resourceType); @@ -117,7 +115,7 @@ public class Upgrade2211to2212 implements DbUpgrade { pstmt.setLong(2, domainId); rs = pstmt.executeQuery(); if (!rs.next()) { - s_logger.debug("Inserting resource_count record of type " + resourceType + " for domain id=" + domainId); + logger.debug("Inserting resource_count record of type " + resourceType + " for domain id=" + domainId); pstmt = conn.prepareStatement("INSERT INTO resource_count (account_id, domain_id, type, count) VALUES (null, ?, ?, 0)"); pstmt.setLong(1, domainId); pstmt.setString(2, resourceType); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2211to2212Premium.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2211to2212Premium.java index 37448381136..d2f0f00ee0a 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2211to2212Premium.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2211to2212Premium.java @@ -18,12 +18,10 @@ package com.cloud.upgrade.dao; import java.io.InputStream; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; public class Upgrade2211to2212Premium extends Upgrade2211to2212 { - final static Logger s_logger = Logger.getLogger(Upgrade2211to2212Premium.class); @Override public InputStream[] getPrepareScripts() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2212to2213.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2212to2213.java index 7debe2ec378..809e23c1b5a 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2212to2213.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2212to2213.java @@ -24,12 +24,10 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade2212to2213 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade2212to2213.class); +public class Upgrade2212to2213 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -74,7 +72,7 @@ public class Upgrade2212to2213 implements DbUpgrade { foreignKeys.put("networks", keys); // drop all foreign keys - s_logger.debug("Dropping old key fk_networks__data_center_id..."); + logger.debug("Dropping old key fk_networks__data_center_id..."); for (String tableName : foreignKeys.keySet()) { DbUpgradeUtils.dropKeysIfExist(conn, tableName, foreignKeys.get(tableName), true); } @@ -95,7 +93,7 @@ public class Upgrade2212to2213 implements DbUpgrade { try { PreparedStatement pstmt = conn.prepareStatement("drop index network_offering_id on cloud_usage.usage_network_offering"); pstmt.executeUpdate(); - s_logger.debug("Dropped usage_network_offering unique key"); + logger.debug("Dropped usage_network_offering unique key"); } catch (Exception e) { // Ignore error if the usage_network_offering table or the unique key doesn't exist } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2213to2214.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2213to2214.java index 9dc3f5be2d8..6299abf1030 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2213to2214.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2213to2214.java @@ -23,12 +23,10 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade2213to2214 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade2213to2214.class); +public class Upgrade2213to2214 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2214to30.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2214to30.java index d806490d87d..524b6a34893 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2214to30.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade2214to30.java @@ -29,7 +29,6 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.offering.NetworkOffering; import com.cloud.utils.crypt.DBEncryptionUtil; @@ -37,8 +36,7 @@ import com.cloud.utils.crypt.EncryptionSecretKeyChecker; import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade2214to30.class); +public class Upgrade2214to30 extends Upgrade30xBase { @Override public String[] getUpgradableVersionRange() { @@ -183,7 +181,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt2.setLong(1, zoneId); ResultSet rsTags = pstmt2.executeQuery(); if (rsTags.next()) { - s_logger.debug("Network tags are not empty, might have to create more than one physical network..."); + logger.debug("Network tags are not empty, might have to create more than one physical network..."); //make sure setup does not use guest vnets if (vnet != null) { @@ -214,7 +212,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { + "6. Reconfigure the vnet ranges for each physical network as desired by using updatePhysicalNetwork API \n" + "7. Start all your VMs"; - s_logger.error(message); + logger.error(message); throw new CloudRuntimeException( "Cannot upgrade this setup since it uses guest vnet and will have multiple physical networks. Please check the logs for details on how to proceed"); @@ -263,7 +261,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { if (crtPbNtwk) { addTrafficType(conn, physicalNetworkId, "Public", xenPublicLabel, kvmPublicLabel, vmwarePublicLabel); } else { - s_logger.debug("Skip adding public traffic type to zone id=" + zoneId); + logger.debug("Skip adding public traffic type to zone id=" + zoneId); } addTrafficType(conn, physicalNetworkId, "Management", xenPrivateLabel, kvmPrivateLabel, vmwarePrivateLabel); addTrafficType(conn, physicalNetworkId, "Storage", xenStorageLabel, null, null); @@ -276,9 +274,9 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { PreparedStatement pstmt3 = conn.prepareStatement("SELECT network_id FROM `cloud`.`network_tags` where tag= ?"); pstmt3.setString(1,guestNetworkTag); ResultSet rsNet = pstmt3.executeQuery(); - s_logger.debug("Adding PhysicalNetwork to VLAN"); - s_logger.debug("Adding PhysicalNetwork to user_ip_address"); - s_logger.debug("Adding PhysicalNetwork to networks"); + logger.debug("Adding PhysicalNetwork to VLAN"); + logger.debug("Adding PhysicalNetwork to user_ip_address"); + logger.debug("Adding PhysicalNetwork to networks"); while (rsNet.next()) { Long networkId = rsNet.getLong(1); addPhysicalNtwk_To_Ntwk_IP_Vlan(conn, physicalNetworkId, networkId); @@ -288,7 +286,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { // add the reference to this physical network for the default public network entries in vlan / user_ip_address tables // add first physicalNetworkId to op_dc_vnet_alloc for this zone - just a placeholder since direct networking don't need this if (isFirstPhysicalNtwk) { - s_logger.debug("Adding PhysicalNetwork to default Public network entries in vlan and user_ip_address"); + logger.debug("Adding PhysicalNetwork to default Public network entries in vlan and user_ip_address"); pstmt3 = conn.prepareStatement("SELECT id FROM `cloud`.`networks` where traffic_type = 'Public' and data_center_id = " + zoneId); ResultSet rsPubNet = pstmt3.executeQuery(); if (rsPubNet.next()) { @@ -297,7 +295,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } pstmt3.close(); - s_logger.debug("Adding PhysicalNetwork to op_dc_vnet_alloc"); + logger.debug("Adding PhysicalNetwork to op_dc_vnet_alloc"); String updateVnet = "UPDATE `cloud`.`op_dc_vnet_alloc` SET physical_network_id = " + physicalNetworkId + " WHERE data_center_id = " + zoneId; pstmtUpdate = conn.prepareStatement(updateVnet); pstmtUpdate.executeUpdate(); @@ -314,7 +312,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { if (crtPbNtwk) { addTrafficType(conn, physicalNetworkId, "Public", xenPublicLabel, kvmPublicLabel, vmwarePublicLabel); } else { - s_logger.debug("Skip adding public traffic type to zone id=" + zoneId); + logger.debug("Skip adding public traffic type to zone id=" + zoneId); } addTrafficType(conn, physicalNetworkId, "Management", xenPrivateLabel, kvmPrivateLabel, vmwarePrivateLabel); addTrafficType(conn, physicalNetworkId, "Storage", xenStorageLabel, null, null); @@ -323,28 +321,28 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { addDefaultSGProvider(conn, physicalNetworkId, zoneId, networkType, false); // add physicalNetworkId to op_dc_vnet_alloc for this zone - s_logger.debug("Adding PhysicalNetwork to op_dc_vnet_alloc"); + logger.debug("Adding PhysicalNetwork to op_dc_vnet_alloc"); String updateVnet = "UPDATE `cloud`.`op_dc_vnet_alloc` SET physical_network_id = " + physicalNetworkId + " WHERE data_center_id = " + zoneId; pstmtUpdate = conn.prepareStatement(updateVnet); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); // add physicalNetworkId to vlan for this zone - s_logger.debug("Adding PhysicalNetwork to VLAN"); + logger.debug("Adding PhysicalNetwork to VLAN"); String updateVLAN = "UPDATE `cloud`.`vlan` SET physical_network_id = " + physicalNetworkId + " WHERE data_center_id = " + zoneId; pstmtUpdate = conn.prepareStatement(updateVLAN); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); // add physicalNetworkId to user_ip_address for this zone - s_logger.debug("Adding PhysicalNetwork to user_ip_address"); + logger.debug("Adding PhysicalNetwork to user_ip_address"); String updateUsrIp = "UPDATE `cloud`.`user_ip_address` SET physical_network_id = " + physicalNetworkId + " WHERE data_center_id = " + zoneId; pstmtUpdate = conn.prepareStatement(updateUsrIp); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); // add physicalNetworkId to guest networks for this zone - s_logger.debug("Adding PhysicalNetwork to networks"); + logger.debug("Adding PhysicalNetwork to networks"); String updateNet = "UPDATE `cloud`.`networks` SET physical_network_id = " + physicalNetworkId + " WHERE data_center_id = " + zoneId + " AND traffic_type = 'Guest'"; pstmtUpdate = conn.prepareStatement(updateNet); @@ -370,17 +368,17 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } private void encryptData(Connection conn) { - s_logger.debug("Encrypting the data..."); + logger.debug("Encrypting the data..."); encryptConfigValues(conn); encryptHostDetails(conn); encryptVNCPassword(conn); encryptUserCredentials(conn); encryptVPNPassword(conn); - s_logger.debug("Done encrypting the data"); + logger.debug("Done encrypting the data"); } private void encryptConfigValues(Connection conn) { - s_logger.debug("Encrypting Config values"); + logger.debug("Encrypting Config values"); PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -412,14 +410,14 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.close(); } } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } } - s_logger.debug("Done encrypting Config values"); + logger.debug("Done encrypting Config values"); } private void encryptHostDetails(Connection conn) { - s_logger.debug("Encrypting host details"); + logger.debug("Encrypting host details"); List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; @@ -447,11 +445,11 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } finally { TransactionLegacy.closePstmts(pstmt2Close); } - s_logger.debug("Done encrypting host details"); + logger.debug("Done encrypting host details"); } private void encryptVNCPassword(Connection conn) { - s_logger.debug("Encrypting vm_instance vnc_password"); + logger.debug("Encrypting vm_instance vnc_password"); List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; @@ -493,11 +491,11 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } finally { TransactionLegacy.closePstmts(pstmt2Close); } - s_logger.debug("Done encrypting vm_instance vnc_password"); + logger.debug("Done encrypting vm_instance vnc_password"); } private void encryptUserCredentials(Connection conn) { - s_logger.debug("Encrypting user keys"); + logger.debug("Encrypting user keys"); List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; @@ -526,11 +524,11 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } finally { TransactionLegacy.closePstmts(pstmt2Close); } - s_logger.debug("Done encrypting user keys"); + logger.debug("Done encrypting user keys"); } private void encryptVPNPassword(Connection conn) { - s_logger.debug("Encrypting vpn_users password"); + logger.debug("Encrypting vpn_users password"); List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; ResultSet rs = null; @@ -559,7 +557,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { } finally { TransactionLegacy.closePstmts(pstmt2Close); } - s_logger.debug("Done encrypting vpn_users password"); + logger.debug("Done encrypting vpn_users password"); } private void dropKeysIfExist(Connection conn) { @@ -570,7 +568,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { uniqueKeys.put("secondary_storage_vm", keys); // drop keys - s_logger.debug("Dropping public_ip_address keys from `cloud`.`secondary_storage_vm` and console_proxy tables..."); + logger.debug("Dropping public_ip_address keys from `cloud`.`secondary_storage_vm` and console_proxy tables..."); for (String tableName : uniqueKeys.keySet()) { DbUpgradeUtils.dropKeysIfExist(conn, tableName, uniqueKeys.get(tableName), false); } @@ -697,7 +695,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt2Close.add(pstmt); pstmt.setBoolean(1, subdomainAccess); pstmt.executeUpdate(); - s_logger.debug("Successfully updated subdomain_access field in network_domain table with value " + subdomainAccess); + logger.debug("Successfully updated subdomain_access field in network_domain table with value " + subdomainAccess); } // convert zone level 2.2.x networks to ROOT domain 3.0 access networks @@ -710,7 +708,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt2Close.add(pstmt); pstmt.setLong(1, networkId); pstmt.executeUpdate(); - s_logger.debug("Successfully converted zone specific network id=" + networkId + " to the ROOT domain level network with subdomain access set to true"); + logger.debug("Successfully converted zone specific network id=" + networkId + " to the ROOT domain level network with subdomain access set to true"); } } catch (SQLException e) { @@ -745,7 +743,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.setString(3, provider); pstmt.executeUpdate(); } - s_logger.debug("Created service/provider map for network id=" + networkId); + logger.debug("Created service/provider map for network id=" + networkId); } } catch (SQLException e) { throw new CloudRuntimeException("Unable to create service/provider map for networks", e); @@ -757,7 +755,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { protected void updateRouters(Connection conn) { PreparedStatement pstmt = null; try { - s_logger.debug("Updating domain_router table"); + logger.debug("Updating domain_router table"); pstmt = conn.prepareStatement("UPDATE domain_router, virtual_router_providers vrp LEFT JOIN (physical_network_service_providers pnsp INNER JOIN physical_network pntwk INNER JOIN vm_instance vm INNER JOIN domain_router vr) ON (vrp.nsp_id = pnsp.id AND pnsp.physical_network_id = pntwk.id AND pntwk.data_center_id = vm.data_center_id AND vm.id=vr.id) SET vr.element_id=vrp.id;"); pstmt.executeUpdate(); @@ -793,7 +791,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { ntwkOffCount = rs1.getLong(1); } - s_logger.debug("Have " + ntwkOffCount + " networkOfferings"); + logger.debug("Have " + ntwkOffCount + " networkOfferings"); pstmt = conn.prepareStatement("CREATE TEMPORARY TABLE `cloud`.`network_offerings2` ENGINE=MEMORY SELECT * FROM `cloud`.`network_offerings` WHERE id=1"); pstmt2Close.add(pstmt); pstmt.executeUpdate(); @@ -803,7 +801,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { while (rs.next()) { long networkId = rs.getLong(1); long networkOfferingId = rs.getLong(2); - s_logger.debug("Updating network offering for the network id=" + networkId + " as it has redundant routers"); + logger.debug("Updating network offering for the network id=" + networkId + " as it has redundant routers"); Long newNetworkOfferingId = null; if (!newNetworkOfferingMap.containsKey(networkOfferingId)) { @@ -852,7 +850,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.executeUpdate(); } - s_logger.debug("Successfully updated network offering id=" + networkId + " with new network offering id " + newNetworkOfferingId); + logger.debug("Successfully updated network offering id=" + networkId + " with new network offering id " + newNetworkOfferingId); } } catch (SQLException e) { @@ -863,7 +861,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.executeUpdate(); pstmt.close(); } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } TransactionLegacy.closePstmts(pstmt2Close); } @@ -873,7 +871,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { List pstmt2Close = new ArrayList(); PreparedStatement pstmt = null; try { - s_logger.debug("Updating op_host_capacity table, column capacity_state"); + logger.debug("Updating op_host_capacity table, column capacity_state"); pstmt = conn.prepareStatement("UPDATE op_host_capacity, host SET op_host_capacity.capacity_state='Disabled' where host.id=op_host_capacity.host_id and op_host_capacity.capacity_type in (0,1) and host.resource_state='Disabled';"); pstmt2Close.add(pstmt); @@ -912,7 +910,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt2Close.add(pstmt); rs = pstmt.executeQuery(); } catch (Exception ex) { - s_logger.debug("switch_to_isolated field is not present in networks table"); + logger.debug("switch_to_isolated field is not present in networks table"); if (pstmt != null) { pstmt.close(); } @@ -932,7 +930,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { ntwkOffCount = rs1.getLong(1); } - s_logger.debug("Have " + ntwkOffCount + " networkOfferings"); + logger.debug("Have " + ntwkOffCount + " networkOfferings"); pstmt = conn.prepareStatement("CREATE TEMPORARY TABLE `cloud`.`network_offerings2` ENGINE=MEMORY SELECT * FROM `cloud`.`network_offerings` WHERE id=1"); pstmt2Close.add(pstmt); pstmt.executeUpdate(); @@ -942,7 +940,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { while (rs.next()) { long networkId = rs.getLong(1); long networkOfferingId = rs.getLong(2); - s_logger.debug("Updating network offering for the network id=" + networkId + " as it has switch_to_isolated=1"); + logger.debug("Updating network offering for the network id=" + networkId + " as it has switch_to_isolated=1"); Long newNetworkOfferingId = null; if (!newNetworkOfferingMap.containsKey(networkOfferingId)) { @@ -983,7 +981,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.executeUpdate(); } - s_logger.debug("Successfully updated network offering id=" + networkId + " with new network offering id " + newNetworkOfferingId); + logger.debug("Successfully updated network offering id=" + networkId + " with new network offering id " + newNetworkOfferingId); } try { @@ -992,7 +990,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.executeUpdate(); } catch (SQLException ex) { // do nothing here - s_logger.debug("Caught SQLException when trying to drop switch_to_isolated column ", ex); + logger.debug("Caught SQLException when trying to drop switch_to_isolated column ", ex); } } catch (SQLException e) { @@ -1003,7 +1001,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.executeUpdate(); pstmt.close(); } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } TransactionLegacy.closePstmts(pstmt2Close); } @@ -1057,7 +1055,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.close(); } } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } } } @@ -1107,7 +1105,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { while (rs.next()) { long networkId = rs.getLong(1); long networkOfferingId = rs.getLong(2); - s_logger.debug("Updating network offering for the network id=" + networkId + " as it has switch_to_isolated=1"); + logger.debug("Updating network offering for the network id=" + networkId + " as it has switch_to_isolated=1"); Long newNetworkOfferingId = null; if (!newNetworkOfferingMap.containsKey(networkOfferingId)) { uniqueName = "Isolated with external providers"; @@ -1150,7 +1148,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmt.executeUpdate(); } - s_logger.debug("Successfully updated network id=" + networkId + " with new network offering id " + newNetworkOfferingId); + logger.debug("Successfully updated network id=" + networkId + " with new network offering id " + newNetworkOfferingId); } } catch (SQLException e) { @@ -1159,7 +1157,7 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { try (PreparedStatement dropStatement = conn.prepareStatement("DROP TABLE `cloud`.`network_offerings2`");){ dropStatement.executeUpdate(); } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } TransactionLegacy.closePstmts(pstmt2Close); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade221to222.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade221to222.java index 41198adb14b..307b72c61ea 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade221to222.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade221to222.java @@ -21,7 +21,7 @@ import java.sql.Connection; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade221to222 implements DbUpgrade { +public class Upgrade221to222 extends DbUpgradeAbstractImpl { @Override public InputStream[] getPrepareScripts() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade222to224.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade222to224.java index 51a929d0377..b891b02ea57 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade222to224.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade222to224.java @@ -25,13 +25,11 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.capacity.Capacity; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade222to224 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade222to224.class); +public class Upgrade222to224 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -64,7 +62,7 @@ public class Upgrade222to224 implements DbUpgrade { try { pstmt.executeUpdate(); } catch (SQLException e) { - s_logger.debug("Ignore if the key is not there."); + logger.debug("Ignore if the key is not there."); } pstmt.close(); @@ -130,11 +128,11 @@ public class Upgrade222to224 implements DbUpgrade { } if (zonesWithDuplicateNetworks.size() > 0) { - s_logger.warn(errorMsg + zonesWithDuplicateNetworks); + logger.warn(errorMsg + zonesWithDuplicateNetworks); } } catch (SQLException e) { - s_logger.warn(e); + logger.warn(e); throw new CloudRuntimeException("Unable to check for duplicate public networks as part of 222 to 224 upgrade."); } } @@ -208,21 +206,21 @@ public class Upgrade222to224 implements DbUpgrade { try { pstmtUpdate.close(); } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } } @@ -275,7 +273,7 @@ public class Upgrade222to224 implements DbUpgrade { ResultSet rs1 = pstmt.executeQuery(); if (rs1.next()) { - s_logger.debug("Not updating user_statistics table for domR id=" + instanceId + " as domR is already expunged"); + logger.debug("Not updating user_statistics table for domR id=" + instanceId + " as domR is already expunged"); continue; } @@ -301,7 +299,7 @@ public class Upgrade222to224 implements DbUpgrade { rs.close(); pstmt.close(); - s_logger.debug("Upgraded user_statistics with networkId for DomainRouter device type"); + logger.debug("Upgraded user_statistics with networkId for DomainRouter device type"); // update network_id information for ExternalFirewall and ExternalLoadBalancer device types PreparedStatement pstmt1 = @@ -310,9 +308,9 @@ public class Upgrade222to224 implements DbUpgrade { pstmt1.executeUpdate(); pstmt1.close(); - s_logger.debug("Upgraded user_statistics with networkId for ExternalFirewall and ExternalLoadBalancer device types"); + logger.debug("Upgraded user_statistics with networkId for ExternalFirewall and ExternalLoadBalancer device types"); - s_logger.debug("Successfully update user_statistics table with network_ids as a part of 222 to 224 upgrade"); + logger.debug("Successfully update user_statistics table with network_ids as a part of 222 to 224 upgrade"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to update user_statistics table with network_ids as a part of 222 to 224 upgrade", e); @@ -327,7 +325,7 @@ public class Upgrade222to224 implements DbUpgrade { if (rs.next()) { pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`domain` DROP INDEX `path`"); pstmt.executeUpdate(); - s_logger.debug("Unique key 'path' is removed successfully"); + logger.debug("Unique key 'path' is removed successfully"); } rs.close(); @@ -346,7 +344,7 @@ public class Upgrade222to224 implements DbUpgrade { Long zoneId = rs.getLong(1); Long networkId = null; Long vmCount = 0L; - s_logger.debug("Updating basic zone id=" + zoneId + " with correct nic count"); + logger.debug("Updating basic zone id=" + zoneId + " with correct nic count"); pstmt = conn.prepareStatement("SELECT id from networks where data_center_id=? AND guest_type='Direct'"); pstmt.setLong(1, zoneId); @@ -372,7 +370,7 @@ public class Upgrade222to224 implements DbUpgrade { } - s_logger.debug("Basic zones are updated with correct nic counts successfully"); + logger.debug("Basic zones are updated with correct nic counts successfully"); rs.close(); pstmt.close(); } catch (SQLException e) { @@ -386,7 +384,7 @@ public class Upgrade222to224 implements DbUpgrade { PreparedStatement pstmtUpdate = null; try { // Load all Routing hosts - s_logger.debug("Updating total CPU capacity entries in op_host_capacity"); + logger.debug("Updating total CPU capacity entries in op_host_capacity"); pstmt = conn.prepareStatement("SELECT id, cpus, speed FROM host WHERE type = 'Routing'"); rs = pstmt.executeQuery(); while (rs.next()) { @@ -410,21 +408,21 @@ public class Upgrade222to224 implements DbUpgrade { try { pstmtUpdate.close(); } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } } @@ -439,7 +437,7 @@ public class Upgrade222to224 implements DbUpgrade { if (!rs.next()) { pstmt = conn.prepareStatement("INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (138, 7, 'None')"); pstmt.executeUpdate(); - s_logger.debug("Inserted NONE category to guest_os table"); + logger.debug("Inserted NONE category to guest_os table"); } rs.close(); @@ -488,7 +486,7 @@ public class Upgrade222to224 implements DbUpgrade { try { pstmt.executeUpdate(); } catch (SQLException e) { - s_logger.debug("Ignore if the key is not there."); + logger.debug("Ignore if the key is not there."); } pstmt.close(); } @@ -499,7 +497,7 @@ public class Upgrade222to224 implements DbUpgrade { try { pstmt.executeUpdate(); } catch (SQLException e) { - s_logger.debug("Ignore if the index is not there."); + logger.debug("Ignore if the index is not there."); } pstmt.close(); } @@ -613,7 +611,7 @@ public class Upgrade222to224 implements DbUpgrade { pstmt.close(); - s_logger.debug("Resource limit is cleaned up successfully as a part of db upgrade"); + logger.debug("Resource limit is cleaned up successfully as a part of db upgrade"); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade222to224Premium.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade222to224Premium.java index ac7bd120c3d..cc5d3399fa6 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade222to224Premium.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade222to224Premium.java @@ -20,12 +20,10 @@ import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; public class Upgrade222to224Premium extends Upgrade222to224 { - final static Logger s_logger = Logger.getLogger(Upgrade222to224Premium.class); @Override public InputStream[] getPrepareScripts() { @@ -55,7 +53,7 @@ public class Upgrade222to224Premium extends Upgrade222to224 { ) { pstmt.executeUpdate(); - s_logger.debug("Upgraded cloud_usage user_statistics with networkId"); + logger.debug("Upgraded cloud_usage user_statistics with networkId"); } catch (Exception e) { throw new CloudRuntimeException("Failed to upgrade user stats: ", e); } @@ -66,7 +64,7 @@ public class Upgrade222to224Premium extends Upgrade222to224 { + "us.network_id where us.account_id = un.account_id and us.data_center_id = un.zone_id and us.device_id = un.host_id"); ) { pstmt1.executeUpdate(); - s_logger.debug("Upgraded cloud_usage usage_network with networkId"); + logger.debug("Upgraded cloud_usage usage_network with networkId"); } catch (Exception e) { throw new CloudRuntimeException("Failed to upgrade user stats: ", e); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade224to225.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade224to225.java index 48908f5c7d5..4d88e1a6f40 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade224to225.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade224to225.java @@ -25,12 +25,10 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade224to225 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade224to225.class); +public class Upgrade224to225 extends DbUpgradeAbstractImpl { @Override public InputStream[] getPrepareScripts() { @@ -80,7 +78,7 @@ public class Upgrade224to225 implements DbUpgrade { } private void createSecurityGroups(Connection conn) { - s_logger.debug("Creating missing default security group as a part of 224-225 upgrade"); + logger.debug("Creating missing default security group as a part of 224-225 upgrade"); try { List accounts = new ArrayList(); PreparedStatement pstmt = conn.prepareStatement("SELECT id FROM account WHERE removed IS NULL and id != 1"); @@ -95,7 +93,7 @@ public class Upgrade224to225 implements DbUpgrade { pstmt.setLong(1, accountId); rs = pstmt.executeQuery(); if (!rs.next()) { - s_logger.debug("Default security group is missing for account id=" + accountId + " so adding it"); + logger.debug("Default security group is missing for account id=" + accountId + " so adding it"); // get accountName/domainId information @@ -208,7 +206,7 @@ public class Upgrade224to225 implements DbUpgrade { columns.add("guest_ip_type"); tablesToModify.put("service_offering", columns); - s_logger.debug("Dropping columns that don't exist in 2.2.5 version of the DB..."); + logger.debug("Dropping columns that don't exist in 2.2.5 version of the DB..."); for (String tableName : tablesToModify.keySet()) { DbUpgradeUtils.dropTableColumnsIfExist(conn, tableName, tablesToModify.get(tableName)); } @@ -277,7 +275,7 @@ public class Upgrade224to225 implements DbUpgrade { indexes.put("remote_access_vpn", keys); // drop all foreign keys first - s_logger.debug("Dropping keys that don't exist in 2.2.5 version of the DB..."); + logger.debug("Dropping keys that don't exist in 2.2.5 version of the DB..."); for (String tableName : foreignKeys.keySet()) { DbUpgradeUtils.dropKeysIfExist(conn, tableName, foreignKeys.get(tableName), true); } @@ -291,7 +289,7 @@ public class Upgrade224to225 implements DbUpgrade { private void addMissingKeys(Connection conn) { PreparedStatement pstmt = null; try { - s_logger.debug("Adding missing foreign keys"); + logger.debug("Adding missing foreign keys"); HashMap keyToTableMap = new HashMap(); keyToTableMap.put("fk_console_proxy__id", "console_proxy"); @@ -325,13 +323,13 @@ public class Upgrade224to225 implements DbUpgrade { pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " ADD CONSTRAINT " + key + " FOREIGN KEY " + keyToStatementMap.get(key)); pstmt.executeUpdate(); - s_logger.debug("Added missing key " + key + " to table " + tableName); + logger.debug("Added missing key " + key + " to table " + tableName); rs.close(); } - s_logger.debug("Missing keys were added successfully as a part of 224 to 225 upgrade"); + logger.debug("Missing keys were added successfully as a part of 224 to 225 upgrade"); pstmt.close(); } catch (SQLException e) { - s_logger.error("Unable to add missing foreign key; following statement was executed:" + pstmt); + logger.error("Unable to add missing foreign key; following statement was executed:" + pstmt); throw new CloudRuntimeException("Unable to add missing keys due to exception", e); } } @@ -341,13 +339,13 @@ public class Upgrade224to225 implements DbUpgrade { PreparedStatement pstmt = conn.prepareStatement("SELECT * from ovs_tunnel_account"); ResultSet rs = pstmt.executeQuery(); if (!rs.next()) { - s_logger.debug("Adding missing ovs tunnel account"); + logger.debug("Adding missing ovs tunnel account"); pstmt = conn.prepareStatement("INSERT INTO `cloud`.`ovs_tunnel_account` (`from`, `to`, `account`, `key`, `port_name`, `state`) VALUES (0, 0, 0, 0, 'lock', 'SUCCESS')"); pstmt.executeUpdate(); } } catch (SQLException e) { - s_logger.error("Unable to add missing ovs tunnel account due to ", e); + logger.error("Unable to add missing ovs tunnel account due to ", e); throw new CloudRuntimeException("Unable to add missing ovs tunnel account due to ", e); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade225to226.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade225to226.java index f606d6e756f..99bf1f981da 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade225to226.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade225to226.java @@ -22,12 +22,10 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade225to226 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade225to226.class); +public class Upgrade225to226 extends DbUpgradeAbstractImpl { @Override public InputStream[] getPrepareScripts() { @@ -75,7 +73,7 @@ public class Upgrade225to226 implements DbUpgrade { columns.add("domain_id"); tablesToModify.put("domain_router", columns); - s_logger.debug("Dropping columns that don't exist in 2.2.6 version of the DB..."); + logger.debug("Dropping columns that don't exist in 2.2.6 version of the DB..."); for (String tableName : tablesToModify.keySet()) { DbUpgradeUtils.dropTableColumnsIfExist(conn, tableName, tablesToModify.get(tableName)); } @@ -95,7 +93,7 @@ public class Upgrade225to226 implements DbUpgrade { indexes.put("domain_router", keys); // drop all foreign keys first - s_logger.debug("Dropping keys that don't exist in 2.2.6 version of the DB..."); + logger.debug("Dropping keys that don't exist in 2.2.6 version of the DB..."); for (String tableName : foreignKeys.keySet()) { DbUpgradeUtils.dropKeysIfExist(conn, tableName, foreignKeys.get(tableName), true); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade227to228.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade227to228.java index 7d665718db4..3c85ee21d1b 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade227to228.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade227to228.java @@ -23,12 +23,10 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade227to228 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade227to228.class); +public class Upgrade227to228 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -79,7 +77,7 @@ public class Upgrade227to228 implements DbUpgrade { pstmt.executeUpdate(); } catch (SQLException e) { - s_logger.error("Failed to DB migration for multiple secondary storages", e); + logger.error("Failed to DB migration for multiple secondary storages", e); throw new CloudRuntimeException("Failed to DB migration for multiple secondary storages", e); } @@ -93,7 +91,7 @@ public class Upgrade227to228 implements DbUpgrade { } private void updateDomainLevelNetworks(Connection conn) { - s_logger.debug("Updating domain level specific networks..."); + logger.debug("Updating domain level specific networks..."); try { PreparedStatement pstmt = conn.prepareStatement("SELECT n.id FROM networks n, network_offerings o WHERE n.shared=1 AND o.system_only=0 AND o.id=n.network_offering_id"); @@ -113,7 +111,7 @@ public class Upgrade227to228 implements DbUpgrade { pstmt.setLong(1, networkId); rs = pstmt.executeQuery(); if (rs.next()) { - s_logger.debug("Setting network id=" + networkId + " as domain specific shared network"); + logger.debug("Setting network id=" + networkId + " as domain specific shared network"); pstmt = conn.prepareStatement("UPDATE networks set is_domain_specific=1 where id=?"); pstmt.setLong(1, networkId); pstmt.executeUpdate(); @@ -122,9 +120,9 @@ public class Upgrade227to228 implements DbUpgrade { pstmt.close(); } - s_logger.debug("Successfully updated domain level specific networks"); + logger.debug("Successfully updated domain level specific networks"); } catch (SQLException e) { - s_logger.error("Failed to set domain specific shared networks due to ", e); + logger.error("Failed to set domain specific shared networks due to ", e); throw new CloudRuntimeException("Failed to set domain specific shared networks due to ", e); } } @@ -132,7 +130,7 @@ public class Upgrade227to228 implements DbUpgrade { //this method inserts missing volume.delete events (events were missing when vm failed to create) private void updateVolumeUsageRecords(Connection conn) { try { - s_logger.debug("Inserting missing usage_event records for destroyed volumes..."); + logger.debug("Inserting missing usage_event records for destroyed volumes..."); PreparedStatement pstmt = conn.prepareStatement("select id, account_id, data_center_id, name from volumes where state='Destroy' and id in (select resource_id from usage_event where type='volume.create') and id not in (select resource_id from usage_event where type='volume.delete')"); ResultSet rs = pstmt.executeQuery(); @@ -151,9 +149,9 @@ public class Upgrade227to228 implements DbUpgrade { pstmt.executeUpdate(); } - s_logger.debug("Successfully inserted missing usage_event records for destroyed volumes"); + logger.debug("Successfully inserted missing usage_event records for destroyed volumes"); } catch (SQLException e) { - s_logger.error("Failed to insert missing delete usage records ", e); + logger.error("Failed to insert missing delete usage records ", e); throw new CloudRuntimeException("Failed to insert missing delete usage records ", e); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade227to228Premium.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade227to228Premium.java index 032fb58da86..4787017ce4b 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade227to228Premium.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade227to228Premium.java @@ -22,12 +22,10 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; public class Upgrade227to228Premium extends Upgrade227to228 { - final static Logger s_logger = Logger.getLogger(Upgrade227to228Premium.class); @Override public InputStream[] getPrepareScripts() { @@ -59,7 +57,7 @@ public class Upgrade227to228Premium extends Upgrade227to228 { ResultSet rs = pstmt.executeQuery(); if (rs.next()) { - s_logger.info("The source id field already exist, not adding it"); + logger.info("The source id field already exist, not adding it"); } } catch (Exception e) { @@ -68,21 +66,21 @@ public class Upgrade227to228Premium extends Upgrade227to228 { } if (insertField) { - s_logger.debug("Adding source_id to usage_storage..."); + logger.debug("Adding source_id to usage_storage..."); pstmt = conn.prepareStatement("ALTER TABLE `cloud_usage`.`usage_storage` ADD COLUMN `source_id` bigint unsigned"); pstmt.executeUpdate(); - s_logger.debug("Column source_id was added successfully to usage_storage table"); + logger.debug("Column source_id was added successfully to usage_storage table"); pstmt.close(); } } catch (SQLException e) { - s_logger.error("Failed to add source_id to usage_storage due to ", e); + logger.error("Failed to add source_id to usage_storage due to ", e); throw new CloudRuntimeException("Failed to add source_id to usage_storage due to ", e); } } private void addNetworkIdsToUserStats(Connection conn) { - s_logger.debug("Adding network IDs to user stats..."); + logger.debug("Adding network IDs to user stats..."); try { String stmt = "SELECT DISTINCT public_ip_address FROM `cloud`.`user_statistics` WHERE public_ip_address IS NOT null"; PreparedStatement pstmt = conn.prepareStatement(stmt); @@ -112,10 +110,10 @@ public class Upgrade227to228Premium extends Upgrade227to228 { rs.close(); pstmt.close(); - s_logger.debug("Successfully added network IDs to user stats."); + logger.debug("Successfully added network IDs to user stats."); } catch (SQLException e) { String errorMsg = "Failed to add network IDs to user stats."; - s_logger.error(errorMsg, e); + logger.error(errorMsg, e); throw new CloudRuntimeException(errorMsg, e); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade228to229.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade228to229.java index c556cd90089..bd95a067129 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade228to229.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade228to229.java @@ -24,12 +24,10 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade228to229 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade228to229.class); +public class Upgrade228to229 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -126,7 +124,7 @@ public class Upgrade228to229 implements DbUpgrade { foreignKeys.put("network_tags", keys); // drop all foreign keys first - s_logger.debug("Dropping keys that don't exist in 2.2.6 version of the DB..."); + logger.debug("Dropping keys that don't exist in 2.2.6 version of the DB..."); for (String tableName : foreignKeys.keySet()) { DbUpgradeUtils.dropKeysIfExist(conn, tableName, foreignKeys.get(tableName), true); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade229to2210.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade229to2210.java index 1ad7e6d2b4c..3d4725c108f 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade229to2210.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade229to2210.java @@ -23,12 +23,10 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade229to2210 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade229to2210.class); +public class Upgrade229to2210 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -128,7 +126,7 @@ public class Upgrade229to2210 implements DbUpgrade { pstmt.setString(8, UUID.randomUUID().toString()); pstmt.setLong(9, id); - s_logger.debug("Updating firewall rule with the statement " + pstmt); + logger.debug("Updating firewall rule with the statement " + pstmt); pstmt.executeUpdate(); //get new FirewallRule update @@ -159,12 +157,12 @@ public class Upgrade229to2210 implements DbUpgrade { pstmt = conn.prepareStatement("update firewall_rules_cidrs set firewall_rule_id=? where firewall_rule_id=?"); pstmt.setLong(1, firewallRuleId); pstmt.setLong(2, id); - s_logger.debug("Updating existing cidrs for the rule id=" + id + " with the new Firewall rule id=" + firewallRuleId + " with statement" + pstmt); + logger.debug("Updating existing cidrs for the rule id=" + id + " with the new Firewall rule id=" + firewallRuleId + " with statement" + pstmt); pstmt.executeUpdate(); } else { pstmt = conn.prepareStatement("insert into firewall_rules_cidrs (firewall_rule_id,source_cidr) values (?, '0.0.0.0/0')"); pstmt.setLong(1, firewallRuleId); - s_logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + pstmt); + logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + pstmt); pstmt.executeUpdate(); } } @@ -180,7 +178,7 @@ public class Upgrade229to2210 implements DbUpgrade { pstmt.close(); } } catch (SQLException e) { - s_logger.info("[ignored]",e); + logger.info("[ignored]",e); } } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade301to302.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade301to302.java index ba479b52f89..28e8d89dff0 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade301to302.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade301to302.java @@ -26,12 +26,10 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; public class Upgrade301to302 extends LegacyDbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade301to302.class); @Override public String[] getUpgradableVersionRange() { @@ -66,7 +64,7 @@ public class Upgrade301to302 extends LegacyDbUpgrade { keys.add("i_host__allocation_state"); uniqueKeys.put("host", keys); - s_logger.debug("Dropping i_host__allocation_state key in host table"); + logger.debug("Dropping i_host__allocation_state key in host table"); for (String tableName : uniqueKeys.keySet()) { DbUpgradeUtils.dropKeysIfExist(conn, tableName, uniqueKeys.get(tableName), false); } @@ -129,7 +127,7 @@ public class Upgrade301to302 extends LegacyDbUpgrade { pstmt = conn.prepareStatement("DELETE FROM `cloud`.`ntwk_offering_service_map` WHERE id=?"); pstmt.setLong(1, mapId); pstmt.executeUpdate(); - s_logger.debug("Deleted lb service for network offering id=" + ntwkOffId + " as it doesn't have source nat service enabled"); + logger.debug("Deleted lb service for network offering id=" + ntwkOffId + " as it doesn't have source nat service enabled"); //delete lb service for the network pstmt = @@ -144,7 +142,7 @@ public class Upgrade301to302 extends LegacyDbUpgrade { pstmt = conn.prepareStatement("DELETE FROM `cloud`.`ntwk_service_map` WHERE id=?"); pstmt.setLong(1, mapId); pstmt.executeUpdate(); - s_logger.debug("Deleted lb service for network id=" + ntwkId + " as it doesn't have source nat service enabled"); + logger.debug("Deleted lb service for network id=" + ntwkId + " as it doesn't have source nat service enabled"); } } @@ -180,14 +178,14 @@ public class Upgrade301to302 extends LegacyDbUpgrade { } private void changeEngine(Connection conn) { - s_logger.debug("Fixing engine and row_format for op_lock and op_nwgrp_work tables"); + logger.debug("Fixing engine and row_format for op_lock and op_nwgrp_work tables"); String sqlOpLock = "ALTER TABLE `cloud`.`op_lock` ENGINE=MEMORY, ROW_FORMAT = FIXED"; try ( PreparedStatement pstmt = conn.prepareStatement(sqlOpLock); ) { pstmt.executeUpdate(); } catch (Exception e) { - s_logger.debug("Failed do execute the statement " + sqlOpLock + ", moving on as it's not critical fix"); + logger.debug("Failed do execute the statement " + sqlOpLock + ", moving on as it's not critical fix"); } String sqlOpNwgrpWork = "ALTER TABLE `cloud`.`op_nwgrp_work` ENGINE=MEMORY, ROW_FORMAT = FIXED"; @@ -196,7 +194,7 @@ public class Upgrade301to302 extends LegacyDbUpgrade { ) { pstmt.executeUpdate(); } catch (Exception e) { - s_logger.debug("Failed do execute the statement " + sqlOpNwgrpWork + ", moving on as it's not critical fix"); + logger.debug("Failed do execute the statement " + sqlOpNwgrpWork + ", moving on as it's not critical fix"); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade302to303.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade302to303.java index e07c98dd448..91b9b3849a8 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade302to303.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade302to303.java @@ -28,14 +28,12 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; public class Upgrade302to303 extends LegacyDbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade302to303.class); @Override public String[] getUpgradableVersionRange() { @@ -142,7 +140,7 @@ public class Upgrade302to303 extends LegacyDbUpgrade { private void addF5LoadBalancer(Connection conn, long hostId, long physicalNetworkId) { PreparedStatement pstmtUpdate = null; try { - s_logger.debug("Adding F5 Big IP load balancer with host id " + hostId + " in to physical network" + physicalNetworkId); + logger.debug("Adding F5 Big IP load balancer with host id " + hostId + " in to physical network" + physicalNetworkId); String insertF5 = "INSERT INTO `cloud`.`external_load_balancer_devices` (physical_network_id, host_id, provider_name, " + "device_name, capacity, is_dedicated, device_state, allocation_state, is_inline, is_managed, uuid) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; @@ -169,7 +167,7 @@ public class Upgrade302to303 extends LegacyDbUpgrade { private void addSrxFirewall(Connection conn, long hostId, long physicalNetworkId) { PreparedStatement pstmtUpdate = null; try { - s_logger.debug("Adding SRX firewall device with host id " + hostId + " in to physical network" + physicalNetworkId); + logger.debug("Adding SRX firewall device with host id " + hostId + " in to physical network" + physicalNetworkId); String insertSrx = "INSERT INTO `cloud`.`external_firewall_devices` (physical_network_id, host_id, provider_name, " + "device_name, capacity, is_dedicated, device_state, allocation_state, uuid) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?)"; @@ -195,7 +193,7 @@ public class Upgrade302to303 extends LegacyDbUpgrade { PreparedStatement pstmtUpdate = null; try { // add physical network service provider - F5BigIp - s_logger.debug("Adding PhysicalNetworkServiceProvider F5BigIp" + " in to physical network" + physicalNetworkId); + logger.debug("Adding PhysicalNetworkServiceProvider F5BigIp" + " in to physical network" + physicalNetworkId); String insertPNSP = "INSERT INTO `cloud`.`physical_network_service_providers` (`uuid`, `physical_network_id` , `provider_name`, `state` ," + "`destination_physical_network_id`, `vpn_service_provided`, `dhcp_service_provided`, `dns_service_provided`, `gateway_service_provided`," @@ -219,7 +217,7 @@ public class Upgrade302to303 extends LegacyDbUpgrade { PreparedStatement pstmtUpdate = null; try { // add physical network service provider - JuniperSRX - s_logger.debug("Adding PhysicalNetworkServiceProvider JuniperSRX"); + logger.debug("Adding PhysicalNetworkServiceProvider JuniperSRX"); String insertPNSP = "INSERT INTO `cloud`.`physical_network_service_providers` (`uuid`, `physical_network_id` , `provider_name`, `state` ," + "`destination_physical_network_id`, `vpn_service_provided`, `dhcp_service_provided`, `dns_service_provided`, `gateway_service_provided`," @@ -241,7 +239,7 @@ public class Upgrade302to303 extends LegacyDbUpgrade { private void encryptConfig(Connection conn) { //Encrypt config params and change category to Hidden - s_logger.debug("Encrypting Config values"); + logger.debug("Encrypting Config values"); PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -268,7 +266,7 @@ public class Upgrade302to303 extends LegacyDbUpgrade { closeAutoCloseable(rs); closeAutoCloseable(pstmt); } - s_logger.debug("Done encrypting Config values"); + logger.debug("Done encrypting Config values"); } @Override diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade302to40.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade302to40.java index eb0492cd288..aa427252585 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade302to40.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade302to40.java @@ -27,14 +27,12 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; public class Upgrade302to40 extends Upgrade30xBase { - final static Logger s_logger = Logger.getLogger(Upgrade302to40.class); @Override public String[] getUpgradableVersionRange() { @@ -211,9 +209,9 @@ public class Upgrade302to40 extends Upgrade30xBase { if (rsSameLabel.next()) { Long sameLabelcount = rsSameLabel.getLong(1); if (sameLabelcount > 0) { - s_logger.error("There are untagged networks for which we need to add a physical network with Xen traffic label = 'xen.guest.network.device' config value, which is: " + + logger.error("There are untagged networks for which we need to add a physical network with Xen traffic label = 'xen.guest.network.device' config value, which is: " + xenGuestLabel); - s_logger.error("However already there are " + sameLabelcount + " physical networks setup with same traffic label, cannot upgrade"); + logger.error("However already there are " + sameLabelcount + " physical networks setup with same traffic label, cannot upgrade"); throw new CloudRuntimeException("Cannot upgrade this setup since a physical network with same traffic label: " + xenGuestLabel + " already exists, Please check logs and contact Support."); } @@ -230,9 +228,9 @@ public class Upgrade302to40 extends Upgrade30xBase { conn.prepareStatement("SELECT n.id FROM networks n WHERE n.physical_network_id IS NULL AND n.traffic_type = 'Guest' and n.data_center_id = ? and n.removed is null"); pstmt3.setLong(1, zoneId); ResultSet rsNet = pstmt3.executeQuery(); - s_logger.debug("Adding PhysicalNetwork to VLAN"); - s_logger.debug("Adding PhysicalNetwork to user_ip_address"); - s_logger.debug("Adding PhysicalNetwork to networks"); + logger.debug("Adding PhysicalNetwork to VLAN"); + logger.debug("Adding PhysicalNetwork to user_ip_address"); + logger.debug("Adding PhysicalNetwork to networks"); while (rsNet.next()) { Long networkId = rsNet.getLong(1); addPhysicalNtwk_To_Ntwk_IP_Vlan(conn, physicalNetworkId, networkId); @@ -253,7 +251,7 @@ public class Upgrade302to40 extends Upgrade30xBase { if (rs.next()) { Long count = rs.getLong(1); if (count > 1) { - s_logger.debug("There are " + count + " physical networks setup"); + logger.debug("There are " + count + " physical networks setup"); multiplePhysicalNetworks = true; } } @@ -272,7 +270,7 @@ public class Upgrade302to40 extends Upgrade30xBase { String networkId = rsVNet.getString(5); String vpid = rsVNet.getString(4); String npid = rsVNet.getString(6); - s_logger.error("Guest Vnet assignment is set wrongly . Cannot upgrade until that is corrected. Example- Vnet: " + vnet + + logger.error("Guest Vnet assignment is set wrongly . Cannot upgrade until that is corrected. Example- Vnet: " + vnet + " has physical network id: " + vpid + " ,but the guest network: " + networkId + " that uses it has physical network id: " + npid); String message = "Cannot upgrade. Your setup has multiple Physical Networks and is using guest Vnet that is assigned wrongly. " @@ -291,7 +289,7 @@ public class Upgrade302to40 extends Upgrade30xBase { + "5. Run upgrade. This will allocate all your guest vnet range to first physical network. \n" + "6. Reconfigure the vnet ranges for each physical network as desired by using updatePhysicalNetwork API \n" + "7. Start all your VMs"; - s_logger.error(message); + logger.error(message); throw new CloudRuntimeException("Cannot upgrade this setup since Guest Vnet assignment to the multiple physical " + "networks is incorrect. Please check the logs for details on how to proceed"); @@ -470,26 +468,26 @@ public class Upgrade302to40 extends Upgrade30xBase { pstmt = conn.prepareStatement("DROP TEMPORARY TABLE `cloud`.`network_offerings2`"); pstmt.executeUpdate(); } catch (SQLException e) { - s_logger.info("[ignored] ",e); + logger.info("[ignored] ",e); } closeAutoCloseable(pstmt); } } private void addHostDetailsUniqueKey(Connection conn) { - s_logger.debug("Checking if host_details unique key exists, if not we will add it"); + logger.debug("Checking if host_details unique key exists, if not we will add it"); try ( PreparedStatement pstmt = conn.prepareStatement("SHOW INDEX FROM `cloud`.`host_details` WHERE KEY_NAME = 'uk_host_id_name'"); ResultSet rs = pstmt.executeQuery(); ) { if (rs.next()) { - s_logger.debug("Unique key already exists on host_details - not adding new one"); + logger.debug("Unique key already exists on host_details - not adding new one"); } else { //add the key PreparedStatement pstmtUpdate = conn.prepareStatement("ALTER IGNORE TABLE `cloud`.`host_details` ADD CONSTRAINT UNIQUE KEY `uk_host_id_name` (`host_id`, `name`)"); pstmtUpdate.executeUpdate(); - s_logger.debug("Unique key did not exist on host_details - added new one"); + logger.debug("Unique key did not exist on host_details - added new one"); pstmtUpdate.close(); } } catch (SQLException e) { @@ -499,7 +497,7 @@ public class Upgrade302to40 extends Upgrade30xBase { private void addVpcProvider(Connection conn) { //Encrypt config params and change category to Hidden - s_logger.debug("Adding vpc provider to all physical networks in the system"); + logger.debug("Adding vpc provider to all physical networks in the system"); PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -534,7 +532,7 @@ public class Upgrade302to40 extends Upgrade30xBase { pstmt.setLong(1, providerId); pstmt.executeUpdate(); - s_logger.debug("Added VPC Virtual router provider for physical network id=" + pNtwkId); + logger.debug("Added VPC Virtual router provider for physical network id=" + pNtwkId); } } catch (SQLException e) { @@ -543,12 +541,12 @@ public class Upgrade302to40 extends Upgrade30xBase { closeAutoCloseable(rs); closeAutoCloseable(pstmt); } - s_logger.debug("Done adding VPC physical network service providers to all physical networks"); + logger.debug("Done adding VPC physical network service providers to all physical networks"); } private void updateRouterNetworkRef(Connection conn) { //Encrypt config params and change category to Hidden - s_logger.debug("Updating router network ref"); + logger.debug("Updating router network ref"); try ( PreparedStatement pstmt = conn.prepareStatement("SELECT d.id, d.network_id FROM `cloud`.`domain_router` d, `cloud`.`vm_instance` v " + "WHERE d.id=v.id AND v.removed is NULL"); PreparedStatement pstmt1 = conn.prepareStatement("SELECT guest_type from `cloud`.`networks` where id=?"); @@ -571,13 +569,13 @@ public class Upgrade302to40 extends Upgrade30xBase { pstmt2.setString(3, networkType); pstmt2.executeUpdate(); } - s_logger.debug("Added reference for router id=" + routerId + " and network id=" + networkId); + logger.debug("Added reference for router id=" + routerId + " and network id=" + networkId); } } catch (SQLException e) { throw new CloudRuntimeException("Failed to update the router/network reference ", e); } - s_logger.debug("Done updating router/network references"); + logger.debug("Done updating router/network references"); } private void fixForeignKeys(Connection conn) { @@ -693,7 +691,7 @@ public class Upgrade302to40 extends Upgrade30xBase { } private void addF5LoadBalancer(Connection conn, long hostId, long physicalNetworkId) { - s_logger.debug("Adding F5 Big IP load balancer with host id " + hostId + " in to physical network" + physicalNetworkId); + logger.debug("Adding F5 Big IP load balancer with host id " + hostId + " in to physical network" + physicalNetworkId); String insertF5 = "INSERT INTO `cloud`.`external_load_balancer_devices` (physical_network_id, host_id, provider_name, " + "device_name, capacity, is_dedicated, device_state, allocation_state, is_inline, is_managed, uuid) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; @@ -716,7 +714,7 @@ public class Upgrade302to40 extends Upgrade30xBase { } private void addSrxFirewall(Connection conn, long hostId, long physicalNetworkId) { - s_logger.debug("Adding SRX firewall device with host id " + hostId + " in to physical network" + physicalNetworkId); + logger.debug("Adding SRX firewall device with host id " + hostId + " in to physical network" + physicalNetworkId); String insertSrx = "INSERT INTO `cloud`.`external_firewall_devices` (physical_network_id, host_id, provider_name, " + "device_name, capacity, is_dedicated, device_state, allocation_state, uuid) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?)"; @@ -738,7 +736,7 @@ public class Upgrade302to40 extends Upgrade30xBase { private void addF5ServiceProvider(Connection conn, long physicalNetworkId, long zoneId) { // add physical network service provider - F5BigIp - s_logger.debug("Adding PhysicalNetworkServiceProvider F5BigIp" + " in to physical network" + physicalNetworkId); + logger.debug("Adding PhysicalNetworkServiceProvider F5BigIp" + " in to physical network" + physicalNetworkId); String insertPNSP = "INSERT INTO `cloud`.`physical_network_service_providers` (`uuid`, `physical_network_id` , `provider_name`, `state` ," + "`destination_physical_network_id`, `vpn_service_provided`, `dhcp_service_provided`, `dns_service_provided`, `gateway_service_provided`," @@ -757,7 +755,7 @@ public class Upgrade302to40 extends Upgrade30xBase { private void addSrxServiceProvider(Connection conn, long physicalNetworkId, long zoneId) { // add physical network service provider - JuniperSRX - s_logger.debug("Adding PhysicalNetworkServiceProvider JuniperSRX"); + logger.debug("Adding PhysicalNetworkServiceProvider JuniperSRX"); String insertPNSP = "INSERT INTO `cloud`.`physical_network_service_providers` (`uuid`, `physical_network_id` , `provider_name`, `state` ," + "`destination_physical_network_id`, `vpn_service_provided`, `dhcp_service_provided`, `dns_service_provided`, `gateway_service_provided`," @@ -875,7 +873,7 @@ public class Upgrade302to40 extends Upgrade30xBase { pstmtUpdate.setLong(2, networkId); pstmtUpdate.setLong(3, f5DeviceId); pstmtUpdate.executeUpdate(); - s_logger.debug("Successfully added entry in network_external_lb_device_map for network " + networkId + " and F5 device ID " + f5DeviceId); + logger.debug("Successfully added entry in network_external_lb_device_map for network " + networkId + " and F5 device ID " + f5DeviceId); // add mapping for the network in network_external_firewall_device_map String insertFwMapping = @@ -885,11 +883,11 @@ public class Upgrade302to40 extends Upgrade30xBase { pstmtUpdate.setLong(2, networkId); pstmtUpdate.setLong(3, srxDevivceId); pstmtUpdate.executeUpdate(); - s_logger.debug("Successfully added entry in network_external_firewall_device_map for network " + networkId + " and SRX device ID " + srxDevivceId); + logger.debug("Successfully added entry in network_external_firewall_device_map for network " + networkId + " and SRX device ID " + srxDevivceId); } // update host details for F5 and SRX devices - s_logger.debug("Updating the host details for F5 and SRX devices"); + logger.debug("Updating the host details for F5 and SRX devices"); pstmt = conn.prepareStatement("SELECT host_id, name FROM `cloud`.`host_details` WHERE host_id=? OR host_id=?"); pstmt.setLong(1, f5HostId); pstmt.setLong(2, srxHostId); @@ -908,20 +906,20 @@ public class Upgrade302to40 extends Upgrade30xBase { pstmt.setString(3, camlCaseName); pstmt.executeUpdate(); } - s_logger.debug("Successfully updated host details for F5 and SRX devices"); + logger.debug("Successfully updated host details for F5 and SRX devices"); } catch (SQLException e) { throw new CloudRuntimeException("Unable create a mapping for the networks in network_external_lb_device_map and network_external_firewall_device_map", e); } finally { closeAutoCloseable(rs); closeAutoCloseable(pstmt); } - s_logger.info("Successfully upgraded networks using F5 and SRX devices to have a entry in the network_external_lb_device_map and network_external_firewall_device_map"); + logger.info("Successfully upgraded networks using F5 and SRX devices to have a entry in the network_external_lb_device_map and network_external_firewall_device_map"); } } private void encryptConfig(Connection conn) { //Encrypt config params and change category to Hidden - s_logger.debug("Encrypting Config values"); + logger.debug("Encrypting Config values"); try ( PreparedStatement pstmt = conn.prepareStatement("select name, value from `cloud`.`configuration` where name in ('router.ram.size', 'secondary.storage.vm', 'security.hash.key') and category <> 'Hidden'"); PreparedStatement pstmt1 = conn.prepareStatement("update `cloud`.`configuration` set value=?, category = 'Hidden' where name=?"); @@ -943,11 +941,11 @@ public class Upgrade302to40 extends Upgrade30xBase { } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt configuration values ", e); } - s_logger.debug("Done encrypting Config values"); + logger.debug("Done encrypting Config values"); } private void encryptClusterDetails(Connection conn) { - s_logger.debug("Encrypting cluster details"); + logger.debug("Encrypting cluster details"); try ( PreparedStatement pstmt = conn.prepareStatement("select id, value from `cloud`.`cluster_details` where name = 'password'"); PreparedStatement pstmt1 = conn.prepareStatement("update `cloud`.`cluster_details` set value=? where id=?"); @@ -969,6 +967,6 @@ public class Upgrade302to40 extends Upgrade30xBase { } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt cluster_details values ", e); } - s_logger.debug("Done encrypting cluster_details"); + logger.debug("Done encrypting cluster_details"); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade303to304.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade303to304.java index 03f69ddefc9..d713a1c8592 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade303to304.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade303to304.java @@ -24,13 +24,11 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade303to304 extends Upgrade30xBase implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade303to304.class); +public class Upgrade303to304 extends Upgrade30xBase { @Override public String[] getUpgradableVersionRange() { @@ -171,9 +169,9 @@ public class Upgrade303to304 extends Upgrade30xBase implements DbUpgrade { if (rsSameLabel.next()) { Long sameLabelcount = rsSameLabel.getLong(1); if (sameLabelcount > 0) { - s_logger.error("There are untagged networks for which we need to add a physical network with Xen traffic label = 'xen.guest.network.device' config value, which is: " + + logger.error("There are untagged networks for which we need to add a physical network with Xen traffic label = 'xen.guest.network.device' config value, which is: " + xenGuestLabel); - s_logger.error("However already there are " + sameLabelcount + " physical networks setup with same traffic label, cannot upgrade"); + logger.error("However already there are " + sameLabelcount + " physical networks setup with same traffic label, cannot upgrade"); throw new CloudRuntimeException("Cannot upgrade this setup since a physical network with same traffic label: " + xenGuestLabel + " already exists, Please check logs and contact Support."); } @@ -188,9 +186,9 @@ public class Upgrade303to304 extends Upgrade30xBase implements DbUpgrade { pstmt_network_id.setLong(1, zoneId); try (ResultSet rsNet = pstmt_network_id.executeQuery();) { - s_logger.debug("Adding PhysicalNetwork to VLAN"); - s_logger.debug("Adding PhysicalNetwork to user_ip_address"); - s_logger.debug("Adding PhysicalNetwork to networks"); + logger.debug("Adding PhysicalNetwork to VLAN"); + logger.debug("Adding PhysicalNetwork to user_ip_address"); + logger.debug("Adding PhysicalNetwork to networks"); while (rsNet.next()) { Long networkId = rsNet.getLong(1); addPhysicalNtwk_To_Ntwk_IP_Vlan(conn, physicalNetworkId, networkId); @@ -207,7 +205,7 @@ public class Upgrade303to304 extends Upgrade30xBase implements DbUpgrade { if (rs.next()) { Long count = rs.getLong(1); if (count > 1) { - s_logger.debug("There are " + count + " physical networks setup"); + logger.debug("There are " + count + " physical networks setup"); multiplePhysicalNetworks = true; } } @@ -223,7 +221,7 @@ public class Upgrade303to304 extends Upgrade30xBase implements DbUpgrade { String networkId = rsVNet.getString(5); String vpid = rsVNet.getString(4); String npid = rsVNet.getString(6); - s_logger.error("Guest Vnet assignment is set wrongly . Cannot upgrade until that is corrected. Example- Vnet: " + vnet + + logger.error("Guest Vnet assignment is set wrongly . Cannot upgrade until that is corrected. Example- Vnet: " + vnet + " has physical network id: " + vpid + " ,but the guest network: " + networkId + " that uses it has physical network id: " + npid); String message = "Cannot upgrade. Your setup has multiple Physical Networks and is using guest Vnet that is assigned wrongly. " @@ -242,7 +240,7 @@ public class Upgrade303to304 extends Upgrade30xBase implements DbUpgrade { + "5. Run upgrade. This will allocate all your guest vnet range to first physical network. \n" + "6. Reconfigure the vnet ranges for each physical network as desired by using updatePhysicalNetwork API \n" + "7. Start all your VMs"; - s_logger.error(message); + logger.error(message); throw new CloudRuntimeException("Cannot upgrade this setup since Guest Vnet assignment to the multiple physical networks " + "is incorrect. Please check the logs for details on how to proceed"); @@ -383,7 +381,7 @@ public class Upgrade303to304 extends Upgrade30xBase implements DbUpgrade { try (PreparedStatement pstmt_drop_table = conn.prepareStatement("DROP TEMPORARY TABLE `cloud`.`network_offerings2`");) { pstmt_drop_table.executeUpdate(); } catch (SQLException e) { - s_logger.debug("drop of temp table 'network_offerings2' failed", e); + logger.debug("drop of temp table 'network_offerings2' failed", e); } } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade304to305.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade304to305.java index a8009630976..bb4c73f67b6 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade304to305.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade304to305.java @@ -27,13 +27,11 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; public class Upgrade304to305 extends Upgrade30xBase { - final static Logger s_logger = Logger.getLogger(Upgrade304to305.class); @Override public String[] getUpgradableVersionRange() { @@ -99,7 +97,7 @@ public class Upgrade304to305 extends Upgrade30xBase { throw new CloudRuntimeException("Error while iterating through list of hypervisors in use", e); } // Just update the VMware system template. Other hypervisor templates are unchanged from previous 3.0.x versions. - s_logger.debug("Updating VMware System Vms"); + logger.debug("Updating VMware System Vms"); try { //Get 3.0.5 VMware system Vm template Id pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = 'systemvm-vmware-3.0.5' and removed is null"); @@ -122,18 +120,18 @@ public class Upgrade304to305 extends Upgrade30xBase { if (VMware) { throw new CloudRuntimeException("3.0.5 VMware SystemVm template not found. Cannot upgrade system Vms"); } else { - s_logger.warn("3.0.5 VMware SystemVm template not found. VMware hypervisor is not used, so not failing upgrade"); + logger.warn("3.0.5 VMware SystemVm template not found. VMware hypervisor is not used, so not failing upgrade"); } } } catch (SQLException e) { throw new CloudRuntimeException("Error while updating VMware systemVm template", e); } - s_logger.debug("Updating System Vm Template IDs Complete"); + logger.debug("Updating System Vm Template IDs Complete"); } private void addVpcProvider(Connection conn) { //Encrypt config params and change category to Hidden - s_logger.debug("Adding vpc provider to all physical networks in the system"); + logger.debug("Adding vpc provider to all physical networks in the system"); PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -168,7 +166,7 @@ public class Upgrade304to305 extends Upgrade30xBase { pstmt.setLong(1, providerId); pstmt.executeUpdate(); - s_logger.debug("Added VPC Virtual router provider for physical network id=" + pNtwkId); + logger.debug("Added VPC Virtual router provider for physical network id=" + pNtwkId); } } catch (SQLException e) { @@ -177,12 +175,12 @@ public class Upgrade304to305 extends Upgrade30xBase { closeAutoCloseable(rs); closeAutoCloseable(pstmt); } - s_logger.debug("Done adding VPC physical network service providers to all physical networks"); + logger.debug("Done adding VPC physical network service providers to all physical networks"); } private void updateRouterNetworkRef(Connection conn) { //Encrypt config params and change category to Hidden - s_logger.debug("Updating router network ref"); + logger.debug("Updating router network ref"); PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -207,7 +205,7 @@ public class Upgrade304to305 extends Upgrade30xBase { pstmt.setString(3, networkType); pstmt.executeUpdate(); - s_logger.debug("Added reference for router id=" + routerId + " and network id=" + networkId); + logger.debug("Added reference for router id=" + routerId + " and network id=" + networkId); } } catch (SQLException e) { @@ -216,24 +214,24 @@ public class Upgrade304to305 extends Upgrade30xBase { closeAutoCloseable(rs); closeAutoCloseable(pstmt); } - s_logger.debug("Done updating router/network references"); + logger.debug("Done updating router/network references"); } private void addHostDetailsUniqueKey(Connection conn) { - s_logger.debug("Checking if host_details unique key exists, if not we will add it"); + logger.debug("Checking if host_details unique key exists, if not we will add it"); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement("SHOW INDEX FROM `cloud`.`host_details` WHERE KEY_NAME = 'uk_host_id_name'"); rs = pstmt.executeQuery(); if (rs.next()) { - s_logger.debug("Unique key already exists on host_details - not adding new one"); + logger.debug("Unique key already exists on host_details - not adding new one"); } else { //add the key PreparedStatement pstmtUpdate = conn.prepareStatement("ALTER IGNORE TABLE `cloud`.`host_details` ADD CONSTRAINT UNIQUE KEY `uk_host_id_name` (`host_id`, `name`)"); pstmtUpdate.executeUpdate(); - s_logger.debug("Unique key did not exist on host_details - added new one"); + logger.debug("Unique key did not exist on host_details - added new one"); pstmtUpdate.close(); } } catch (SQLException e) { @@ -347,7 +345,7 @@ public class Upgrade304to305 extends Upgrade30xBase { pstmtUpdate.setLong(2, networkId); pstmtUpdate.setLong(3, f5DeviceId); pstmtUpdate.executeUpdate(); - s_logger.debug("Successfully added entry in network_external_lb_device_map for network " + networkId + " and F5 device ID " + f5DeviceId); + logger.debug("Successfully added entry in network_external_lb_device_map for network " + networkId + " and F5 device ID " + f5DeviceId); // add mapping for the network in network_external_firewall_device_map String insertFwMapping = @@ -357,11 +355,11 @@ public class Upgrade304to305 extends Upgrade30xBase { pstmtUpdate.setLong(2, networkId); pstmtUpdate.setLong(3, srxDevivceId); pstmtUpdate.executeUpdate(); - s_logger.debug("Successfully added entry in network_external_firewall_device_map for network " + networkId + " and SRX device ID " + srxDevivceId); + logger.debug("Successfully added entry in network_external_firewall_device_map for network " + networkId + " and SRX device ID " + srxDevivceId); } // update host details for F5 and SRX devices - s_logger.debug("Updating the host details for F5 and SRX devices"); + logger.debug("Updating the host details for F5 and SRX devices"); pstmt = conn.prepareStatement("SELECT host_id, name FROM `cloud`.`host_details` WHERE host_id=? OR host_id=?"); pstmt.setLong(1, f5HostId); pstmt.setLong(2, srxHostId); @@ -380,19 +378,19 @@ public class Upgrade304to305 extends Upgrade30xBase { pstmt.setString(3, camlCaseName); pstmt.executeUpdate(); } - s_logger.debug("Successfully updated host details for F5 and SRX devices"); + logger.debug("Successfully updated host details for F5 and SRX devices"); } catch (SQLException e) { throw new CloudRuntimeException("Unable create a mapping for the networks in network_external_lb_device_map and network_external_firewall_device_map", e); } finally { closeAutoCloseable(rs); closeAutoCloseable(pstmt); } - s_logger.info("Successfully upgraded network using F5 and SRX devices to have a entry in the network_external_lb_device_map and network_external_firewall_device_map"); + logger.info("Successfully upgraded network using F5 and SRX devices to have a entry in the network_external_lb_device_map and network_external_firewall_device_map"); } } private void fixForeignKeys(Connection conn) { - s_logger.debug("Fixing foreign keys' names in ssh_keypairs table"); + logger.debug("Fixing foreign keys' names in ssh_keypairs table"); //Drop the keys (if exist) List keys = new ArrayList(); keys.add("fk_ssh_keypair__account_id"); @@ -434,7 +432,7 @@ public class Upgrade304to305 extends Upgrade30xBase { } private void encryptClusterDetails(Connection conn) { - s_logger.debug("Encrypting cluster details"); + logger.debug("Encrypting cluster details"); PreparedStatement pstmt = null; ResultSet rs = null; try { @@ -460,6 +458,6 @@ public class Upgrade304to305 extends Upgrade30xBase { closeAutoCloseable(rs); closeAutoCloseable(pstmt); } - s_logger.debug("Done encrypting cluster_details"); + logger.debug("Done encrypting cluster_details"); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade305to306.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade305to306.java index 796287697a9..52aab2a13e9 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade305to306.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade305to306.java @@ -27,12 +27,10 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; public class Upgrade305to306 extends Upgrade30xBase { - final static Logger s_logger = Logger.getLogger(Upgrade305to306.class); @Override public String[] getUpgradableVersionRange() { @@ -78,14 +76,14 @@ public class Upgrade305to306 extends Upgrade30xBase { //First drop if it exists. (Due to patches shipped to customers some will have the index and some won't.) List indexList = new ArrayList(); - s_logger.debug("Dropping index i_alert__last_sent if it exists"); + logger.debug("Dropping index i_alert__last_sent if it exists"); indexList.add("i_alert__last_sent"); DbUpgradeUtils.dropKeysIfExist(conn, "alert", indexList, false); //Now add index. try (PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`alert` ADD INDEX `i_alert__last_sent`(`last_sent`)");) { pstmt.executeUpdate(); - s_logger.debug("Added index i_alert__last_sent for table alert"); + logger.debug("Added index i_alert__last_sent for table alert"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to add index i_alert__last_sent to alert table for the column last_sent", e); } @@ -117,14 +115,14 @@ public class Upgrade305to306 extends Upgrade30xBase { //First drop if it exists. (Due to patches shipped to customers some will have the index and some won't.) List indexList = new ArrayList(); - s_logger.debug("Dropping index fk_host_details__host_id if it exists"); + logger.debug("Dropping index fk_host_details__host_id if it exists"); indexList.add("fk_host_details__host_id"); DbUpgradeUtils.dropKeysIfExist(conn, "host_details", indexList, false); //Now add index. try (PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`host_details` ADD INDEX `fk_host_details__host_id`(`host_id`)");) { pstmt.executeUpdate(); - s_logger.debug("Added index fk_host_details__host_id for table host_details"); + logger.debug("Added index fk_host_details__host_id for table host_details"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to add index fk_host_details__host_id to host_details table for the column host_id", e); } @@ -140,7 +138,7 @@ public class Upgrade305to306 extends Upgrade30xBase { // update the existing ingress rules traffic type pstmt = conn.prepareStatement("update `cloud`.`firewall_rules`" + " set traffic_type='Ingress' where purpose='Firewall' and ip_address_id is not null and traffic_type is null"); - s_logger.debug("Updating firewall Ingress rule traffic type: " + pstmt); + logger.debug("Updating firewall Ingress rule traffic type: " + pstmt); pstmt.executeUpdate(); pstmt = conn.prepareStatement("select network_id FROM `cloud`.`ntwk_service_map` where service='Firewall' and provider='VirtualRouter' "); @@ -152,7 +150,7 @@ public class Upgrade305to306 extends Upgrade30xBase { pstmt = conn.prepareStatement("select account_id, domain_id FROM `cloud`.`networks` where (guest_type='Isolated' OR guest_type='" + "Virtual') and traffic_type='Guest' and vpc_id is NULL and (state='implemented' OR state='Shutdown') and id=? "); pstmt.setLong(1, netId); - s_logger.debug("Getting account_id, domain_id from networks table: " + pstmt); + logger.debug("Getting account_id, domain_id from networks table: " + pstmt); rsNw = pstmt.executeQuery(); if (rsNw.next()) { @@ -160,7 +158,7 @@ public class Upgrade305to306 extends Upgrade30xBase { long domainId = rsNw.getLong(2); //Add new rule for the existing networks - s_logger.debug("Adding default egress firewall rule for network " + netId); + logger.debug("Adding default egress firewall rule for network " + netId); pstmt = conn.prepareStatement("INSERT INTO firewall_rules (uuid, state, protocol, purpose, account_id, domain_id, network_id, xid, created, traffic_type) VALUES (?, 'Active', 'all', 'Firewall', ?, ?, ?, ?, now(), 'Egress')"); pstmt.setString(1, UUID.randomUUID().toString()); @@ -168,7 +166,7 @@ public class Upgrade305to306 extends Upgrade30xBase { pstmt.setLong(3, domainId); pstmt.setLong(4, netId); pstmt.setString(5, UUID.randomUUID().toString()); - s_logger.debug("Inserting default egress firewall rule " + pstmt); + logger.debug("Inserting default egress firewall rule " + pstmt); pstmt.executeUpdate(); pstmt = conn.prepareStatement("select id from firewall_rules where protocol='all' and network_id=?"); @@ -180,7 +178,7 @@ public class Upgrade305to306 extends Upgrade30xBase { firewallRuleId = rsId.getLong(1); pstmt = conn.prepareStatement("insert into firewall_rules_cidrs (firewall_rule_id,source_cidr) values (?, '0.0.0.0/0')"); pstmt.setLong(1, firewallRuleId); - s_logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + pstmt); + logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + pstmt); pstmt.executeUpdate(); } } @@ -218,7 +216,7 @@ public class Upgrade305to306 extends Upgrade30xBase { private void fix22xKVMSnapshots(Connection conn) { PreparedStatement pstmt = null; ResultSet rs = null; - s_logger.debug("Updating KVM snapshots"); + logger.debug("Updating KVM snapshots"); try { pstmt = conn.prepareStatement("select id, backup_snap_id from `cloud`.`snapshots` where hypervisor_type='KVM' and removed is null and backup_snap_id is not null"); @@ -232,14 +230,14 @@ public class Upgrade305to306 extends Upgrade30xBase { int index = backUpPath.indexOf("snapshots" + File.separator); if (index > 1) { String correctedPath = File.separator + backUpPath.substring(index); - s_logger.debug("Updating Snapshot with id: " + id + " original backup path: " + backUpPath + " updated backup path: " + correctedPath); + logger.debug("Updating Snapshot with id: " + id + " original backup path: " + backUpPath + " updated backup path: " + correctedPath); pstmt = conn.prepareStatement("UPDATE `cloud`.`snapshots` set backup_snap_id=? where id = ?"); pstmt.setString(1, correctedPath); pstmt.setLong(2, id); pstmt.executeUpdate(); } } - s_logger.debug("Done updating KVM snapshots"); + logger.debug("Done updating KVM snapshots"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to update backup id for KVM snapshots", e); } finally { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade306to307.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade306to307.java index 4eb39af51d7..3d28d73031a 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade306to307.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade306to307.java @@ -23,12 +23,10 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; public class Upgrade306to307 extends Upgrade30xBase { - final static Logger s_logger = Logger.getLogger(Upgrade306to307.class); @Override public String[] getUpgradableVersionRange() { @@ -96,7 +94,7 @@ public class Upgrade306to307 extends Upgrade30xBase { pstmt = conn.prepareStatement("drop table `cloud`.`network_details`"); pstmt.executeUpdate(); } catch (SQLException e) { - s_logger.info("[ignored] error during network offering update:" + e.getLocalizedMessage(), e); + logger.info("[ignored] error during network offering update:" + e.getLocalizedMessage(), e); } finally { closeAutoCloseable(rs); closeAutoCloseable(rs1); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade307to410.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade307to410.java index 1554ff04f70..1d47717a2de 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade307to410.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade307to410.java @@ -23,13 +23,11 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; -import org.apache.log4j.Logger; import com.cloud.utils.db.DbProperties; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade307to410 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade307to410.class); +public class Upgrade307to410 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -71,7 +69,7 @@ public class Upgrade307to410 implements DbUpgrade { } try (PreparedStatement pstmt = conn.prepareStatement("update `cloud`.`region` set id = ?");){ //Update regionId in region table - s_logger.debug("Updating region table with Id: " + region_id); + logger.debug("Updating region table with Id: " + region_id); pstmt.setInt(1, region_id); pstmt.executeUpdate(); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade30to301.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade30to301.java index 806cabb12eb..ba17082bab5 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade30to301.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade30to301.java @@ -22,13 +22,11 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import org.apache.log4j.Logger; import com.cloud.configuration.Resource.ResourceType; import com.cloud.utils.exception.CloudRuntimeException; public class Upgrade30to301 extends LegacyDbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade30to301.class); @Override public String[] getUpgradableVersionRange() { @@ -95,7 +93,7 @@ public class Upgrade30to301 extends LegacyDbUpgrade { pstmt.setLong(1, accountId); pstmt.setLong(2, count); pstmt.executeUpdate(); - s_logger.debug("Updated network resource count for account id=" + accountId + " to be " + count); + logger.debug("Updated network resource count for account id=" + accountId + " to be " + count); } } catch (SQLException e) { throw new CloudRuntimeException("Unable to update network resource count for account id=" + accountId, e); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade30xBase.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade30xBase.java index 47b877d5aa5..d2dd7736533 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade30xBase.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade30xBase.java @@ -23,13 +23,11 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; public abstract class Upgrade30xBase extends LegacyDbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade30xBase.class); protected String getNetworkLabelFromConfig(Connection conn, String name) { String sql = "SELECT value FROM `cloud`.`configuration` where name = ?"; @@ -72,7 +70,7 @@ public abstract class Upgrade30xBase extends LegacyDbUpgrade { broadcastDomainRange = "ZONE"; } - s_logger.debug("Adding PhysicalNetwork " + physicalNetworkId + " for Zone id " + zoneId); + logger.debug("Adding PhysicalNetwork " + physicalNetworkId + " for Zone id " + zoneId); String sql = "INSERT INTO `cloud`.`physical_network` (id, uuid, data_center_id, vnet, broadcast_domain_range, state, name) VALUES (?,?,?,?,?,?,?)"; pstmtUpdate = conn.prepareStatement(sql); @@ -84,12 +82,12 @@ public abstract class Upgrade30xBase extends LegacyDbUpgrade { pstmtUpdate.setString(6, "Enabled"); zoneName = zoneName + "-pNtwk" + physicalNetworkId; pstmtUpdate.setString(7, zoneName); - s_logger.warn("Statement is " + pstmtUpdate.toString()); + logger.warn("Statement is " + pstmtUpdate.toString()); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); if (domainId != null && domainId.longValue() != 0) { - s_logger.debug("Updating domain_id for physical network id=" + physicalNetworkId); + logger.debug("Updating domain_id for physical network id=" + physicalNetworkId); sql = "UPDATE `cloud`.`physical_network` set domain_id=? where id=?"; pstmtUpdate = conn.prepareStatement(sql); pstmtUpdate.setLong(1, domainId); @@ -111,7 +109,7 @@ public abstract class Upgrade30xBase extends LegacyDbUpgrade { // add traffic types PreparedStatement pstmtUpdate = null; try { - s_logger.debug("Adding PhysicalNetwork traffic types"); + logger.debug("Adding PhysicalNetwork traffic types"); String insertTraficType = "INSERT INTO `cloud`.`physical_network_traffic_types` (physical_network_id, traffic_type, xen_network_label, kvm_network_label, vmware_network_label, uuid) VALUES ( ?, ?, ?, ?, ?, ?)"; pstmtUpdate = conn.prepareStatement(insertTraficType); @@ -154,7 +152,7 @@ public abstract class Upgrade30xBase extends LegacyDbUpgrade { pstmt2.close(); if (isSGServiceEnabled) { - s_logger.debug("Adding PhysicalNetworkServiceProvider SecurityGroupProvider to the physical network id=" + physicalNetworkId); + logger.debug("Adding PhysicalNetworkServiceProvider SecurityGroupProvider to the physical network id=" + physicalNetworkId); String insertPNSP = "INSERT INTO `cloud`.`physical_network_service_providers` (`uuid`, `physical_network_id` , `provider_name`, `state` ," + "`destination_physical_network_id`, `vpn_service_provided`, `dhcp_service_provided`, `dns_service_provided`, `gateway_service_provided`," @@ -182,7 +180,7 @@ public abstract class Upgrade30xBase extends LegacyDbUpgrade { PreparedStatement pstmtUpdate = null, pstmt2 = null; try { // add physical network service provider - VirtualRouter - s_logger.debug("Adding PhysicalNetworkServiceProvider VirtualRouter"); + logger.debug("Adding PhysicalNetworkServiceProvider VirtualRouter"); String insertPNSP = "INSERT INTO `cloud`.`physical_network_service_providers` (`uuid`, `physical_network_id` , `provider_name`, `state` ," + "`destination_physical_network_id`, `vpn_service_provided`, `dhcp_service_provided`, `dns_service_provided`, `gateway_service_provided`," diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade40to41.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade40to41.java index 3e15ff6782b..6dc58fdda79 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade40to41.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade40to41.java @@ -25,13 +25,11 @@ import java.sql.SQLException; import java.util.Properties; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.utils.db.DbProperties; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade40to41 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade40to41.class); +public class Upgrade40to41 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -85,7 +83,7 @@ public class Upgrade40to41 implements DbUpgrade { } try (PreparedStatement pstmt = conn.prepareStatement("update `cloud`.`region` set id = ?");) { //Update regionId in region table - s_logger.debug("Updating region table with Id: " + region_id); + logger.debug("Updating region table with Id: " + region_id); pstmt.setInt(1, region_id); pstmt.executeUpdate(); @@ -101,7 +99,7 @@ public class Upgrade40to41 implements DbUpgrade { "not null and traffic_type is null");) { updateNwpstmt.executeUpdate(); - s_logger.debug("Updating firewall Ingress rule traffic type: " + updateNwpstmt); + logger.debug("Updating firewall Ingress rule traffic type: " + updateNwpstmt); } catch (SQLException e) { throw new CloudRuntimeException("Unable to update ingress firewall rules ", e); } @@ -120,13 +118,13 @@ public class Upgrade40to41 implements DbUpgrade { NwAcctDomIdpstmt.setLong(1, netId); try (ResultSet NwAcctDomIdps = NwAcctDomIdpstmt.executeQuery();) { - s_logger.debug("Getting account_id, domain_id from networks table: " + NwAcctDomIdpstmt); + logger.debug("Getting account_id, domain_id from networks table: " + NwAcctDomIdpstmt); if (NwAcctDomIdps.next()) { long accountId = NwAcctDomIdps.getLong(1); long domainId = NwAcctDomIdps.getLong(2); //Add new rule for the existing networks - s_logger.debug("Adding default egress firewall rule for network " + netId); + logger.debug("Adding default egress firewall rule for network " + netId); try (PreparedStatement fwRulespstmt = conn.prepareStatement("INSERT INTO firewall_rules "+ " (uuid, state, protocol, purpose, account_id, domain_id, network_id, xid, created," + " traffic_type) VALUES (?, 'Active', 'all', 'Firewall', ?, ?, ?, ?, now(), " @@ -137,7 +135,7 @@ public class Upgrade40to41 implements DbUpgrade { fwRulespstmt.setLong(3, domainId); fwRulespstmt.setLong(4, netId); fwRulespstmt.setString(5, UUID.randomUUID().toString()); - s_logger.debug("Inserting default egress firewall rule " + fwRulespstmt); + logger.debug("Inserting default egress firewall rule " + fwRulespstmt); fwRulespstmt.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("failed to insert default egress firewall rule ", e); @@ -154,7 +152,7 @@ public class Upgrade40to41 implements DbUpgrade { try (PreparedStatement fwCidrsPstmt = conn.prepareStatement("insert into firewall_rules_cidrs (firewall_rule_id,source_cidr) values (?, '0.0.0.0/0')");) { fwCidrsPstmt.setLong(1, firewallRuleId); - s_logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + fwCidrsPstmt); + logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + fwCidrsPstmt); fwCidrsPstmt.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Unable to set egress firewall rules ", e); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41000to41100.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41000to41100.java index 3900cf0bf82..9b2a7fcc0bb 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41000to41100.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41000to41100.java @@ -25,14 +25,12 @@ import java.sql.SQLException; import java.util.Map; import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade41000to41100 implements DbUpgrade { +public class Upgrade41000to41100 extends DbUpgradeAbstractImpl { - final static Logger LOG = Logger.getLogger(Upgrade41000to41100.class); @Override public String[] getUpgradableVersionRange() { @@ -69,16 +67,16 @@ public class Upgrade41000to41100 implements DbUpgrade { private void checkAndEnableDynamicRoles(final Connection conn) { final Map apiMap = PropertiesUtil.processConfigFile(new String[] { "commands.properties" }); if (apiMap == null || apiMap.isEmpty()) { - if (LOG.isDebugEnabled()) { - LOG.debug("No commands.properties file was found, enabling dynamic roles by setting dynamic.apichecker.enabled to true if not already enabled."); + if (logger.isDebugEnabled()) { + logger.debug("No commands.properties file was found, enabling dynamic roles by setting dynamic.apichecker.enabled to true if not already enabled."); } try (final PreparedStatement updateStatement = conn.prepareStatement("INSERT INTO cloud.configuration (category, instance, name, default_value, value) VALUES ('Advanced', 'DEFAULT', 'dynamic.apichecker.enabled', 'false', 'true') ON DUPLICATE KEY UPDATE value='true'")) { updateStatement.executeUpdate(); } catch (SQLException e) { - LOG.error("Failed to set dynamic.apichecker.enabled to true, please run migrate-dynamicroles.py script to manually migrate to dynamic roles.", e); + logger.error("Failed to set dynamic.apichecker.enabled to true, please run migrate-dynamicroles.py script to manually migrate to dynamic roles.", e); } } else { - LOG.warn("Old commands.properties static checker is deprecated, please use migrate-dynamicroles.py to migrate to dynamic roles. Refer http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/accounts.html#using-dynamic-roles"); + logger.warn("Old commands.properties static checker is deprecated, please use migrate-dynamicroles.py to migrate to dynamic roles. Refer http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/accounts.html#using-dynamic-roles"); } } @@ -96,19 +94,19 @@ public class Upgrade41000to41100 implements DbUpgrade { updateStatement.setLong(2, userVmId); updateStatement.executeUpdate(); } catch (SQLException e) { - LOG.error("Failed to update cloud.user_vm user_data for id:" + userVmId + " with exception: " + e.getMessage()); + logger.error("Failed to update cloud.user_vm user_data for id:" + userVmId + " with exception: " + e.getMessage()); throw new CloudRuntimeException("Exception while updating cloud.user_vm for id " + userVmId, e); } } } else { // Update to NULL since it's invalid - LOG.warn("Removing user_data for vm id " + userVmId + " because it's invalid"); - LOG.warn("Removed data was: " + userData); + logger.warn("Removing user_data for vm id " + userVmId + " because it's invalid"); + logger.warn("Removed data was: " + userData); try (final PreparedStatement updateStatement = conn.prepareStatement("UPDATE `cloud`.`user_vm` SET `user_data` = NULL WHERE `id` = ? ;")) { updateStatement.setLong(1, userVmId); updateStatement.executeUpdate(); } catch (SQLException e) { - LOG.error("Failed to update cloud.user_vm user_data for id:" + userVmId + " to NULL with exception: " + e.getMessage()); + logger.error("Failed to update cloud.user_vm user_data for id:" + userVmId + " to NULL with exception: " + e.getMessage()); throw new CloudRuntimeException("Exception while updating cloud.user_vm for id " + userVmId + " to NULL", e); } } @@ -116,8 +114,8 @@ public class Upgrade41000to41100 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Exception while validating existing user_vm table's user_data column to be base64 valid with padding", e); } - if (LOG.isDebugEnabled()) { - LOG.debug("Done validating base64 content of user data"); + if (logger.isDebugEnabled()) { + logger.debug("Done validating base64 content of user data"); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade410to420.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade410to420.java index 2e7eee13a5a..b78aed3119a 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade410to420.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade410to420.java @@ -33,7 +33,6 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; @@ -44,8 +43,7 @@ import com.cloud.utils.Pair; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade410to420 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade410to420.class); +public class Upgrade410to420 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -194,15 +192,15 @@ public class Upgrade410to420 implements DbUpgrade { detailsMap.put(clusterId, detailsList); updateClusterDetails(conn, detailsMap); - s_logger.debug("Persist vSwitch Configuration: Successfully persisted vswitch configuration for cluster " + clusterId); + logger.debug("Persist vSwitch Configuration: Successfully persisted vswitch configuration for cluster " + clusterId); } else { - s_logger.debug("Persist vSwitch Configuration: Ignoring cluster " + clusterId + " with hypervisor type " + clusterHypervisorType); + logger.debug("Persist vSwitch Configuration: Ignoring cluster " + clusterId + " with hypervisor type " + clusterHypervisorType); continue; } } // End cluster iteration }catch (SQLException e) { String msg = "Unable to persist vswitch configuration of VMware clusters." + e.getMessage(); - s_logger.error(msg); + logger.error(msg); throw new CloudRuntimeException(msg, e); } @@ -212,7 +210,7 @@ public class Upgrade410to420 implements DbUpgrade { } } catch (SQLException e) { String msg = "Unable to persist vswitch configuration of VMware clusters." + e.getMessage(); - s_logger.error(msg); + logger.error(msg); throw new CloudRuntimeException(msg, e); } } @@ -238,7 +236,7 @@ public class Upgrade410to420 implements DbUpgrade { clusterDetailsInsert.setString(3, val); clusterDetailsInsert.executeUpdate(); } - s_logger.debug("Inserted vswitch configuration details into cloud.cluster_details for cluster with id " + clusterId + "."); + logger.debug("Inserted vswitch configuration details into cloud.cluster_details for cluster with id " + clusterId + "."); }catch (SQLException e) { throw new CloudRuntimeException("Unable insert cluster details into cloud.cluster_details table.", e); } @@ -272,7 +270,7 @@ public class Upgrade410to420 implements DbUpgrade { { pstmt.setString(1, paramVal); pstmt.setString(2, paramName); - s_logger.debug("Updating global configuration parameter " + paramName + " with value " + paramVal + ". Update SQL statement is " + pstmt); + logger.debug("Updating global configuration parameter " + paramName + " with value " + paramVal + ". Update SQL statement is " + pstmt); pstmt.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Unable to set global configuration parameter " + paramName + " to " + paramVal + ". ", e); @@ -311,7 +309,7 @@ public class Upgrade410to420 implements DbUpgrade { String type = "ExplicitDedication"; String uuid = UUID.randomUUID().toString(); String groupName = "DedicatedGrp-domain-" + domainName; - s_logger.debug("Adding AffinityGroup of type " + type + " for domain id " + domainId); + logger.debug("Adding AffinityGroup of type " + type + " for domain id " + domainId); String sql = "INSERT INTO `cloud`.`affinity_group` (`name`, `type`, `uuid`, `description`, `domain_id`, `account_id`, `acl_type`) VALUES (?, ?, ?, ?, 1, 1, 'Domain')"; try (PreparedStatement insert_pstmt = conn.prepareStatement(sql);) { @@ -416,7 +414,7 @@ public class Upgrade410to420 implements DbUpgrade { }catch (SQLException e) { throw new CloudRuntimeException("Unable to add foreign keys to baremetal_dhcp_devices table", e); } - s_logger.debug("Added foreign keys for table baremetal_dhcp_devices"); + logger.debug("Added foreign keys for table baremetal_dhcp_devices"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to add foreign keys to baremetal_dhcp_devices table", e); } @@ -436,7 +434,7 @@ public class Upgrade410to420 implements DbUpgrade { }catch (SQLException e) { throw new CloudRuntimeException("Unable to add foreign keys to baremetal_pxe_devices table", e); } - s_logger.debug("Added foreign keys for table baremetal_pxe_devices"); + logger.debug("Added foreign keys for table baremetal_pxe_devices"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to add foreign keys to baremetal_pxe_devices table", e); } @@ -445,7 +443,7 @@ public class Upgrade410to420 implements DbUpgrade { private void addIndexForAlert(Connection conn) { //First drop if it exists. (Due to patches shipped to customers some will have the index and some won't.) List indexList = new ArrayList(); - s_logger.debug("Dropping index i_alert__last_sent if it exists"); + logger.debug("Dropping index i_alert__last_sent if it exists"); indexList.add("last_sent"); // in 4.1, we created this index that is not in convention. indexList.add("i_alert__last_sent"); DbUpgradeUtils.dropKeysIfExist(conn, "alert", indexList, false); @@ -453,7 +451,7 @@ public class Upgrade410to420 implements DbUpgrade { try(PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`alert` ADD INDEX `i_alert__last_sent`(`last_sent`)");) { pstmt.executeUpdate(); - s_logger.debug("Added index i_alert__last_sent for table alert"); + logger.debug("Added index i_alert__last_sent for table alert"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to add index i_alert__last_sent to alert table for the column last_sent", e); } @@ -462,7 +460,7 @@ public class Upgrade410to420 implements DbUpgrade { private void dropUploadTable(Connection conn) { try(PreparedStatement pstmt0 = conn.prepareStatement("SELECT url, created, type_id, host_id from upload where type=?");) { // Read upload table - Templates - s_logger.debug("Populating template_store_ref table"); + logger.debug("Populating template_store_ref table"); pstmt0.setString(1, "TEMPLATE"); try(ResultSet rs0 = pstmt0.executeQuery();) { @@ -476,7 +474,7 @@ public class Upgrade410to420 implements DbUpgrade { pstmt1.executeUpdate(); } // Read upload table - Volumes - s_logger.debug("Populating volume store ref table"); + logger.debug("Populating volume store ref table"); try(PreparedStatement pstmt2 = conn.prepareStatement("SELECT url, created, type_id, host_id, install_path from upload where type=?");) { pstmt2.setString(1, "VOLUME"); try(ResultSet rs2 = pstmt2.executeQuery();) { @@ -518,7 +516,7 @@ public class Upgrade410to420 implements DbUpgrade { //KVM snapshot flag: only turn on if Customers is using snapshot; private void setKVMSnapshotFlag(Connection conn) { - s_logger.debug("Verify and set the KVM snapshot flag if snapshot was used. "); + logger.debug("Verify and set the KVM snapshot flag if snapshot was used. "); try(PreparedStatement pstmt = conn.prepareStatement("select count(*) from `cloud`.`snapshots` where hypervisor_type = 'KVM'");) { int numRows = 0; @@ -541,7 +539,7 @@ public class Upgrade410to420 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Failed to read the snapshot table for KVM upgrade. ", e); } - s_logger.debug("Done set KVM snapshot flag. "); + logger.debug("Done set KVM snapshot flag. "); } private void updatePrimaryStore(Connection conn) { @@ -633,7 +631,7 @@ public class Upgrade410to420 implements DbUpgrade { } } } catch (SQLException e) { - s_logger.error(new CloudRuntimeException("Failed to read vmware_network_label : " + e)); + logger.error(new CloudRuntimeException("Failed to read vmware_network_label : " + e)); } return newGuestLabel; } @@ -667,7 +665,7 @@ public class Upgrade410to420 implements DbUpgrade { newLabel = getNewLabel(rsLabel, trafficTypeVswitchParamValue); try(PreparedStatement update_pstmt = conn.prepareStatement("update physical_network_traffic_types set vmware_network_label = ? where traffic_type = ? and vmware_network_label is not NULL;");) { - s_logger.debug("Updating vmware label for " + trafficType + " traffic. Update SQL statement is " + pstmt); + logger.debug("Updating vmware label for " + trafficType + " traffic. Update SQL statement is " + pstmt); pstmt.setString(1, newLabel); pstmt.setString(2, trafficType); update_pstmt.executeUpdate(); @@ -748,7 +746,7 @@ public class Upgrade410to420 implements DbUpgrade { if (count > 0) { if (!dcOfPreviousCluster.equalsIgnoreCase(dcOfCurrentCluster)) { legacyZone = true; - s_logger.debug("Marking the zone " + zoneId + " as legacy zone."); + logger.debug("Marking the zone " + zoneId + " as legacy zone."); } } } catch (SQLException e) { @@ -758,7 +756,7 @@ public class Upgrade410to420 implements DbUpgrade { throw new CloudRuntimeException("Unable add zones to cloud.legacyzones table.", e); } } else { - s_logger.debug("Ignoring zone " + zoneId + " with hypervisor type " + clusterHypervisorType); + logger.debug("Ignoring zone " + zoneId + " with hypervisor type " + clusterHypervisorType); break; } count++; @@ -798,11 +796,11 @@ public class Upgrade410to420 implements DbUpgrade { updateLegacyZones(conn, listOfLegacyZones); updateNonLegacyZones(conn, listOfNonLegacyZones); } catch (SQLException e) { - s_logger.error("Unable to discover legacy zones." + e.getMessage(),e); + logger.error("Unable to discover legacy zones." + e.getMessage(),e); throw new CloudRuntimeException("Unable to discover legacy zones." + e.getMessage(), e); } }catch (SQLException e) { - s_logger.error("Unable to discover legacy zones." + e.getMessage(),e); + logger.error("Unable to discover legacy zones." + e.getMessage(),e); throw new CloudRuntimeException("Unable to discover legacy zones." + e.getMessage(), e); } } @@ -813,7 +811,7 @@ public class Upgrade410to420 implements DbUpgrade { for (Long zoneId : zones) { legacyZonesQuery.setLong(1, zoneId); legacyZonesQuery.executeUpdate(); - s_logger.debug("Inserted zone " + zoneId + " into cloud.legacyzones table"); + logger.debug("Inserted zone " + zoneId + " into cloud.legacyzones table"); } } catch (SQLException e) { throw new CloudRuntimeException("Unable add zones to cloud.legacyzones table.", e); @@ -823,7 +821,7 @@ public class Upgrade410to420 implements DbUpgrade { private void updateNonLegacyZones(Connection conn, List zones) { try { for (Long zoneId : zones) { - s_logger.debug("Discovered non-legacy zone " + zoneId + ". Processing the zone to associate with VMware datacenter."); + logger.debug("Discovered non-legacy zone " + zoneId + ". Processing the zone to associate with VMware datacenter."); // All clusters in a non legacy zone will belong to the same VMware DC, hence pick the first cluster try (PreparedStatement clustersQuery = conn.prepareStatement("select id from `cloud`.`cluster` where removed is NULL AND data_center_id=?");) { @@ -888,7 +886,7 @@ public class Upgrade410to420 implements DbUpgrade { } } catch (SQLException e) { String msg = "Unable to update non legacy zones." + e.getMessage(); - s_logger.error(msg); + logger.error(msg); throw new CloudRuntimeException(msg, e); } } @@ -914,7 +912,7 @@ public class Upgrade410to420 implements DbUpgrade { }catch (SQLException e) { throw new CloudRuntimeException("Unable to create placeholder nics", e); } - s_logger.debug("Created placeholder nic for the ipAddress " + ip + " and network " + networkId); + logger.debug("Created placeholder nic for the ipAddress " + ip + " and network " + networkId); } }catch (SQLException e) { throw new CloudRuntimeException("Unable to create placeholder nics", e); @@ -959,7 +957,7 @@ public class Upgrade410to420 implements DbUpgrade { try(PreparedStatement sel_net_pstmt = conn.prepareStatement("select account_id, domain_id FROM `cloud`.`networks` where (guest_type='Isolated' OR guest_type='Virtual') and traffic_type='Guest' and vpc_id is NULL and (state='implemented' OR state='Shutdown') and id=? ");) { sel_net_pstmt.setLong(1, netId); - s_logger.debug("Getting account_id, domain_id from networks table: "); + logger.debug("Getting account_id, domain_id from networks table: "); try(ResultSet rsNw = pstmt.executeQuery();) { if (rsNw.next()) { @@ -967,7 +965,7 @@ public class Upgrade410to420 implements DbUpgrade { long domainId = rsNw.getLong(2); //Add new rule for the existing networks - s_logger.debug("Adding default egress firewall rule for network " + netId); + logger.debug("Adding default egress firewall rule for network " + netId); try (PreparedStatement insert_pstmt = conn.prepareStatement("INSERT INTO firewall_rules (uuid, state, protocol, purpose, account_id, domain_id, network_id, xid, created, traffic_type) VALUES (?, 'Active', 'all', 'Firewall', ?, ?, ?, ?, now(), 'Egress')");) { insert_pstmt.setString(1, UUID.randomUUID().toString()); @@ -975,7 +973,7 @@ public class Upgrade410to420 implements DbUpgrade { insert_pstmt.setLong(3, domainId); insert_pstmt.setLong(4, netId); insert_pstmt.setString(5, UUID.randomUUID().toString()); - s_logger.debug("Inserting default egress firewall rule " + insert_pstmt); + logger.debug("Inserting default egress firewall rule " + insert_pstmt); insert_pstmt.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Unable to set egress firewall rules ", e); @@ -988,7 +986,7 @@ public class Upgrade410to420 implements DbUpgrade { firewallRuleId = rsId.getLong(1); try (PreparedStatement insert_pstmt = conn.prepareStatement("insert into firewall_rules_cidrs (firewall_rule_id,source_cidr) values (?, '0.0.0.0/0')");) { insert_pstmt.setLong(1, firewallRuleId); - s_logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + insert_pstmt); + logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + insert_pstmt); insert_pstmt.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Unable to set egress firewall rules ", e); @@ -1040,7 +1038,7 @@ public class Upgrade410to420 implements DbUpgrade { //For each tier create a network ACL and move all the acl_items to network_acl_item table // If there are no acl_items for a tier, associate it with default ACL - s_logger.debug("Updating network ACLs"); + logger.debug("Updating network ACLs"); //1,2 are default acl Ids, start acl Ids from 3 long nextAclId = 3; @@ -1066,7 +1064,7 @@ public class Upgrade410to420 implements DbUpgrade { //Get all VPC tiers while (rsNetworkIds.next()) { Long networkId = rsNetworkIds.getLong(1); - s_logger.debug("Updating network ACLs for network: " + networkId); + logger.debug("Updating network ACLs for network: " + networkId); Long vpcId = rsNetworkIds.getLong(2); String tierUuid = rsNetworkIds.getString(3); pstmtSelectFirewallRules.setLong(1, networkId); @@ -1079,7 +1077,7 @@ public class Upgrade410to420 implements DbUpgrade { hasAcls = true; aclId = nextAclId++; //create ACL for the tier - s_logger.debug("Creating network ACL for tier: " + tierUuid); + logger.debug("Creating network ACL for tier: " + tierUuid); pstmtInsertNetworkAcl.setLong(1, aclId); pstmtInsertNetworkAcl.setLong(2, vpcId); pstmtInsertNetworkAcl.setString(3, "ACL for tier " + tierUuid); @@ -1107,7 +1105,7 @@ public class Upgrade410to420 implements DbUpgrade { } String aclItemUuid = rsAcls.getString(2); //Move acl to network_acl_item table - s_logger.debug("Moving firewall rule: " + aclItemUuid); + logger.debug("Moving firewall rule: " + aclItemUuid); //uuid pstmtInsertNetworkAclItem.setString(1, aclItemUuid); //aclId @@ -1178,7 +1176,7 @@ public class Upgrade410to420 implements DbUpgrade { pstmtUpdate.setLong(2, networkId); pstmtUpdate.executeUpdate(); } - s_logger.debug("Done updating network ACLs "); + logger.debug("Done updating network ACLs "); } catch (SQLException e) { throw new CloudRuntimeException("Unable to move network acls from firewall rules table to network_acl_item table", e); } @@ -1292,17 +1290,17 @@ public class Upgrade410to420 implements DbUpgrade { } private void addHostDetailsIndex(Connection conn) { - s_logger.debug("Checking if host_details index exists, if not we will add it"); + logger.debug("Checking if host_details index exists, if not we will add it"); try(PreparedStatement pstmt = conn.prepareStatement("SHOW INDEX FROM `cloud`.`host_details` where KEY_NAME = 'fk_host_details__host_id'");) { try(ResultSet rs = pstmt.executeQuery();) { if (rs.next()) { - s_logger.debug("Index already exists on host_details - not adding new one"); + logger.debug("Index already exists on host_details - not adding new one"); } else { // add the index try(PreparedStatement pstmtUpdate = conn.prepareStatement("ALTER TABLE `cloud`.`host_details` ADD INDEX `fk_host_details__host_id` (`host_id`)");) { pstmtUpdate.executeUpdate(); - s_logger.debug("Index did not exist on host_details - added new one"); + logger.debug("Index did not exist on host_details - added new one"); }catch (SQLException e) { throw new CloudRuntimeException("Failed to check/update the host_details index ", e); } @@ -1363,7 +1361,7 @@ public class Upgrade410to420 implements DbUpgrade { } private void fix22xKVMSnapshots(Connection conn) { - s_logger.debug("Updating KVM snapshots"); + logger.debug("Updating KVM snapshots"); try (PreparedStatement pstmt = conn.prepareStatement("select id, backup_snap_id from `cloud`.`snapshots` where hypervisor_type='KVM' and removed is null and backup_snap_id is not null");) { try(ResultSet rs = pstmt.executeQuery();) { @@ -1376,7 +1374,7 @@ public class Upgrade410to420 implements DbUpgrade { int index = backUpPath.indexOf("snapshots" + File.separator); if (index > 1) { String correctedPath = backUpPath.substring(index); - s_logger.debug("Updating Snapshot with id: " + id + " original backup path: " + backUpPath + " updated backup path: " + correctedPath); + logger.debug("Updating Snapshot with id: " + id + " original backup path: " + backUpPath + " updated backup path: " + correctedPath); try(PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`snapshots` set backup_snap_id=? where id = ?");) { update_pstmt.setString(1, correctedPath); update_pstmt.setLong(2, id); @@ -1386,7 +1384,7 @@ public class Upgrade410to420 implements DbUpgrade { } } } - s_logger.debug("Done updating KVM snapshots"); + logger.debug("Done updating KVM snapshots"); }catch (SQLException e) { throw new CloudRuntimeException("Unable to update backup id for KVM snapshots", e); } @@ -1480,7 +1478,7 @@ public class Upgrade410to420 implements DbUpgrade { "INSERT INTO `cloud`.`external_load_balancer_devices` (physical_network_id, host_id, provider_name, " + "device_name, capacity, is_dedicated, device_state, allocation_state, is_managed, uuid) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try(PreparedStatement pstmtUpdate = conn.prepareStatement(insertF5);) { - s_logger.debug("Adding F5 Big IP load balancer with host id " + hostId + " in to physical network" + physicalNetworkId); + logger.debug("Adding F5 Big IP load balancer with host id " + hostId + " in to physical network" + physicalNetworkId); pstmtUpdate.setLong(1, physicalNetworkId); pstmtUpdate.setLong(2, hostId); pstmtUpdate.setString(3, "F5BigIp"); @@ -1502,7 +1500,7 @@ public class Upgrade410to420 implements DbUpgrade { "INSERT INTO `cloud`.`external_firewall_devices` (physical_network_id, host_id, provider_name, " + "device_name, capacity, is_dedicated, device_state, allocation_state, uuid) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try(PreparedStatement pstmtUpdate = conn.prepareStatement(insertSrx);) { - s_logger.debug("Adding SRX firewall device with host id " + hostId + " in to physical network" + physicalNetworkId); + logger.debug("Adding SRX firewall device with host id " + hostId + " in to physical network" + physicalNetworkId); pstmtUpdate.setLong(1, physicalNetworkId); pstmtUpdate.setLong(2, hostId); pstmtUpdate.setString(3, "JuniperSRX"); @@ -1526,7 +1524,7 @@ public class Upgrade410to420 implements DbUpgrade { + "`port_forwarding_service_provided`, `user_data_service_provided`, `security_group_service_provided`) VALUES (?,?,?,?,0,0,0,0,0,0,0,1,0,0,0,0)"; try(PreparedStatement pstmtUpdate = conn.prepareStatement(insertPNSP);) { // add physical network service provider - F5BigIp - s_logger.debug("Adding PhysicalNetworkServiceProvider F5BigIp" + " in to physical network" + physicalNetworkId); + logger.debug("Adding PhysicalNetworkServiceProvider F5BigIp" + " in to physical network" + physicalNetworkId); pstmtUpdate.setString(1, UUID.randomUUID().toString()); pstmtUpdate.setLong(2, physicalNetworkId); pstmtUpdate.setString(3, "F5BigIp"); @@ -1545,7 +1543,7 @@ public class Upgrade410to420 implements DbUpgrade { + "`port_forwarding_service_provided`, `user_data_service_provided`, `security_group_service_provided`) VALUES (?,?,?,?,0,0,0,0,1,1,1,0,1,1,0,0)"; try( PreparedStatement pstmtUpdate = conn.prepareStatement(insertPNSP);) { // add physical network service provider - JuniperSRX - s_logger.debug("Adding PhysicalNetworkServiceProvider JuniperSRX"); + logger.debug("Adding PhysicalNetworkServiceProvider JuniperSRX"); pstmtUpdate.setString(1, UUID.randomUUID().toString()); pstmtUpdate.setLong(2, physicalNetworkId); pstmtUpdate.setString(3, "JuniperSRX"); @@ -1690,7 +1688,7 @@ public class Upgrade410to420 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Unable create a mapping for the networks in network_external_lb_device_map and network_external_firewall_device_map", e); } - s_logger.debug("Successfully added entry in network_external_lb_device_map for network " + networkId + " and F5 device ID " + f5DeviceId); + logger.debug("Successfully added entry in network_external_lb_device_map for network " + networkId + " and F5 device ID " + f5DeviceId); // add mapping for the network in network_external_firewall_device_map String insertFwMapping = @@ -1703,7 +1701,7 @@ public class Upgrade410to420 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Unable create a mapping for the networks in network_external_lb_device_map and network_external_firewall_device_map", e); } - s_logger.debug("Successfully added entry in network_external_firewall_device_map for network " + networkId + " and SRX device ID " + srxDevivceId); + logger.debug("Successfully added entry in network_external_firewall_device_map for network " + networkId + " and SRX device ID " + srxDevivceId); } }catch (SQLException e) { throw new CloudRuntimeException("Unable create a mapping for the networks in network_external_lb_device_map and network_external_firewall_device_map", e); @@ -1712,7 +1710,7 @@ public class Upgrade410to420 implements DbUpgrade { throw new CloudRuntimeException("Unable create a mapping for the networks in network_external_lb_device_map and network_external_firewall_device_map", e); } // update host details for F5 and SRX devices - s_logger.debug("Updating the host details for F5 and SRX devices"); + logger.debug("Updating the host details for F5 and SRX devices"); try(PreparedStatement sel_pstmt = conn.prepareStatement("SELECT host_id, name FROM `cloud`.`host_details` WHERE host_id=? OR host_id=?");) { sel_pstmt.setLong(1, f5HostId); sel_pstmt.setLong(2, srxHostId); @@ -1740,11 +1738,11 @@ public class Upgrade410to420 implements DbUpgrade { }catch (SQLException e) { throw new CloudRuntimeException("Unable create a mapping for the networks in network_external_lb_device_map and network_external_firewall_device_map", e); } - s_logger.debug("Successfully updated host details for F5 and SRX devices"); + logger.debug("Successfully updated host details for F5 and SRX devices"); } catch (RuntimeException e) { throw new CloudRuntimeException("Unable create a mapping for the networks in network_external_lb_device_map and network_external_firewall_device_map", e); } - s_logger.info("Successfully upgraded network using F5 and SRX devices to have a entry in the network_external_lb_device_map and network_external_firewall_device_map"); + logger.info("Successfully upgraded network using F5 and SRX devices to have a entry in the network_external_lb_device_map and network_external_firewall_device_map"); } } @@ -1755,7 +1753,7 @@ public class Upgrade410to420 implements DbUpgrade { String sqlInsertStoreDetail = "INSERT INTO `cloud`.`image_store_details` (store_id, name, value) values(?, ?, ?)"; String sqlUpdateHostAsRemoved = "UPDATE `cloud`.`host` SET removed = now() WHERE type = 'SecondaryStorage' and removed is null"; - s_logger.debug("Migrating secondary storage to image store"); + logger.debug("Migrating secondary storage to image store"); boolean hasS3orSwift = false; try ( PreparedStatement pstmtSelectS3Count = conn.prepareStatement(sqlSelectS3Count); @@ -1770,7 +1768,7 @@ public class Upgrade410to420 implements DbUpgrade { ResultSet rsSelectSwiftCount = pstmtSelectSwiftCount.executeQuery(); ResultSet rsNfs = nfsQuery.executeQuery(); ) { - s_logger.debug("Checking if we need to migrate NFS secondary storage to image store or staging store"); + logger.debug("Checking if we need to migrate NFS secondary storage to image store or staging store"); int numRows = 0; if (rsSelectS3Count.next()) { numRows = rsSelectS3Count.getInt(1); @@ -1788,7 +1786,7 @@ public class Upgrade410to420 implements DbUpgrade { store_role = "ImageCache"; } - s_logger.debug("Migrating NFS secondary storage to " + store_role + " store"); + logger.debug("Migrating NFS secondary storage to " + store_role + " store"); // migrate NFS secondary storage, for nfs, keep previous host_id as the store_id while (rsNfs.next()) { @@ -1820,84 +1818,84 @@ public class Upgrade410to420 implements DbUpgrade { storeInsert.executeUpdate(); } - s_logger.debug("Marking NFS secondary storage in host table as removed"); + logger.debug("Marking NFS secondary storage in host table as removed"); pstmtUpdateHostAsRemoved.executeUpdate(); } catch (SQLException e) { String msg = "Unable to migrate secondary storages." + e.getMessage(); - s_logger.error(msg); + logger.error(msg); throw new CloudRuntimeException(msg, e); } - s_logger.debug("Completed migrating secondary storage to image store"); + logger.debug("Completed migrating secondary storage to image store"); } // migrate volume_host_ref to volume_store_ref private void migrateVolumeHostRef(Connection conn) { - s_logger.debug("Updating volume_store_ref table from volume_host_ref table"); + logger.debug("Updating volume_store_ref table from volume_host_ref table"); try(PreparedStatement volStoreInsert = conn.prepareStatement("INSERT INTO `cloud`.`volume_store_ref` (store_id, volume_id, zone_id, created, last_updated, job_id, download_pct, size, physical_size, download_state, checksum, error_str, local_path, install_path, url, destroyed, update_count, ref_cnt, state) select host_id, volume_id, zone_id, created, last_updated, job_id, download_pct, size, physical_size, download_state, checksum, error_str, local_path, install_path, url, destroyed, 0, 0, 'Allocated' from `cloud`.`volume_host_ref`");) { int rowCount = volStoreInsert.executeUpdate(); - s_logger.debug("Insert modified " + rowCount + " rows"); + logger.debug("Insert modified " + rowCount + " rows"); try(PreparedStatement volStoreUpdate = conn.prepareStatement("update `cloud`.`volume_store_ref` set state = 'Ready' where download_state = 'DOWNLOADED'");) { rowCount = volStoreUpdate.executeUpdate(); - s_logger.debug("Update modified " + rowCount + " rows"); + logger.debug("Update modified " + rowCount + " rows"); }catch (SQLException e) { - s_logger.error("Unable to migrate volume_host_ref." + e.getMessage(),e); + logger.error("Unable to migrate volume_host_ref." + e.getMessage(),e); throw new CloudRuntimeException("Unable to migrate volume_host_ref." + e.getMessage(),e); } } catch (SQLException e) { - s_logger.error("Unable to migrate volume_host_ref." + e.getMessage(),e); + logger.error("Unable to migrate volume_host_ref." + e.getMessage(),e); throw new CloudRuntimeException("Unable to migrate volume_host_ref." + e.getMessage(),e); } - s_logger.debug("Completed updating volume_store_ref table from volume_host_ref table"); + logger.debug("Completed updating volume_store_ref table from volume_host_ref table"); } // migrate template_host_ref to template_store_ref private void migrateTemplateHostRef(Connection conn) { - s_logger.debug("Updating template_store_ref table from template_host_ref table"); + logger.debug("Updating template_store_ref table from template_host_ref table"); try (PreparedStatement tmplStoreInsert = conn.prepareStatement("INSERT INTO `cloud`.`template_store_ref` (store_id, template_id, created, last_updated, job_id, download_pct, size, physical_size, download_state, error_str, local_path, install_path, url, destroyed, is_copy, update_count, ref_cnt, store_role, state) select host_id, template_id, created, last_updated, job_id, download_pct, size, physical_size, download_state, error_str, local_path, install_path, url, destroyed, is_copy, 0, 0, 'Image', 'Allocated' from `cloud`.`template_host_ref`");) { int rowCount = tmplStoreInsert.executeUpdate(); - s_logger.debug("Insert modified " + rowCount + " rows"); + logger.debug("Insert modified " + rowCount + " rows"); try(PreparedStatement tmplStoreUpdate = conn.prepareStatement("update `cloud`.`template_store_ref` set state = 'Ready' where download_state = 'DOWNLOADED'");) { rowCount = tmplStoreUpdate.executeUpdate(); }catch (SQLException e) { - s_logger.error("Unable to migrate template_host_ref." + e.getMessage(),e); + logger.error("Unable to migrate template_host_ref." + e.getMessage(),e); throw new CloudRuntimeException("Unable to migrate template_host_ref." + e.getMessage(), e); } - s_logger.debug("Update modified " + rowCount + " rows"); + logger.debug("Update modified " + rowCount + " rows"); } catch (SQLException e) { - s_logger.error("Unable to migrate template_host_ref." + e.getMessage(),e); + logger.error("Unable to migrate template_host_ref." + e.getMessage(),e); throw new CloudRuntimeException("Unable to migrate template_host_ref." + e.getMessage(), e); } - s_logger.debug("Completed updating template_store_ref table from template_host_ref table"); + logger.debug("Completed updating template_store_ref table from template_host_ref table"); } // migrate some entry contents of snapshots to snapshot_store_ref private void migrateSnapshotStoreRef(Connection conn) { - s_logger.debug("Updating snapshot_store_ref table from snapshots table"); + logger.debug("Updating snapshot_store_ref table from snapshots table"); try(PreparedStatement snapshotStoreInsert = conn.prepareStatement("INSERT INTO `cloud`.`snapshot_store_ref` (store_id, snapshot_id, created, size, parent_snapshot_id, install_path, volume_id, update_count, ref_cnt, store_role, state) select sechost_id, id, created, size, prev_snap_id, CONCAT('snapshots', '/', account_id, '/', volume_id, '/', backup_snap_id), volume_id, 0, 0, 'Image', 'Ready' from `cloud`.`snapshots` where status = 'BackedUp' and hypervisor_type <> 'KVM' and sechost_id is not null and removed is null"); ) { //Update all snapshots except KVM snapshots int rowCount = snapshotStoreInsert.executeUpdate(); - s_logger.debug("Inserted " + rowCount + " snapshots into snapshot_store_ref"); + logger.debug("Inserted " + rowCount + " snapshots into snapshot_store_ref"); //backsnap_id for KVM snapshots is complete path. CONCAT is not required try(PreparedStatement snapshotStoreInsert_2 = conn.prepareStatement("INSERT INTO `cloud`.`snapshot_store_ref` (store_id, snapshot_id, created, size, parent_snapshot_id, install_path, volume_id, update_count, ref_cnt, store_role, state) select sechost_id, id, created, size, prev_snap_id, backup_snap_id, volume_id, 0, 0, 'Image', 'Ready' from `cloud`.`snapshots` where status = 'BackedUp' and hypervisor_type = 'KVM' and sechost_id is not null and removed is null");) { rowCount = snapshotStoreInsert_2.executeUpdate(); - s_logger.debug("Inserted " + rowCount + " KVM snapshots into snapshot_store_ref"); + logger.debug("Inserted " + rowCount + " KVM snapshots into snapshot_store_ref"); }catch (SQLException e) { - s_logger.error("Unable to migrate snapshot_store_ref." + e.getMessage(),e); + logger.error("Unable to migrate snapshot_store_ref." + e.getMessage(),e); throw new CloudRuntimeException("Unable to migrate snapshot_store_ref." + e.getMessage(),e); } } catch (SQLException e) { - s_logger.error("Unable to migrate snapshot_store_ref." + e.getMessage(),e); + logger.error("Unable to migrate snapshot_store_ref." + e.getMessage(),e); throw new CloudRuntimeException("Unable to migrate snapshot_store_ref." + e.getMessage(),e); } - s_logger.debug("Completed updating snapshot_store_ref table from snapshots table"); + logger.debug("Completed updating snapshot_store_ref table from snapshots table"); } // migrate secondary storages S3 from s3 tables to image_store table @@ -1905,7 +1903,7 @@ public class Upgrade410to420 implements DbUpgrade { Long storeId = null; Map s3_store_id_map = new HashMap(); - s_logger.debug("Migrating S3 to image store"); + logger.debug("Migrating S3 to image store"); try ( PreparedStatement storeQuery = conn.prepareStatement("select id from `cloud`.`image_store` where uuid = ?"); PreparedStatement storeDetailInsert = conn.prepareStatement("INSERT INTO `cloud`.`image_store_details` (store_id, name, value) values(?, ?, ?)"); @@ -1976,22 +1974,22 @@ public class Upgrade410to420 implements DbUpgrade { } } catch (SQLException e) { String msg = "Unable to migrate S3 secondary storages." + e.getMessage(); - s_logger.error(msg); + logger.error(msg); throw new CloudRuntimeException(msg, e); } - s_logger.debug("Migrating template_s3_ref to template_store_ref"); + logger.debug("Migrating template_s3_ref to template_store_ref"); migrateTemplateS3Ref(conn, s3_store_id_map); - s_logger.debug("Migrating s3 backedup snapshots to snapshot_store_ref"); + logger.debug("Migrating s3 backedup snapshots to snapshot_store_ref"); migrateSnapshotS3Ref(conn, s3_store_id_map); - s_logger.debug("Completed migrating S3 secondary storage to image store"); + logger.debug("Completed migrating S3 secondary storage to image store"); } // migrate template_s3_ref to template_store_ref private void migrateTemplateS3Ref(Connection conn, Map s3StoreMap) { - s_logger.debug("Updating template_store_ref table from template_s3_ref table"); + logger.debug("Updating template_store_ref table from template_s3_ref table"); try(PreparedStatement tmplStoreInsert = conn.prepareStatement("INSERT INTO `cloud`.`template_store_ref` (store_id, template_id, created, download_pct, size, physical_size, download_state, local_path, install_path, update_count, ref_cnt, store_role, state) values(?, ?, ?, 100, ?, ?, 'DOWNLOADED', '?', '?', 0, 0, 'Image', 'Ready')"); ) { @@ -2024,23 +2022,23 @@ public class Upgrade410to420 implements DbUpgrade { tmplStoreInsert.executeUpdate(); } }catch (SQLException e) { - s_logger.error("Unable to migrate template_s3_ref." + e.getMessage(),e); + logger.error("Unable to migrate template_s3_ref." + e.getMessage(),e); throw new CloudRuntimeException("Unable to migrate template_s3_ref." + e.getMessage(),e); } }catch (SQLException e) { - s_logger.error("Unable to migrate template_s3_ref." + e.getMessage(),e); + logger.error("Unable to migrate template_s3_ref." + e.getMessage(),e); throw new CloudRuntimeException("Unable to migrate template_s3_ref." + e.getMessage(),e); } } catch (SQLException e) { - s_logger.error("Unable to migrate template_s3_ref." + e.getMessage(),e); + logger.error("Unable to migrate template_s3_ref." + e.getMessage(),e); throw new CloudRuntimeException("Unable to migrate template_s3_ref." + e.getMessage(),e); } - s_logger.debug("Completed migrating template_s3_ref table."); + logger.debug("Completed migrating template_s3_ref table."); } // migrate some entry contents of snapshots to snapshot_store_ref private void migrateSnapshotS3Ref(Connection conn, Map s3StoreMap) { - s_logger.debug("Updating snapshot_store_ref table from snapshots table for s3"); + logger.debug("Updating snapshot_store_ref table from snapshots table for s3"); try(PreparedStatement snapshotStoreInsert = conn.prepareStatement("INSERT INTO `cloud`.`snapshot_store_ref` (store_id, snapshot_id, created, size, parent_snapshot_id, install_path, volume_id, update_count, ref_cnt, store_role, state) values(?, ?, ?, ?, ?, ?, ?, 0, 0, 'Image', 'Ready')"); ) { @@ -2074,18 +2072,18 @@ public class Upgrade410to420 implements DbUpgrade { snapshotStoreInsert.executeUpdate(); } }catch (SQLException e) { - s_logger.error("migrateSnapshotS3Ref:Exception:"+e.getMessage(),e); + logger.error("migrateSnapshotS3Ref:Exception:"+e.getMessage(),e); throw new CloudRuntimeException("migrateSnapshotS3Ref:Exception:"+e.getMessage(),e); } }catch (SQLException e) { - s_logger.error("migrateSnapshotS3Ref:Exception:"+e.getMessage(),e); + logger.error("migrateSnapshotS3Ref:Exception:"+e.getMessage(),e); throw new CloudRuntimeException("migrateSnapshotS3Ref:Exception:"+e.getMessage(),e); } } catch (SQLException e) { - s_logger.error("Unable to migrate s3 backedup snapshots to snapshot_store_ref." + e.getMessage()); + logger.error("Unable to migrate s3 backedup snapshots to snapshot_store_ref." + e.getMessage()); throw new CloudRuntimeException("Unable to migrate s3 backedup snapshots to snapshot_store_ref." + e.getMessage(), e); } - s_logger.debug("Completed updating snapshot_store_ref table from s3 snapshots entries"); + logger.debug("Completed updating snapshot_store_ref table from s3 snapshots entries"); } // migrate secondary storages Swift from swift tables to image_store table @@ -2093,7 +2091,7 @@ public class Upgrade410to420 implements DbUpgrade { Long storeId = null; Map swift_store_id_map = new HashMap(); - s_logger.debug("Migrating Swift to image store"); + logger.debug("Migrating Swift to image store"); try ( PreparedStatement storeQuery = conn.prepareStatement("select id from `cloud`.`image_store` where uuid = ?"); PreparedStatement storeDetailInsert = conn.prepareStatement("INSERT INTO `cloud`.`image_store_details` (store_id, name, value) values(?, ?, ?)"); @@ -2146,22 +2144,22 @@ public class Upgrade410to420 implements DbUpgrade { } } catch (SQLException e) { String msg = "Unable to migrate swift secondary storages." + e.getMessage(); - s_logger.error(msg); + logger.error(msg); throw new CloudRuntimeException(msg, e); } - s_logger.debug("Migrating template_swift_ref to template_store_ref"); + logger.debug("Migrating template_swift_ref to template_store_ref"); migrateTemplateSwiftRef(conn, swift_store_id_map); - s_logger.debug("Migrating swift backedup snapshots to snapshot_store_ref"); + logger.debug("Migrating swift backedup snapshots to snapshot_store_ref"); migrateSnapshotSwiftRef(conn, swift_store_id_map); - s_logger.debug("Completed migrating Swift secondary storage to image store"); + logger.debug("Completed migrating Swift secondary storage to image store"); } // migrate template_s3_ref to template_store_ref private void migrateTemplateSwiftRef(Connection conn, Map swiftStoreMap) { - s_logger.debug("Updating template_store_ref table from template_swift_ref table"); + logger.debug("Updating template_store_ref table from template_swift_ref table"); try ( PreparedStatement tmplStoreInsert = conn.prepareStatement("INSERT INTO `cloud`.`template_store_ref` (store_id, template_id, created, download_pct, size, physical_size, download_state, local_path, install_path, update_count, ref_cnt, store_role, state) values(?, ?, ?, 100, ?, ?, 'DOWNLOADED', '?', '?', 0, 0, 'Image', 'Ready')"); @@ -2195,15 +2193,15 @@ public class Upgrade410to420 implements DbUpgrade { } } catch (SQLException e) { String msg = "Unable to migrate template_swift_ref." + e.getMessage(); - s_logger.error(msg); + logger.error(msg); throw new CloudRuntimeException(msg, e); } - s_logger.debug("Completed migrating template_swift_ref table."); + logger.debug("Completed migrating template_swift_ref table."); } // migrate some entry contents of snapshots to snapshot_store_ref private void migrateSnapshotSwiftRef(Connection conn, Map swiftStoreMap) { - s_logger.debug("Updating snapshot_store_ref table from snapshots table for swift"); + logger.debug("Updating snapshot_store_ref table from snapshots table for swift"); try (PreparedStatement snapshotStoreInsert = conn.prepareStatement("INSERT INTO `cloud`.`snapshot_store_ref` (store_id, snapshot_id, created, size, parent_snapshot_id, install_path, volume_id, update_count, ref_cnt, store_role, state) values(?, ?, ?, ?, ?, ?, ?, 0, 0, 'Image', 'Ready')"); ){ @@ -2229,31 +2227,31 @@ public class Upgrade410to420 implements DbUpgrade { snapshotStoreInsert.executeUpdate(); } }catch (SQLException e) { - s_logger.error("migrateSnapshotSwiftRef:Exception:"+e.getMessage(),e); + logger.error("migrateSnapshotSwiftRef:Exception:"+e.getMessage(),e); throw new CloudRuntimeException("migrateSnapshotSwiftRef:Exception:"+e.getMessage(),e); } }catch (SQLException e) { - s_logger.error("migrateSnapshotSwiftRef:Exception:"+e.getMessage(),e); + logger.error("migrateSnapshotSwiftRef:Exception:"+e.getMessage(),e); throw new CloudRuntimeException("migrateSnapshotSwiftRef:Exception:"+e.getMessage(),e); } } catch (SQLException e) { - s_logger.error("migrateSnapshotSwiftRef:Exception:"+e.getMessage(),e); + logger.error("migrateSnapshotSwiftRef:Exception:"+e.getMessage(),e); throw new CloudRuntimeException("migrateSnapshotSwiftRef:Exception:"+e.getMessage(),e); } - s_logger.debug("Completed updating snapshot_store_ref table from swift snapshots entries"); + logger.debug("Completed updating snapshot_store_ref table from swift snapshots entries"); } private void fixNiciraKeys(Connection conn) { //First drop the key if it exists. List keys = new ArrayList(); - s_logger.debug("Dropping foreign key fk_nicira_nvp_nic_map__nic from the table nicira_nvp_nic_map if it exists"); + logger.debug("Dropping foreign key fk_nicira_nvp_nic_map__nic from the table nicira_nvp_nic_map if it exists"); keys.add("fk_nicira_nvp_nic_map__nic"); DbUpgradeUtils.dropKeysIfExist(conn, "nicira_nvp_nic_map", keys, true); //Now add foreign key. try(PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`nicira_nvp_nic_map` ADD CONSTRAINT `fk_nicira_nvp_nic_map__nic` FOREIGN KEY (`nic`) REFERENCES `nics` (`uuid`) ON DELETE CASCADE");) { pstmt.executeUpdate(); - s_logger.debug("Added foreign key fk_nicira_nvp_nic_map__nic to the table nicira_nvp_nic_map"); + logger.debug("Added foreign key fk_nicira_nvp_nic_map__nic to the table nicira_nvp_nic_map"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to add foreign key fk_nicira_nvp_nic_map__nic to the table nicira_nvp_nic_map", e); } @@ -2262,7 +2260,7 @@ public class Upgrade410to420 implements DbUpgrade { private void fixRouterKeys(Connection conn) { //First drop the key if it exists. List keys = new ArrayList(); - s_logger.debug("Dropping foreign key fk_router_network_ref__router_id from the table router_network_ref if it exists"); + logger.debug("Dropping foreign key fk_router_network_ref__router_id from the table router_network_ref if it exists"); keys.add("fk_router_network_ref__router_id"); DbUpgradeUtils.dropKeysIfExist(conn, "router_network_ref", keys, true); //Now add foreign key. @@ -2270,14 +2268,14 @@ public class Upgrade410to420 implements DbUpgrade { conn.prepareStatement("ALTER TABLE `cloud`.`router_network_ref` ADD CONSTRAINT `fk_router_network_ref__router_id` FOREIGN KEY (`router_id`) REFERENCES `domain_router` (`id`) ON DELETE CASCADE");) { pstmt.executeUpdate(); - s_logger.debug("Added foreign key fk_router_network_ref__router_id to the table router_network_ref"); + logger.debug("Added foreign key fk_router_network_ref__router_id to the table router_network_ref"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to add foreign key fk_router_network_ref__router_id to the table router_network_ref", e); } } private void encryptSite2SitePSK(Connection conn) { - s_logger.debug("Encrypting Site2Site Customer Gateway pre-shared key"); + logger.debug("Encrypting Site2Site Customer Gateway pre-shared key"); try (PreparedStatement select_pstmt = conn.prepareStatement("select id, ipsec_psk from `cloud`.`s2s_customer_gateway`");){ try(ResultSet rs = select_pstmt.executeQuery();) { @@ -2304,7 +2302,7 @@ public class Upgrade410to420 implements DbUpgrade { } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable to encrypt Site2Site Customer Gateway pre-shared key ", e); } - s_logger.debug("Done encrypting Site2Site Customer Gateway pre-shared key"); + logger.debug("Done encrypting Site2Site Customer Gateway pre-shared key"); } protected void updateConcurrentConnectionsInNetworkOfferings(Connection conn) { @@ -2388,31 +2386,31 @@ public class Upgrade410to420 implements DbUpgrade { conn.prepareStatement("ALTER TABLE `cloud`.`volumes` CHANGE COLUMN `iso_id1` `iso_id` bigint(20) unsigned COMMENT 'The id of the iso from which the volume was created'");) { alter_iso_pstmt.executeUpdate(); }catch (SQLException e) { - s_logger.info("migrateDatafromIsoIdInVolumesTable: ignoring Exception: " + e.getMessage()); - if (s_logger.isTraceEnabled()) { - s_logger.trace("migrateDatafromIsoIdInVolumesTable: ignored Exception",e); + logger.info("migrateDatafromIsoIdInVolumesTable: ignoring Exception: " + e.getMessage()); + if (logger.isTraceEnabled()) { + logger.trace("migrateDatafromIsoIdInVolumesTable: ignored Exception",e); } //implies iso_id1 is not present, so do nothing. } }catch (SQLException e) { - s_logger.info("migrateDatafromIsoIdInVolumesTable: ignoring Exception: " + e.getMessage()); - if (s_logger.isTraceEnabled()) { - s_logger.trace("migrateDatafromIsoIdInVolumesTable: ignored Exception",e); + logger.info("migrateDatafromIsoIdInVolumesTable: ignoring Exception: " + e.getMessage()); + if (logger.isTraceEnabled()) { + logger.trace("migrateDatafromIsoIdInVolumesTable: ignored Exception",e); } //implies iso_id1 is not present, so do nothing. } } }catch (SQLException e) { - s_logger.info("migrateDatafromIsoIdInVolumesTable: ignoring Exception: " + e.getMessage()); - if (s_logger.isTraceEnabled()) { - s_logger.trace("migrateDatafromIsoIdInVolumesTable: ignored Exception",e); + logger.info("migrateDatafromIsoIdInVolumesTable: ignoring Exception: " + e.getMessage()); + if (logger.isTraceEnabled()) { + logger.trace("migrateDatafromIsoIdInVolumesTable: ignored Exception",e); } //implies iso_id1 is not present, so do nothing. } } catch (SQLException e) { - s_logger.info("migrateDatafromIsoIdInVolumesTable: ignoring Exception: " + e.getMessage()); - if (s_logger.isTraceEnabled()) { - s_logger.trace("migrateDatafromIsoIdInVolumesTable: ignored Exception",e); + logger.info("migrateDatafromIsoIdInVolumesTable: ignoring Exception: " + e.getMessage()); + if (logger.isTraceEnabled()) { + logger.trace("migrateDatafromIsoIdInVolumesTable: ignored Exception",e); } //implies iso_id1 is not present, so do nothing. } @@ -2421,7 +2419,7 @@ public class Upgrade410to420 implements DbUpgrade { protected void setRAWformatForRBDVolumes(Connection conn) { try(PreparedStatement pstmt = conn.prepareStatement("UPDATE volumes SET format = 'RAW' WHERE pool_id IN(SELECT id FROM storage_pool WHERE pool_type = 'RBD')");) { - s_logger.debug("Setting format to RAW for all volumes on RBD primary storage pools"); + logger.debug("Setting format to RAW for all volumes on RBD primary storage pools"); pstmt.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Failed to update volume format to RAW for volumes on RBD pools due to exception ", e); @@ -2429,7 +2427,7 @@ public class Upgrade410to420 implements DbUpgrade { } private void upgradeVpcServiceMap(Connection conn) { - s_logger.debug("Upgrading VPC service Map"); + logger.debug("Upgrading VPC service Map"); try(PreparedStatement listVpc = conn.prepareStatement("SELECT id, vpc_offering_id FROM `cloud`.`vpc` where removed is NULL");) { //Get all vpc Ids along with vpc offering Id @@ -2461,7 +2459,7 @@ public class Upgrade410to420 implements DbUpgrade { }catch (SQLException e) { throw new CloudRuntimeException("Error during VPC service map upgrade", e); } - s_logger.debug("Upgraded service map for VPC: " + vpc_id); + logger.debug("Upgraded service map for VPC: " + vpc_id); } } } catch (SQLException e) { @@ -2470,7 +2468,7 @@ public class Upgrade410to420 implements DbUpgrade { } private void upgradeResourceCount(Connection conn) { - s_logger.debug("upgradeResourceCount start"); + logger.debug("upgradeResourceCount start"); try( PreparedStatement sel_dom_pstmt = conn.prepareStatement("select id, domain_id FROM `cloud`.`account` where removed is NULL "); ResultSet rsAccount = sel_dom_pstmt.executeQuery(); @@ -2599,7 +2597,7 @@ public class Upgrade410to420 implements DbUpgrade { throw new CloudRuntimeException("Unable to upgrade resource count (cpu,memory,primary_storage,secondary_storage) ", e); } } - s_logger.debug("upgradeResourceCount finish"); + logger.debug("upgradeResourceCount finish"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to upgrade resource count (cpu,memory,primary_storage,secondary_storage) ", e); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41100to41110.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41100to41110.java index 3703040771b..1df197b4fcf 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41100to41110.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41100to41110.java @@ -25,13 +25,11 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import org.apache.log4j.Logger; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade41100to41110 implements DbUpgrade { - final static Logger LOG = Logger.getLogger(Upgrade41000to41100.class); +public class Upgrade41100to41110 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -105,8 +103,8 @@ public class Upgrade41100to41110 implements DbUpgrade { try ( ResultSet resultSet = prepSelStmt.executeQuery(); ) { - if (LOG.isInfoEnabled()) { - LOG.info("updating setting '" + name + "'"); + if (logger.isInfoEnabled()) { + logger.info("updating setting '" + name + "'"); } if (resultSet.next()) { if ("Secure".equals(resultSet.getString(1))) { @@ -118,10 +116,10 @@ public class Upgrade41100to41110 implements DbUpgrade { prepUpdStmt.setString(2, name); prepUpdStmt.execute(); } catch (SQLException e) { - if (LOG.isInfoEnabled()) { - LOG.info("failed to update configuration item '" + name + "' with value '" + value + "'"); - if (LOG.isDebugEnabled()) { - LOG.debug("no update because ", e); + if (logger.isInfoEnabled()) { + logger.info("failed to update configuration item '" + name + "' with value '" + value + "'"); + if (logger.isDebugEnabled()) { + logger.debug("no update because ", e); } } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41110to41120.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41110to41120.java index f7782cebf46..85be41fc6f2 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41110to41120.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41110to41120.java @@ -20,12 +20,10 @@ package com.cloud.upgrade.dao; import java.io.InputStream; import java.sql.Connection; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade41110to41120 implements DbUpgrade { - final static Logger LOG = Logger.getLogger(Upgrade41110to41120.class); +public class Upgrade41110to41120 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41120to41130.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41120to41130.java index d9eec476628..d011f4fb0fc 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41120to41130.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41120to41130.java @@ -20,7 +20,7 @@ package com.cloud.upgrade.dao; import java.io.InputStream; import java.sql.Connection; -public class Upgrade41120to41130 implements DbUpgrade { +public class Upgrade41120to41130 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41120to41200.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41120to41200.java index f68f04a53aa..ce0e1e39c2e 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41120to41200.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41120to41200.java @@ -23,11 +23,9 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import com.cloud.utils.exception.CloudRuntimeException; -import org.apache.log4j.Logger; -public class Upgrade41120to41200 implements DbUpgrade { +public class Upgrade41120to41200 extends DbUpgradeAbstractImpl { - final static Logger LOG = Logger.getLogger(Upgrade41120to41200.class); @Override public String[] getUpgradableVersionRange() { @@ -64,7 +62,7 @@ public class Upgrade41120to41200 implements DbUpgrade { try (final PreparedStatement updateStatement = conn.prepareStatement("UPDATE cloud.mshost SET uuid=UUID()")) { updateStatement.executeUpdate(); } catch (SQLException e) { - LOG.error("Failed to add an UUID to each management server.", e); + logger.error("Failed to add an UUID to each management server.", e); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41200to41300.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41200to41300.java index 2de8dc98358..dd6f2cf3036 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41200to41300.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41200to41300.java @@ -22,7 +22,7 @@ import java.sql.Connection; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade41200to41300 implements DbUpgrade { +public class Upgrade41200to41300 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41300to41310.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41300to41310.java index ac6149f7844..4cae3d445c7 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41300to41310.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41300to41310.java @@ -19,7 +19,7 @@ package com.cloud.upgrade.dao; import java.io.InputStream; import java.sql.Connection; -public class Upgrade41300to41310 implements DbUpgrade { +public class Upgrade41300to41310 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { return new String[] {"4.13.0.0", "4.13.1.0"}; diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41310to41400.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41310to41400.java index f1a333e7d48..91fd5b6d57f 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41310to41400.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41310to41400.java @@ -20,13 +20,11 @@ package com.cloud.upgrade.dao; import java.io.InputStream; import java.sql.Connection; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade41310to41400 implements DbUpgrade { +public class Upgrade41310to41400 extends DbUpgradeAbstractImpl { - final static Logger LOG = Logger.getLogger(Upgrade41310to41400.class); @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41400to41500.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41400to41500.java index ba969ae879e..4750915baa6 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41400to41500.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41400to41500.java @@ -27,13 +27,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade41400to41500 implements DbUpgrade { - - final static Logger LOG = Logger.getLogger(Upgrade41400to41500.class); +public class Upgrade41400to41500 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -74,7 +71,7 @@ public class Upgrade41400to41500 implements DbUpgrade { } private void addRolePermissionsForReadOnlyAdmin(final Connection conn) { - LOG.debug("Adding role permissions for new read-only admin role"); + logger.debug("Adding role permissions for new read-only admin role"); try { PreparedStatement pstmt = conn.prepareStatement("SELECT id FROM `cloud`.`roles` WHERE name = 'Read-Only Admin - Default' AND is_default = 1"); ResultSet rs = pstmt.executeQuery(); @@ -108,15 +105,15 @@ public class Upgrade41400to41500 implements DbUpgrade { if (pstmt != null && !pstmt.isClosed()) { pstmt.close(); } - LOG.debug("Successfully added role permissions for new read-only admin role"); + logger.debug("Successfully added role permissions for new read-only admin role"); } catch (final SQLException e) { - LOG.error("Exception while adding role permissions for read-only admin role: " + e.getMessage()); + logger.error("Exception while adding role permissions for read-only admin role: " + e.getMessage()); throw new CloudRuntimeException("Exception while adding role permissions for read-only admin role: " + e.getMessage(), e); } } private void addRolePermissionsForReadOnlyUser(final Connection conn) { - LOG.debug("Adding role permissions for new read-only user role"); + logger.debug("Adding role permissions for new read-only user role"); try { PreparedStatement pstmt = conn.prepareStatement("SELECT id FROM `cloud`.`roles` WHERE name = 'Read-Only User - Default' AND is_default = 1"); ResultSet rs = pstmt.executeQuery(); @@ -179,15 +176,15 @@ public class Upgrade41400to41500 implements DbUpgrade { if (pstmt != null && !pstmt.isClosed()) { pstmt.close(); } - LOG.debug("Successfully added role permissions for new read-only user role"); + logger.debug("Successfully added role permissions for new read-only user role"); } catch (final SQLException e) { - LOG.error("Exception while adding role permissions for read-only user role: " + e.getMessage()); + logger.error("Exception while adding role permissions for read-only user role: " + e.getMessage()); throw new CloudRuntimeException("Exception while adding role permissions for read-only user role: " + e.getMessage(), e); } } private void addRolePermissionsForSupportAdmin(final Connection conn) { - LOG.debug("Adding role permissions for new support admin role"); + logger.debug("Adding role permissions for new support admin role"); try { PreparedStatement pstmt = conn.prepareStatement("SELECT id FROM `cloud`.`roles` WHERE name = 'Support Admin - Default' AND is_default = 1"); ResultSet rs = pstmt.executeQuery(); @@ -264,15 +261,15 @@ public class Upgrade41400to41500 implements DbUpgrade { if (pstmt != null && !pstmt.isClosed()) { pstmt.close(); } - LOG.debug("Successfully added role permissions for new support admin role"); + logger.debug("Successfully added role permissions for new support admin role"); } catch (final SQLException e) { - LOG.error("Exception while adding role permissions for support admin role: " + e.getMessage()); + logger.error("Exception while adding role permissions for support admin role: " + e.getMessage()); throw new CloudRuntimeException("Exception while adding role permissions for support admin role: " + e.getMessage(), e); } } private void addRolePermissionsForSupportUser(final Connection conn) { - LOG.debug("Adding role permissions for new support user role"); + logger.debug("Adding role permissions for new support user role"); try { PreparedStatement pstmt = conn.prepareStatement("SELECT id FROM `cloud`.`roles` WHERE name = 'Support User - Default' AND is_default = 1"); ResultSet rs = pstmt.executeQuery(); @@ -341,9 +338,9 @@ public class Upgrade41400to41500 implements DbUpgrade { if (pstmt != null && !pstmt.isClosed()) { pstmt.close(); } - LOG.debug("Successfully added role permissions for new support user role"); + logger.debug("Successfully added role permissions for new support user role"); } catch (final SQLException e) { - LOG.error("Exception while adding role permissions for support user role: " + e.getMessage()); + logger.error("Exception while adding role permissions for support user role: " + e.getMessage()); throw new CloudRuntimeException("Exception while adding role permissions for support user role: " + e.getMessage(), e); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41500to41510.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41500to41510.java index 344bbccc95b..a6b77813fa1 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41500to41510.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41500to41510.java @@ -27,14 +27,18 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.apache.log4j.Logger; import com.cloud.hypervisor.Hypervisor; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade41500to41510 implements DbUpgrade, DbUpgradeSystemVmTemplate { +import static com.cloud.hypervisor.Hypervisor.HypervisorType.Hyperv; +import static com.cloud.hypervisor.Hypervisor.HypervisorType.KVM; +import static com.cloud.hypervisor.Hypervisor.HypervisorType.LXC; +import static com.cloud.hypervisor.Hypervisor.HypervisorType.Ovm3; +import static com.cloud.hypervisor.Hypervisor.HypervisorType.VMware; +import static com.cloud.hypervisor.Hypervisor.HypervisorType.XenServer; - final static Logger LOG = Logger.getLogger(Upgrade41500to41510.class); +public class Upgrade41500to41510 extends DbUpgradeAbstractImpl implements DbUpgradeSystemVmTemplate { @Override public String[] getUpgradableVersionRange() { @@ -70,84 +74,76 @@ public class Upgrade41500to41510 implements DbUpgrade, DbUpgradeSystemVmTemplate @Override @SuppressWarnings("serial") public void updateSystemVmTemplates(final Connection conn) { - LOG.debug("Updating System Vm template IDs"); + logger.debug("Updating System Vm template IDs"); final Set hypervisorsListInUse = new HashSet(); try (PreparedStatement pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null"); ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { - switch (Hypervisor.HypervisorType.getType(rs.getString(1))) { - case XenServer: - hypervisorsListInUse.add(Hypervisor.HypervisorType.XenServer); - break; - case KVM: - hypervisorsListInUse.add(Hypervisor.HypervisorType.KVM); - break; - case VMware: - hypervisorsListInUse.add(Hypervisor.HypervisorType.VMware); - break; - case Hyperv: - hypervisorsListInUse.add(Hypervisor.HypervisorType.Hyperv); - break; - case LXC: - hypervisorsListInUse.add(Hypervisor.HypervisorType.LXC); - break; - case Ovm3: - hypervisorsListInUse.add(Hypervisor.HypervisorType.Ovm3); - break; - default: - break; + Hypervisor.HypervisorType type = Hypervisor.HypervisorType.getType(rs.getString(1)); + if (type.equals(XenServer)) { + hypervisorsListInUse.add(XenServer); + } else if (type.equals(KVM)) { + hypervisorsListInUse.add(KVM); + } else if (type.equals(VMware)) { + hypervisorsListInUse.add(VMware); + } else if (type.equals(Hyperv)) { + hypervisorsListInUse.add(Hyperv); + } else if (type.equals(LXC)) { + hypervisorsListInUse.add(LXC); + } else if (type.equals(Ovm3)) { + hypervisorsListInUse.add(Ovm3); } } } catch (final SQLException e) { - LOG.error("updateSystemVmTemplates: Exception caught while getting hypervisor types from clusters: " + e.getMessage()); + logger.error("updateSystemVmTemplates: Exception caught while getting hypervisor types from clusters: " + e.getMessage()); throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting hypervisor types from clusters", e); } final Map NewTemplateNameList = new HashMap() { { - put(Hypervisor.HypervisorType.KVM, "systemvm-kvm-4.15.1"); - put(Hypervisor.HypervisorType.VMware, "systemvm-vmware-4.15.1"); - put(Hypervisor.HypervisorType.XenServer, "systemvm-xenserver-4.15.1"); - put(Hypervisor.HypervisorType.Hyperv, "systemvm-hyperv-4.15.1"); - put(Hypervisor.HypervisorType.LXC, "systemvm-lxc-4.15.1"); - put(Hypervisor.HypervisorType.Ovm3, "systemvm-ovm3-4.15.1"); + put(KVM, "systemvm-kvm-4.15.1"); + put(VMware, "systemvm-vmware-4.15.1"); + put(XenServer, "systemvm-xenserver-4.15.1"); + put(Hyperv, "systemvm-hyperv-4.15.1"); + put(LXC, "systemvm-lxc-4.15.1"); + put(Ovm3, "systemvm-ovm3-4.15.1"); } }; final Map routerTemplateConfigurationNames = new HashMap() { { - put(Hypervisor.HypervisorType.KVM, "router.template.kvm"); - put(Hypervisor.HypervisorType.VMware, "router.template.vmware"); - put(Hypervisor.HypervisorType.XenServer, "router.template.xenserver"); - put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv"); - put(Hypervisor.HypervisorType.LXC, "router.template.lxc"); - put(Hypervisor.HypervisorType.Ovm3, "router.template.ovm3"); + put(KVM, "router.template.kvm"); + put(VMware, "router.template.vmware"); + put(XenServer, "router.template.xenserver"); + put(Hyperv, "router.template.hyperv"); + put(LXC, "router.template.lxc"); + put(Ovm3, "router.template.ovm3"); } }; final Map newTemplateUrl = new HashMap() { { - put(Hypervisor.HypervisorType.KVM, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-kvm.qcow2.bz2"); - put(Hypervisor.HypervisorType.VMware, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-vmware.ova"); - put(Hypervisor.HypervisorType.XenServer, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-xen.vhd.bz2"); - put(Hypervisor.HypervisorType.Hyperv, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-hyperv.vhd.zip"); - put(Hypervisor.HypervisorType.LXC, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-kvm.qcow2.bz2"); - put(Hypervisor.HypervisorType.Ovm3, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-ovm.raw.bz2"); + put(KVM, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-kvm.qcow2.bz2"); + put(VMware, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-vmware.ova"); + put(XenServer, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-xen.vhd.bz2"); + put(Hyperv, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-hyperv.vhd.zip"); + put(LXC, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-kvm.qcow2.bz2"); + put(Ovm3, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-ovm.raw.bz2"); } }; final Map newTemplateChecksum = new HashMap() { { - put(Hypervisor.HypervisorType.KVM, "0e9f9a7d0957c3e0a2088e41b2da2cec"); - put(Hypervisor.HypervisorType.XenServer, "86373992740b1eca8aff8b08ebf3aea5"); - put(Hypervisor.HypervisorType.VMware, "4006982765846d373eb3719b2fe4d720"); - put(Hypervisor.HypervisorType.Hyperv, "0b9514e4b6cba1f636fea2125f0f7a5f"); - put(Hypervisor.HypervisorType.LXC, "0e9f9a7d0957c3e0a2088e41b2da2cec"); - put(Hypervisor.HypervisorType.Ovm3, "ae3977e696b3e6c81bdcbb792d514d29"); + put(KVM, "0e9f9a7d0957c3e0a2088e41b2da2cec"); + put(XenServer, "86373992740b1eca8aff8b08ebf3aea5"); + put(VMware, "4006982765846d373eb3719b2fe4d720"); + put(Hyperv, "0b9514e4b6cba1f636fea2125f0f7a5f"); + put(LXC, "0e9f9a7d0957c3e0a2088e41b2da2cec"); + put(Ovm3, "ae3977e696b3e6c81bdcbb792d514d29"); } }; for (final Map.Entry hypervisorAndTemplateName : NewTemplateNameList.entrySet()) { - LOG.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms"); + logger.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms"); try (PreparedStatement pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null and account_id in (select id from account where type = 1 and removed is NULL) order by id desc limit 1")) { // Get systemvm template id for corresponding hypervisor long templateId = -1; @@ -157,7 +153,7 @@ public class Upgrade41500to41510 implements DbUpgrade, DbUpgradeSystemVmTemplate templateId = rs.getLong(1); } } catch (final SQLException e) { - LOG.error("updateSystemVmTemplates: Exception caught while getting ids of templates: " + e.getMessage()); + logger.error("updateSystemVmTemplates: Exception caught while getting ids of templates: " + e.getMessage()); throw new CloudRuntimeException("updateSystemVmTemplates: Exception caught while getting ids of templates", e); } @@ -167,7 +163,7 @@ public class Upgrade41500to41510 implements DbUpgrade, DbUpgradeSystemVmTemplate templ_type_pstmt.setLong(1, templateId); templ_type_pstmt.executeUpdate(); } catch (final SQLException e) { - LOG.error("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system': " + e.getMessage()); + logger.error("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system': " + e.getMessage()); throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system'", e); } // update template ID of system Vms @@ -177,7 +173,7 @@ public class Upgrade41500to41510 implements DbUpgrade, DbUpgradeSystemVmTemplate update_templ_id_pstmt.setString(2, hypervisorAndTemplateName.getKey().toString()); update_templ_id_pstmt.executeUpdate(); } catch (final Exception e) { - LOG.error("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId + logger.error("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId + ": " + e.getMessage()); throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId, e); @@ -190,7 +186,7 @@ public class Upgrade41500to41510 implements DbUpgrade, DbUpgradeSystemVmTemplate update_pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey())); update_pstmt.executeUpdate(); } catch (final SQLException e) { - LOG.error("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + logger.error("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + hypervisorAndTemplateName.getValue() + ": " + e.getMessage()); throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + hypervisorAndTemplateName.getValue(), e); @@ -203,14 +199,14 @@ public class Upgrade41500to41510 implements DbUpgrade, DbUpgradeSystemVmTemplate update_pstmt.setString(2, "minreq.sysvmtemplate.version"); update_pstmt.executeUpdate(); } catch (final SQLException e) { - LOG.error("updateSystemVmTemplates:Exception while setting 'minreq.sysvmtemplate.version' to 4.15.1: " + e.getMessage()); + logger.error("updateSystemVmTemplates:Exception while setting 'minreq.sysvmtemplate.version' to 4.15.1: " + e.getMessage()); throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting 'minreq.sysvmtemplate.version' to 4.15.1", e); } } else { if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())) { throw new CloudRuntimeException(getUpgradedVersion() + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms"); } else { - LOG.warn(getUpgradedVersion() + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() + logger.warn(getUpgradedVersion() + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey() + " hypervisor is not used, so not failing upgrade"); // Update the latest template URLs for corresponding // hypervisor @@ -221,7 +217,7 @@ public class Upgrade41500to41510 implements DbUpgrade, DbUpgradeSystemVmTemplate update_templ_url_pstmt.setString(3, hypervisorAndTemplateName.getKey().toString()); update_templ_url_pstmt.executeUpdate(); } catch (final SQLException e) { - LOG.error("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type " + logger.error("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type " + hypervisorAndTemplateName.getKey().toString() + ": " + e.getMessage()); throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type " + hypervisorAndTemplateName.getKey().toString(), e); @@ -229,11 +225,11 @@ public class Upgrade41500to41510 implements DbUpgrade, DbUpgradeSystemVmTemplate } } } catch (final SQLException e) { - LOG.error("updateSystemVmTemplates:Exception while getting ids of templates: " + e.getMessage()); + logger.error("updateSystemVmTemplates:Exception while getting ids of templates: " + e.getMessage()); throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting ids of templates", e); } } - LOG.debug("Updating System Vm Template IDs Complete"); + logger.debug("Updating System Vm Template IDs Complete"); } @Override diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41510to41520.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41510to41520.java index bf91c8f7ace..41b362c4bf7 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41510to41520.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41510to41520.java @@ -21,11 +21,8 @@ import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -import org.apache.log4j.Logger; -public class Upgrade41510to41520 implements DbUpgrade { - - final static Logger LOG = Logger.getLogger(Upgrade41510to41520.class); +public class Upgrade41510to41520 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41520to41600.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41520to41600.java index 107742076fd..76227d43417 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41520to41600.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41520to41600.java @@ -28,14 +28,12 @@ import java.util.List; import com.cloud.upgrade.RolePermissionChecker; import com.cloud.upgrade.SystemVmTemplateRegistration; import org.apache.cloudstack.acl.RoleType; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade41520to41600 implements DbUpgrade, DbUpgradeSystemVmTemplate { +public class Upgrade41520to41600 extends DbUpgradeAbstractImpl implements DbUpgradeSystemVmTemplate { - final static Logger LOG = Logger.getLogger(Upgrade41520to41600.class); private SystemVmTemplateRegistration systemVmTemplateRegistration; private RolePermissionChecker rolePermissionChecker = new RolePermissionChecker(); @@ -82,21 +80,21 @@ public class Upgrade41520to41600 implements DbUpgrade, DbUpgradeSystemVmTemplate } private void checkAndPersistAnnotationPermissions(Connection conn, RoleType roleType, List rules) { - LOG.debug("Checking the annotation permissions for the role: " + roleType.getId()); + logger.debug("Checking the annotation permissions for the role: " + roleType.getId()); for (String rule : rules) { - LOG.debug("Checking the annotation permissions for the role: " + roleType.getId() + " and rule: " + rule); + logger.debug("Checking the annotation permissions for the role: " + roleType.getId() + " and rule: " + rule); if (!rolePermissionChecker.existsRolePermissionByRoleIdAndRule(conn, roleType.getId(), rule)) { - LOG.debug("Inserting role permission for role: " + roleType.getId() + " and rule: " + rule); + logger.debug("Inserting role permission for role: " + roleType.getId() + " and rule: " + rule); rolePermissionChecker.insertAnnotationRulePermission(conn, roleType.getId(), rule); } else { - LOG.debug("Found existing role permission for role: " + roleType.getId() + " and rule: " + rule + + logger.debug("Found existing role permission for role: " + roleType.getId() + " and rule: " + rule + ", not updating it"); } } } private void generateUuidForExistingSshKeyPairs(Connection conn) { - LOG.debug("Generating uuid for existing ssh key-pairs"); + logger.debug("Generating uuid for existing ssh key-pairs"); try { PreparedStatement pstmt = conn.prepareStatement("SELECT id FROM `cloud`.`ssh_keypairs` WHERE uuid is null"); ResultSet rs = pstmt.executeQuery(); @@ -112,10 +110,10 @@ public class Upgrade41520to41600 implements DbUpgrade, DbUpgradeSystemVmTemplate if (!pstmt.isClosed()) { pstmt.close(); } - LOG.debug("Successfully generated uuid for existing ssh key-pairs"); + logger.debug("Successfully generated uuid for existing ssh key-pairs"); } catch (SQLException e) { String errMsg = "Exception while generating uuid for existing ssh key-pairs: " + e.getMessage(); - LOG.error(errMsg, e); + logger.error(errMsg, e); throw new CloudRuntimeException(errMsg, e); } } @@ -127,7 +125,7 @@ public class Upgrade41520to41600 implements DbUpgrade, DbUpgradeSystemVmTemplate @Override @SuppressWarnings("serial") public void updateSystemVmTemplates(final Connection conn) { - LOG.debug("Updating System Vm template IDs"); + logger.debug("Updating System Vm template IDs"); initSystemVmTemplateRegistration(); try { systemVmTemplateRegistration.updateSystemVmTemplates(conn); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41600to41610.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41600to41610.java index 8094a2e9a3c..3208b4ad8f9 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41600to41610.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41600to41610.java @@ -19,14 +19,12 @@ package com.cloud.upgrade.dao; import com.cloud.upgrade.SystemVmTemplateRegistration; import com.cloud.utils.exception.CloudRuntimeException; -import org.apache.log4j.Logger; import java.io.InputStream; import java.sql.Connection; -public class Upgrade41600to41610 implements DbUpgrade, DbUpgradeSystemVmTemplate { +public class Upgrade41600to41610 extends DbUpgradeAbstractImpl implements DbUpgradeSystemVmTemplate { - final static Logger LOG = Logger.getLogger(Upgrade41600to41610.class); private SystemVmTemplateRegistration systemVmTemplateRegistration; @Override @@ -77,7 +75,7 @@ public class Upgrade41600to41610 implements DbUpgrade, DbUpgradeSystemVmTemplate @Override public void updateSystemVmTemplates(Connection conn) { - LOG.debug("Updating System Vm template IDs"); + logger.debug("Updating System Vm template IDs"); initSystemVmTemplateRegistration(); try { systemVmTemplateRegistration.updateSystemVmTemplates(conn); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41610to41700.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41610to41700.java index bb4e70567c6..0a0ab0b9f5a 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41610to41700.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41610to41700.java @@ -24,14 +24,12 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; -import org.apache.log4j.Logger; import com.cloud.upgrade.SystemVmTemplateRegistration; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade41610to41700 implements DbUpgrade, DbUpgradeSystemVmTemplate { +public class Upgrade41610to41700 extends DbUpgradeAbstractImpl implements DbUpgradeSystemVmTemplate { - final static Logger LOG = Logger.getLogger(Upgrade41700to41710.class); private SystemVmTemplateRegistration systemVmTemplateRegistration; @Override @@ -82,7 +80,7 @@ public class Upgrade41610to41700 implements DbUpgrade, DbUpgradeSystemVmTemplate @Override public void updateSystemVmTemplates(Connection conn) { - LOG.debug("Updating System Vm template IDs"); + logger.debug("Updating System Vm template IDs"); initSystemVmTemplateRegistration(); try { systemVmTemplateRegistration.updateSystemVmTemplates(conn); @@ -92,7 +90,7 @@ public class Upgrade41610to41700 implements DbUpgrade, DbUpgradeSystemVmTemplate } public void fixWrongDatastoreClusterPoolUuid(Connection conn) { - LOG.debug("Replacement of faulty pool uuids on datastorecluster"); + logger.debug("Replacement of faulty pool uuids on datastorecluster"); try (PreparedStatement pstmt = conn.prepareStatement("SELECT id,uuid FROM storage_pool " + "WHERE uuid NOT LIKE \"%-%-%-%\" AND removed IS NULL " + "AND pool_type = 'DatastoreCluster';"); ResultSet rs = pstmt.executeQuery()) { @@ -109,7 +107,7 @@ public class Upgrade41610to41700 implements DbUpgrade, DbUpgradeSystemVmTemplate updateStmt.executeBatch(); } catch (SQLException ex) { String errorMsg = "fixWrongPoolUuid:Exception while updating faulty pool uuids"; - LOG.error(errorMsg,ex); + logger.error(errorMsg,ex); throw new CloudRuntimeException(errorMsg, ex); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41700to41710.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41700to41710.java index a228a01b9e8..266401e0c31 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41700to41710.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41700to41710.java @@ -23,18 +23,20 @@ import java.util.List; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.log4j.Logger; +import org.apache.commons.collections.CollectionUtils; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.dao.VolumeDaoImpl; import com.cloud.upgrade.SystemVmTemplateRegistration; +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade41700to41710 implements DbUpgrade, DbUpgradeSystemVmTemplate { +public class Upgrade41700to41710 extends DbUpgradeAbstractImpl implements DbUpgradeSystemVmTemplate { - final static Logger LOG = Logger.getLogger(Upgrade41700to41710.class); private SystemVmTemplateRegistration systemVmTemplateRegistration; private PrimaryDataStoreDao storageDao; @@ -88,7 +90,7 @@ public class Upgrade41700to41710 implements DbUpgrade, DbUpgradeSystemVmTemplate @Override public void updateSystemVmTemplates(Connection conn) { - LOG.debug("Updating System Vm template IDs"); + logger.debug("Updating System Vm template IDs"); initSystemVmTemplateRegistration(); try { systemVmTemplateRegistration.updateSystemVmTemplates(conn); @@ -97,24 +99,58 @@ public class Upgrade41700to41710 implements DbUpgrade, DbUpgradeSystemVmTemplate } } - private void updateStorPoolStorageType() { - storageDao = new PrimaryDataStoreDaoImpl(); - List storPoolPools = storageDao.findPoolsByProvider("StorPool"); - for (StoragePoolVO storagePoolVO : storPoolPools) { - if (StoragePoolType.SharedMountPoint == storagePoolVO.getPoolType()) { - storagePoolVO.setPoolType(StoragePoolType.StorPool); - storageDao.update(storagePoolVO.getId(), storagePoolVO); - } - updateStorageTypeForStorPoolVolumes(storagePoolVO.getId()); + protected PrimaryDataStoreDao getStorageDao() { + if (storageDao == null) { + storageDao = new PrimaryDataStoreDaoImpl(); } + return storageDao; } - private void updateStorageTypeForStorPoolVolumes(long storagePoolId) { - volumeDao = new VolumeDaoImpl(); - List volumes = volumeDao.findByPoolId(storagePoolId, null); - for (VolumeVO volumeVO : volumes) { - volumeVO.setPoolType(StoragePoolType.StorPool); - volumeDao.update(volumeVO.getId(), volumeVO); + protected VolumeDao getVolumeDao() { + if (volumeDao == null) { + volumeDao = new VolumeDaoImpl(); } + return volumeDao; + } + + /* + GenericDao.customSearch using GenericSearchBuilder and GenericDao.update using + GenericDao.createSearchBuilder used here to prevent any future issues when new fields + are added to StoragePoolVO or VolumeVO and this upgrade path starts to fail. + */ + protected void updateStorPoolStorageType() { + StoragePoolVO pool = getStorageDao().createForUpdate(); + pool.setPoolType(StoragePoolType.StorPool); + SearchBuilder sb = getStorageDao().createSearchBuilder(); + sb.and("provider", sb.entity().getStorageProviderName(), SearchCriteria.Op.EQ); + sb.and("type", sb.entity().getPoolType(), SearchCriteria.Op.EQ); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("provider", StoragePoolType.StorPool.name()); + sc.setParameters("type", StoragePoolType.SharedMountPoint.name()); + getStorageDao().update(pool, sc); + + GenericSearchBuilder gSb = getStorageDao().createSearchBuilder(Long.class); + gSb.selectFields(gSb.entity().getId()); + gSb.and("provider", gSb.entity().getStorageProviderName(), SearchCriteria.Op.EQ); + gSb.done(); + SearchCriteria gSc = gSb.create(); + gSc.setParameters("provider", StoragePoolType.StorPool.name()); + List poolIds = getStorageDao().customSearch(gSc, null); + updateStorageTypeForStorPoolVolumes(poolIds); + } + + protected void updateStorageTypeForStorPoolVolumes(List storagePoolIds) { + if (CollectionUtils.isEmpty(storagePoolIds)) { + return; + } + VolumeVO volume = getVolumeDao().createForUpdate(); + volume.setPoolType(StoragePoolType.StorPool); + SearchBuilder sb = getVolumeDao().createSearchBuilder(); + sb.and("poolId", sb.entity().getPoolId(), SearchCriteria.Op.IN); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("poolId", storagePoolIds.toArray()); + getVolumeDao().update(volume, sc); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41710to41720.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41710to41720.java index 91b7cfe978d..9854268c1ff 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41710to41720.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41710to41720.java @@ -18,14 +18,12 @@ package com.cloud.upgrade.dao; import com.cloud.upgrade.SystemVmTemplateRegistration; import com.cloud.utils.exception.CloudRuntimeException; -import org.apache.log4j.Logger; import java.io.InputStream; import java.sql.Connection; -public class Upgrade41710to41720 implements DbUpgrade, DbUpgradeSystemVmTemplate { +public class Upgrade41710to41720 extends DbUpgradeAbstractImpl implements DbUpgradeSystemVmTemplate { - final static Logger LOG = Logger.getLogger(Upgrade41710to41720.class); private SystemVmTemplateRegistration systemVmTemplateRegistration; @@ -64,7 +62,7 @@ public class Upgrade41710to41720 implements DbUpgrade, DbUpgradeSystemVmTemplate @Override public void updateSystemVmTemplates(Connection conn) { - LOG.debug("Updating System Vm template IDs"); + logger.debug("Updating System Vm template IDs"); initSystemVmTemplateRegistration(); try { systemVmTemplateRegistration.updateSystemVmTemplates(conn); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41720to41800.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41720to41800.java index 77fffb17ddd..6a90396deb0 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41720to41800.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41720to41800.java @@ -25,7 +25,6 @@ import org.apache.cloudstack.api.response.UsageTypeResponse; import org.apache.cloudstack.usage.UsageTypes; import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import org.apache.commons.lang3.time.DateUtils; -import org.apache.log4j.Logger; import java.io.InputStream; import java.sql.Connection; @@ -39,9 +38,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate { +public class Upgrade41720to41800 extends DbUpgradeAbstractImpl implements DbUpgradeSystemVmTemplate { - final static Logger LOG = Logger.getLogger(Upgrade41720to41800.class); private GuestOsMapper guestOsMapper = new GuestOsMapper(); @@ -101,7 +99,7 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate @Override public void updateSystemVmTemplates(Connection conn) { - LOG.debug("Updating System Vm template IDs"); + logger.debug("Updating System Vm template IDs"); initSystemVmTemplateRegistration(); try { systemVmTemplateRegistration.updateSystemVmTemplates(conn); @@ -111,7 +109,7 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate } protected void convertQuotaTariffsToNewParadigm(Connection conn) { - LOG.info("Converting quota tariffs to new paradigm."); + logger.info("Converting quota tariffs to new paradigm."); List usageTypeResponses = UsageTypes.listUsageTypes(); @@ -120,14 +118,14 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate String tariffTypeDescription = ReflectionToStringBuilderUtils.reflectOnlySelectedFields(usageTypeResponse, "description", "usageType"); - LOG.info(String.format("Converting quota tariffs of type %s to new paradigm.", tariffTypeDescription)); + logger.info(String.format("Converting quota tariffs of type %s to new paradigm.", tariffTypeDescription)); for (boolean previousTariff : Arrays.asList(true, false)) { Map tariffs = selectTariffs(conn, usageType, previousTariff, tariffTypeDescription); int tariffsSize = tariffs.size(); if (tariffsSize < 2) { - LOG.info(String.format("Quota tariff of type %s has [%s] %s register(s). Tariffs with less than 2 register do not need to be converted to new paradigm.", + logger.info(String.format("Quota tariff of type %s has [%s] %s register(s). Tariffs with less than 2 register do not need to be converted to new paradigm.", tariffTypeDescription, tariffsSize, previousTariff ? "previous of current" : "next to current")); continue; } @@ -143,7 +141,7 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate String selectQuotaTariffs = String.format("SELECT id, effective_on FROM cloud_usage.quota_tariff WHERE %s AND usage_type = ? ORDER BY effective_on, updated_on;", previousTariff ? "usage_name = name" : "removed is null"); - LOG.info(String.format("Selecting %s quota tariffs of type [%s] according to SQL [%s].", previousTariff ? "previous of current" : "next to current", + logger.info(String.format("Selecting %s quota tariffs of type [%s] according to SQL [%s].", previousTariff ? "previous of current" : "next to current", tariffTypeDescription, selectQuotaTariffs)); try (PreparedStatement pstmt = conn.prepareStatement(selectQuotaTariffs)) { @@ -158,7 +156,7 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate } catch (SQLException e) { String message = String.format("Unable to retrieve %s quota tariffs of type [%s] due to [%s].", previousTariff ? "previous" : "next", tariffTypeDescription, e.getMessage()); - LOG.error(message, e); + logger.error(message, e); throw new CloudRuntimeException(message, e); } } @@ -168,7 +166,7 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate Object[] ids = tariffs.keySet().toArray(); - LOG.info(String.format("Updating %s registers of %s quota tariffs of type [%s] with SQL [%s].", tariffs.size() - 1, setRemoved ? "previous of current" : + logger.info(String.format("Updating %s registers of %s quota tariffs of type [%s] with SQL [%s].", tariffs.size() - 1, setRemoved ? "previous of current" : "next to current", tariffTypeDescription, updateQuotaTariff)); for (int i = 0; i < tariffs.size() - 1; i++) { @@ -195,19 +193,19 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate pstmt.setLong(2, id); } - LOG.info(String.format("Updating \"end_date\" to [%s] %sof quota tariff with ID [%s].", sqlEndDate, updateRemoved, id)); + logger.info(String.format("Updating \"end_date\" to [%s] %sof quota tariff with ID [%s].", sqlEndDate, updateRemoved, id)); pstmt.executeUpdate(); } catch (SQLException e) { String message = String.format("Unable to update \"end_date\" %s of quota tariffs of usage type [%s] due to [%s].", setRemoved ? "and \"removed\"" : "", usageType, e.getMessage()); - LOG.error(message, e); + logger.error(message, e); throw new CloudRuntimeException(message, e); } } } protected void convertVmResourcesQuotaTypesToRunningVmQuotaType(Connection conn) { - LOG.info("Converting quota tariffs of type \"vCPU\", \"CPU_SPEED\" and \"MEMORY\" to \"RUNNING_VM\"."); + logger.info("Converting quota tariffs of type \"vCPU\", \"CPU_SPEED\" and \"MEMORY\" to \"RUNNING_VM\"."); String insertSql = "INSERT INTO cloud_usage.quota_tariff (usage_type, usage_name, usage_unit, usage_discriminator, currency_value, effective_on, updated_on," + " updated_by, uuid, name, description, removed, end_date, activation_rule)\n" @@ -225,11 +223,11 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate pstmt.executeUpdate(); } catch (SQLException e) { String message = String.format("Failed to convert quota tariffs of type \"vCPU\", \"CPU_SPEED\" and \"MEMORY\" to \"RUNNING_VM\" due to [%s].", e.getMessage()); - LOG.error(message, e); + logger.error(message, e); throw new CloudRuntimeException(message, e); } - LOG.info("Disabling unused quota tariffs of type \"vCPU\", \"CPU_SPEED\" and \"MEMORY\"."); + logger.info("Disabling unused quota tariffs of type \"vCPU\", \"CPU_SPEED\" and \"MEMORY\"."); String updateSql = "UPDATE cloud_usage.quota_tariff SET removed = now() WHERE usage_type in (15, 16, 17) and removed is null;"; @@ -237,7 +235,7 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate pstmt.executeUpdate(); } catch (SQLException e) { String message = String.format("Failed disable quota tariffs of type \"vCPU\", \"CPU_SPEED\" and \"MEMORY\" due to [%s].", e.getMessage()); - LOG.error(message, e); + logger.error(message, e); throw new CloudRuntimeException(message, e); } } @@ -251,7 +249,7 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate } private void updateGuestOsMappings() { - LOG.debug("Updating guest OS mappings"); + logger.debug("Updating guest OS mappings"); // Add support for SUSE Linux Enterprise Desktop 12 SP3 (64-bit) for Xenserver 8.1.0 List mappings = new ArrayList(); @@ -708,7 +706,7 @@ public class Upgrade41720to41800 implements DbUpgrade, DbUpgradeSystemVmTemplate } private void correctGuestOsIdsInHypervisorMapping(final Connection conn) { - LOG.debug("Correcting guest OS ids in hypervisor mappings"); + logger.debug("Correcting guest OS ids in hypervisor mappings"); guestOsMapper.updateGuestOsIdInHypervisorMapping(conn, 10, "Ubuntu 20.04 LTS", new GuestOSHypervisorMapping("Xenserver", "8.2.0", "Ubuntu Focal Fossa 20.04")); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41800to41810.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41800to41810.java index a58d9965259..b8d2e618068 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41800to41810.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41800to41810.java @@ -22,7 +22,6 @@ import com.cloud.upgrade.GuestOsMapper; import com.cloud.storage.GuestOSVO; import com.cloud.upgrade.SystemVmTemplateRegistration; import com.cloud.utils.exception.CloudRuntimeException; -import org.apache.log4j.Logger; import java.io.InputStream; import java.sql.Connection; @@ -30,8 +29,7 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; -public class Upgrade41800to41810 implements DbUpgrade, DbUpgradeSystemVmTemplate { - final static Logger LOG = Logger.getLogger(Upgrade41800to41810.class); +public class Upgrade41800to41810 extends DbUpgradeAbstractImpl implements DbUpgrade, DbUpgradeSystemVmTemplate { private GuestOsMapper guestOsMapper = new GuestOsMapper(); private SystemVmTemplateRegistration systemVmTemplateRegistration; @@ -96,7 +94,7 @@ public class Upgrade41800to41810 implements DbUpgrade, DbUpgradeSystemVmTemplate @Override public void updateSystemVmTemplates(Connection conn) { - LOG.debug("Updating System Vm template IDs"); + logger.debug("Updating System Vm template IDs"); initSystemVmTemplateRegistration(); try { systemVmTemplateRegistration.updateSystemVmTemplates(conn); @@ -106,12 +104,12 @@ public class Upgrade41800to41810 implements DbUpgrade, DbUpgradeSystemVmTemplate } private void updateGuestOsMappings(Connection conn) { - LOG.debug("Updating guest OS mappings"); + logger.debug("Updating guest OS mappings"); GuestOsMapper guestOsMapper = new GuestOsMapper(); List mappings = new ArrayList<>(); - LOG.debug("Adding Ubuntu 20.04 support for VMware 6.5+"); + logger.debug("Adding Ubuntu 20.04 support for VMware 6.5+"); guestOsMapper.addGuestOsHypervisorMapping(new GuestOSHypervisorMapping("VMware", "6.5", "ubuntu64Guest"), 10, "Ubuntu 20.04 LTS"); guestOsMapper.addGuestOsHypervisorMapping(new GuestOSHypervisorMapping("VMware", "6.7", "ubuntu64Guest"), 10, "Ubuntu 20.04 LTS"); guestOsMapper.addGuestOsHypervisorMapping(new GuestOSHypervisorMapping("VMware", "6.7.1", "ubuntu64Guest"), 10, "Ubuntu 20.04 LTS"); @@ -123,7 +121,7 @@ public class Upgrade41800to41810 implements DbUpgrade, DbUpgradeSystemVmTemplate guestOsMapper.addGuestOsHypervisorMapping(new GuestOSHypervisorMapping("VMware", "7.0.3.0", "ubuntu64Guest"), 10, "Ubuntu 20.04 LTS"); guestOsMapper.addGuestOsHypervisorMapping(new GuestOSHypervisorMapping("VMware", "8.0", "ubuntu64Guest"), 10, "Ubuntu 20.04 LTS"); - LOG.debug("Adding Ubuntu 22.04 support for KVM and VMware 6.5+"); + logger.debug("Adding Ubuntu 22.04 support for KVM and VMware 6.5+"); mappings.add(new GuestOSHypervisorMapping("KVM", "default", "Ubuntu 22.04 LTS")); mappings.add(new GuestOSHypervisorMapping("VMware", "6.5", "ubuntu64Guest")); mappings.add(new GuestOSHypervisorMapping("VMware", "6.7", "ubuntu64Guest")); @@ -138,7 +136,7 @@ public class Upgrade41800to41810 implements DbUpgrade, DbUpgradeSystemVmTemplate guestOsMapper.addGuestOsAndHypervisorMappings(10, "Ubuntu 22.04 LTS", mappings); mappings.clear(); - LOG.debug("Correcting guest OS names in hypervisor mappings for VMware 8.0 ad 8.0.0.1"); + logger.debug("Correcting guest OS names in hypervisor mappings for VMware 8.0 ad 8.0.0.1"); final String hypervisorVMware = Hypervisor.HypervisorType.VMware.name(); final String hypervisorVersionVmware8 = "8.0"; guestOsMapper.updateGuestOsNameInHypervisorMapping(1, "AlmaLinux 9", new GuestOSHypervisorMapping(hypervisorVMware, hypervisorVersionVmware8, "almalinux_64Guest")); @@ -148,7 +146,7 @@ public class Upgrade41800to41810 implements DbUpgrade, DbUpgradeSystemVmTemplate guestOsMapper.updateGuestOsNameInHypervisorMapping(1, "Oracle Linux 9", new GuestOSHypervisorMapping(hypervisorVMware, "8.0.0.1", "oracleLinux9_64Guest")); guestOsMapper.updateGuestOsNameInHypervisorMapping(1, "Rocky Linux 9", new GuestOSHypervisorMapping(hypervisorVMware, "8.0.0.1", "rockylinux_64Guest")); - LOG.debug("Correcting guest OS names in hypervisor mappings for Red Hat Enterprise Linux 9"); + logger.debug("Correcting guest OS names in hypervisor mappings for Red Hat Enterprise Linux 9"); guestOsMapper.updateGuestOsNameInHypervisorMapping(1, "Red Hat Enterprise Linux 9", new GuestOSHypervisorMapping(hypervisorVMware, "7.0", "rhel9_64Guest")); guestOsMapper.updateGuestOsNameInHypervisorMapping(1, "Red Hat Enterprise Linux 9", new GuestOSHypervisorMapping(hypervisorVMware, "7.0.1.0", "rhel9_64Guest")); guestOsMapper.updateGuestOsNameInHypervisorMapping(1, "Red Hat Enterprise Linux 9", new GuestOSHypervisorMapping(hypervisorVMware, "7.0.2.0", "rhel9_64Guest")); @@ -156,7 +154,7 @@ public class Upgrade41800to41810 implements DbUpgrade, DbUpgradeSystemVmTemplate guestOsMapper.updateGuestOsNameInHypervisorMapping(1, "Red Hat Enterprise Linux 9", new GuestOSHypervisorMapping(hypervisorVMware, hypervisorVersionVmware8, "rhel9_64Guest")); guestOsMapper.updateGuestOsNameInHypervisorMapping(1, "Red Hat Enterprise Linux 9", new GuestOSHypervisorMapping(hypervisorVMware, "8.0.0.1", "rhel9_64Guest")); - LOG.debug("Adding new guest OS ids in hypervisor mappings for VMware 8.0"); + logger.debug("Adding new guest OS ids in hypervisor mappings for VMware 8.0"); // Add support for darwin22_64Guest from VMware 8.0 mappings.add(new GuestOSHypervisorMapping(hypervisorVMware, hypervisorVersionVmware8, "darwin22_64Guest")); guestOsMapper.addGuestOsAndHypervisorMappings(7, "macOS 13 (64-bit)", mappings); @@ -209,7 +207,7 @@ public class Upgrade41800to41810 implements DbUpgrade, DbUpgradeSystemVmTemplate } private void copyGuestOsMappingsToVMware80u1() { - LOG.debug("Copying guest OS mappings from VMware 8.0 to VMware 8.0.1"); + logger.debug("Copying guest OS mappings from VMware 8.0 to VMware 8.0.1"); GuestOsMapper guestOsMapper = new GuestOsMapper(); guestOsMapper.copyGuestOSHypervisorMappings(Hypervisor.HypervisorType.VMware, "8.0", "8.0.1"); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41810to41900.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41810to41900.java index 13e30c0f6e2..e2b1ae1399b 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41810to41900.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41810to41900.java @@ -20,7 +20,6 @@ import com.cloud.upgrade.SystemVmTemplateRegistration; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.DateUtil; import com.cloud.utils.exception.CloudRuntimeException; -import org.apache.log4j.Logger; import org.jasypt.exceptions.EncryptionOperationNotPossibleException; import java.io.InputStream; @@ -34,8 +33,7 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate { - final static Logger LOG = Logger.getLogger(Upgrade41810to41900.class); +public class Upgrade41810to41900 extends DbUpgradeAbstractImpl implements DbUpgrade, DbUpgradeSystemVmTemplate { private SystemVmTemplateRegistration systemVmTemplateRegistration; private static final String ACCOUNT_DETAILS = "account_details"; @@ -97,7 +95,7 @@ public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate @Override public void updateSystemVmTemplates(Connection conn) { - LOG.debug("Updating System Vm template IDs"); + logger.debug("Updating System Vm template IDs"); initSystemVmTemplateRegistration(); try { systemVmTemplateRegistration.updateSystemVmTemplates(conn); @@ -107,15 +105,15 @@ public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate } protected void decryptConfigurationValuesFromAccountAndDomainScopesNotInSecureHiddenCategories(Connection conn) { - LOG.info("Decrypting global configuration values from the following tables: account_details and domain_details."); + logger.info("Decrypting global configuration values from the following tables: account_details and domain_details."); Map accountsMap = getConfigsWithScope(conn, ACCOUNT_DETAILS); updateConfigValuesWithScope(conn, accountsMap, ACCOUNT_DETAILS); - LOG.info("Successfully decrypted configurations from account_details table."); + logger.info("Successfully decrypted configurations from account_details table."); Map domainsMap = getConfigsWithScope(conn, DOMAIN_DETAILS); updateConfigValuesWithScope(conn, domainsMap, DOMAIN_DETAILS); - LOG.info("Successfully decrypted configurations from domain_details table."); + logger.info("Successfully decrypted configurations from domain_details table."); } protected Map getConfigsWithScope(Connection conn, String table) { @@ -132,19 +130,19 @@ public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate return configsToBeUpdated; } catch (SQLException e) { String message = String.format("Unable to retrieve data from table [%s] due to [%s].", table, e.getMessage()); - LOG.error(message, e); + logger.error(message, e); throw new CloudRuntimeException(message, e); } } public void migrateBackupDates(Connection conn) { - LOG.info("Trying to convert backups' date column from varchar(255) to datetime type."); + logger.info("Trying to convert backups' date column from varchar(255) to datetime type."); modifyDateColumnNameAndCreateNewOne(conn); fetchDatesAndMigrateToNewColumn(conn); dropOldColumn(conn); - LOG.info("Finished converting backups' date column from varchar(255) to datetime."); + logger.info("Finished converting backups' date column from varchar(255) to datetime."); } private void modifyDateColumnNameAndCreateNewOne(Connection conn) { @@ -153,7 +151,7 @@ public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate pstmt.execute(); } catch (SQLException e) { String message = String.format("Unable to alter backups' date column name due to [%s].", e.getMessage()); - LOG.error(message, e); + logger.error(message, e); throw new CloudRuntimeException(message, e); } @@ -162,7 +160,7 @@ public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate pstmt.execute(); } catch (SQLException e) { String message = String.format("Unable to crate new backups' column date due to [%s].", e.getMessage()); - LOG.error(message, e); + logger.error(message, e); throw new CloudRuntimeException(message, e); } } @@ -177,12 +175,12 @@ public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate pstmt.setString(1, decryptedValue); pstmt.setLong(2, config.getKey()); - LOG.info(String.format("Updating config with ID [%s] to value [%s].", config.getKey(), decryptedValue)); + logger.info(String.format("Updating config with ID [%s] to value [%s].", config.getKey(), decryptedValue)); pstmt.executeUpdate(); } catch (SQLException | EncryptionOperationNotPossibleException e) { String message = String.format("Unable to update config value with ID [%s] on table [%s] due to [%s]. The config value may already be decrypted.", config.getKey(), table, e); - LOG.error(message); + logger.error(message); throw new CloudRuntimeException(message, e); } } @@ -203,7 +201,7 @@ public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate } } catch (SQLException e) { String message = String.format("Unable to retrieve backup dates due to [%s].", e.getMessage()); - LOG.error(message, e); + logger.error(message, e); throw new CloudRuntimeException(message, e); } } @@ -224,7 +222,7 @@ public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate } if (parsedDate == null) { String msg = String.format("Unable to parse date [%s]. Will change backup date to null.", date); - LOG.error(msg); + logger.error(msg); return null; } @@ -240,7 +238,7 @@ public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate pstmt.executeUpdate(); } catch (SQLException e) { String message = String.format("Unable to update backup date with id [%s] to date [%s] due to [%s].", id, date, e.getMessage()); - LOG.error(message, e); + logger.error(message, e); throw new CloudRuntimeException(message, e); } } @@ -251,7 +249,7 @@ public class Upgrade41810to41900 implements DbUpgrade, DbUpgradeSystemVmTemplate pstmt.execute(); } catch (SQLException e) { String message = String.format("Unable to drop old_date column due to [%s].", e.getMessage()); - LOG.error(message, e); + logger.error(message, e); throw new CloudRuntimeException(message, e); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41900to41910.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41900to41910.java index 4cdd1c3364d..4eb8e9bdb2a 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41900to41910.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41900to41910.java @@ -16,16 +16,13 @@ // under the License. package com.cloud.upgrade.dao; -import org.apache.log4j.Logger; - import com.cloud.upgrade.SystemVmTemplateRegistration; import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -public class Upgrade41900to41910 implements DbUpgrade, DbUpgradeSystemVmTemplate { - final static Logger LOG = Logger.getLogger(Upgrade41900to41910.class); +public class Upgrade41900to41910 extends DbUpgradeAbstractImpl implements DbUpgrade, DbUpgradeSystemVmTemplate { private SystemVmTemplateRegistration systemVmTemplateRegistration; @Override @@ -80,7 +77,7 @@ public class Upgrade41900to41910 implements DbUpgrade, DbUpgradeSystemVmTemplate @Override public void updateSystemVmTemplates(Connection conn) { - LOG.debug("Updating System Vm template IDs"); + logger.debug("Updating System Vm template IDs"); initSystemVmTemplateRegistration(); try { systemVmTemplateRegistration.updateSystemVmTemplates(conn); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41910to42000.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41910to42000.java new file mode 100644 index 00000000000..4c26c6bde50 --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41910to42000.java @@ -0,0 +1,116 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.upgrade.dao; + +import java.io.InputStream; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import com.cloud.upgrade.SystemVmTemplateRegistration; +import com.cloud.utils.exception.CloudRuntimeException; + +public class Upgrade41910to42000 extends DbUpgradeAbstractImpl implements DbUpgrade, DbUpgradeSystemVmTemplate { + private SystemVmTemplateRegistration systemVmTemplateRegistration; + private static final int MAX_INDEXED_CHARS_IN_CHAR_SET_UTF8MB4 = 191; + + @Override + public String[] getUpgradableVersionRange() { + return new String[] {"4.19.1.0", "4.20.0.0"}; + } + + @Override + public String getUpgradedVersion() { + return "4.20.0.0"; + } + + @Override + public boolean supportsRollingUpgrade() { + return false; + } + + @Override + public InputStream[] getPrepareScripts() { + final String scriptFile = "META-INF/db/schema-41910to42000.sql"; + final InputStream script = Thread.currentThread().getContextClassLoader().getResourceAsStream(scriptFile); + if (script == null) { + throw new CloudRuntimeException("Unable to find " + scriptFile); + } + + return new InputStream[] {script}; + } + + @Override + public void performDataMigration(Connection conn) { + checkAndUpdateAffinityGroupNameCharSetToUtf8mb4(conn); + } + + @Override + public InputStream[] getCleanupScripts() { + final String scriptFile = "META-INF/db/schema-41910to42000-cleanup.sql"; + final InputStream script = Thread.currentThread().getContextClassLoader().getResourceAsStream(scriptFile); + if (script == null) { + throw new CloudRuntimeException("Unable to find " + scriptFile); + } + + return new InputStream[] {script}; + } + + private void initSystemVmTemplateRegistration() { + systemVmTemplateRegistration = new SystemVmTemplateRegistration(""); + } + + @Override + public void updateSystemVmTemplates(Connection conn) { + logger.debug("Updating System Vm template IDs"); + initSystemVmTemplateRegistration(); + try { + systemVmTemplateRegistration.updateSystemVmTemplates(conn); + } catch (Exception e) { + throw new CloudRuntimeException("Failed to find / register SystemVM template(s)"); + } + } + + private void checkAndUpdateAffinityGroupNameCharSetToUtf8mb4(Connection conn) { + logger.debug("Check and update char set for affinity group name to utf8mb4"); + try { + PreparedStatement pstmt = conn.prepareStatement("SELECT MAX(LENGTH(name)) FROM `cloud`.`affinity_group`"); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) { + long maxLengthOfName = rs.getLong(1); + if (maxLengthOfName <= MAX_INDEXED_CHARS_IN_CHAR_SET_UTF8MB4) { + pstmt = conn.prepareStatement(String.format("ALTER TABLE `cloud`.`affinity_group` MODIFY `name` VARCHAR(%d) CHARACTER SET utf8mb4 NOT NULL", MAX_INDEXED_CHARS_IN_CHAR_SET_UTF8MB4)); + pstmt.executeUpdate(); + logger.debug("Successfully updated char set for affinity group name to utf8mb4"); + } else { + logger.warn("Unable to update char set for affinity group name, as there are some names with more than " + MAX_INDEXED_CHARS_IN_CHAR_SET_UTF8MB4 + + " chars (max supported chars for index)"); + } + } + + if (rs != null && !rs.isClosed()) { + rs.close(); + } + if (pstmt != null && !pstmt.isClosed()) { + pstmt.close(); + } + } catch (final SQLException e) { + logger.warn("Exception while updating char set for affinity group name to utf8mb4: " + e.getMessage()); + } + } +} diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade42000to42010.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade42000to42010.java new file mode 100644 index 00000000000..0c0a9f070ba --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade42000to42010.java @@ -0,0 +1,120 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.upgrade.dao; + +import java.io.InputStream; +import java.sql.Connection; + +import com.cloud.upgrade.SystemVmTemplateRegistration; +import com.cloud.utils.exception.CloudRuntimeException; + +public class Upgrade42000to42010 extends DbUpgradeAbstractImpl implements DbUpgrade, DbUpgradeSystemVmTemplate { + private SystemVmTemplateRegistration systemVmTemplateRegistration; + + @Override + public String[] getUpgradableVersionRange() { + return new String[] {"4.20.0.0", "4.20.1.0"}; + } + + @Override + public String getUpgradedVersion() { + return "4.20.1.0"; + } + + @Override + public boolean supportsRollingUpgrade() { + return false; + } + + @Override + public InputStream[] getPrepareScripts() { + final String scriptFile = "META-INF/db/schema-42000to42010.sql"; + final InputStream script = Thread.currentThread().getContextClassLoader().getResourceAsStream(scriptFile); + if (script == null) { + throw new CloudRuntimeException("Unable to find " + scriptFile); + } + + return new InputStream[] {script}; + } + + @Override + public void performDataMigration(Connection conn) { + addIndexes(conn); + } + + @Override + public InputStream[] getCleanupScripts() { + final String scriptFile = "META-INF/db/schema-42000to42010-cleanup.sql"; + final InputStream script = Thread.currentThread().getContextClassLoader().getResourceAsStream(scriptFile); + if (script == null) { + throw new CloudRuntimeException("Unable to find " + scriptFile); + } + + return new InputStream[] {script}; + } + + private void initSystemVmTemplateRegistration() { + systemVmTemplateRegistration = new SystemVmTemplateRegistration(""); + } + + @Override + public void updateSystemVmTemplates(Connection conn) { + logger.debug("Updating System Vm template IDs"); + initSystemVmTemplateRegistration(); + try { + systemVmTemplateRegistration.updateSystemVmTemplates(conn); + } catch (Exception e) { + throw new CloudRuntimeException("Failed to find / register SystemVM template(s)", e); + } + } + + private void addIndexes(Connection conn) { + DbUpgradeUtils.addIndexIfNeeded(conn, "host", "mgmt_server_id"); + DbUpgradeUtils.addIndexIfNeeded(conn, "host", "resource"); + DbUpgradeUtils.addIndexIfNeeded(conn, "host", "resource_state"); + DbUpgradeUtils.addIndexIfNeeded(conn, "host", "type"); + + DbUpgradeUtils.renameIndexIfNeeded(conn, "user_ip_address", "public_ip_address", "uk_public_ip_address"); + DbUpgradeUtils.addIndexIfNeeded(conn, "user_ip_address", "public_ip_address"); + DbUpgradeUtils.addIndexIfNeeded(conn, "user_ip_address", "data_center_id"); + DbUpgradeUtils.addIndexIfNeeded(conn, "user_ip_address", "vlan_db_id"); + DbUpgradeUtils.addIndexIfNeeded(conn, "user_ip_address", "removed"); + + DbUpgradeUtils.addIndexIfNeeded(conn, "vlan", "vlan_type"); + DbUpgradeUtils.addIndexIfNeeded(conn, "vlan", "data_center_id"); + DbUpgradeUtils.addIndexIfNeeded(conn, "vlan", "removed"); + + DbUpgradeUtils.addIndexIfNeeded(conn, "network_offering_details", "name"); + + DbUpgradeUtils.addIndexIfNeeded(conn, "service_offering", "cpu"); + DbUpgradeUtils.addIndexIfNeeded(conn, "service_offering", "speed"); + DbUpgradeUtils.addIndexIfNeeded(conn, "service_offering", "ram_size"); + + DbUpgradeUtils.addIndexIfNeeded(conn, "op_host_planner_reservation", "resource_usage"); + + DbUpgradeUtils.addIndexIfNeeded(conn, "storage_pool", "pool_type"); + DbUpgradeUtils.addIndexIfNeeded(conn, "storage_pool", "data_center_id", "status", "scope", "hypervisor"); + + DbUpgradeUtils.addIndexIfNeeded(conn, "router_network_ref", "guest_type"); + + DbUpgradeUtils.addIndexIfNeeded(conn, "domain_router", "role"); + + DbUpgradeUtils.addIndexIfNeeded(conn, "async_job", "instance_type", "job_status"); + + DbUpgradeUtils.addIndexIfNeeded(conn, "cluster", "managed_state"); + } +} diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade420to421.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade420to421.java index d7ba2ed20da..9ca342d7f4a 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade420to421.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade420to421.java @@ -23,13 +23,11 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import org.apache.log4j.Logger; import com.cloud.hypervisor.Hypervisor; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade420to421 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade420to421.class); +public class Upgrade420to421 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -89,7 +87,7 @@ public class Upgrade420to421 implements DbUpgrade { } } // Need to populate only when overprovisioning factor doesn't pre exist. - s_logger.debug("Starting updating user_vm_details with cpu/memory overprovisioning factors"); + logger.debug("Starting updating user_vm_details with cpu/memory overprovisioning factors"); try ( PreparedStatement pstmt2 = conn .prepareStatement("select id, hypervisor_type from `cloud`.`vm_instance` where removed is null and id not in (select vm_id from `cloud`.`user_vm_details` where name='cpuOvercommitRatio')"); @@ -123,14 +121,14 @@ public class Upgrade420to421 implements DbUpgrade { } } } - s_logger.debug("Done updating user_vm_details with cpu/memory overprovisioning factors"); + logger.debug("Done updating user_vm_details with cpu/memory overprovisioning factors"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to update cpu/memory overprovisioning factors", e); } } private void upgradeResourceCount(Connection conn) { - s_logger.debug("upgradeResourceCount start"); + logger.debug("upgradeResourceCount start"); String sqlSelectAccountIds = "select id, domain_id FROM `cloud`.`account` where removed is NULL "; String sqlSelectOfferingTotals = "SELECT SUM(service_offering.cpu), SUM(service_offering.ram_size)" + " FROM `cloud`.`vm_instance`, `cloud`.`service_offering`" @@ -236,7 +234,7 @@ public class Upgrade420to421 implements DbUpgrade { } } } - s_logger.debug("upgradeResourceCount finish"); + logger.debug("upgradeResourceCount finish"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to upgrade resource count (cpu,memory,primary_storage,secondary_storage) ", e); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade421to430.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade421to430.java index 55e7d3bdac2..88428f455f3 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade421to430.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade421to430.java @@ -24,13 +24,11 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import org.apache.log4j.Logger; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade421to430 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade421to430.class); +public class Upgrade421to430 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -88,11 +86,11 @@ public class Upgrade421to430 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Unable to upgrade ram_size of service offering for secondary storage vm. ", e); } - s_logger.debug("Done upgrading RAM for service offering of Secondary Storage VM to " + newRamSize); + logger.debug("Done upgrading RAM for service offering of Secondary Storage VM to " + newRamSize); } private void encryptImageStoreDetails(Connection conn) { - s_logger.debug("Encrypting image store details"); + logger.debug("Encrypting image store details"); try ( PreparedStatement selectPstmt = conn.prepareStatement("select id, value from `cloud`.`image_store_details` where name = 'key' or name = 'secretkey'"); ResultSet rs = selectPstmt.executeQuery(); @@ -115,7 +113,7 @@ public class Upgrade421to430 implements DbUpgrade { } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt image_store_details values ", e); } - s_logger.debug("Done encrypting image_store_details"); + logger.debug("Done encrypting image_store_details"); } @Override diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade430to440.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade430to440.java index 43d4d877361..9a2077471e6 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade430to440.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade430to440.java @@ -23,14 +23,12 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import org.apache.log4j.Logger; import com.cloud.network.Network; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade430to440 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade430to440.class); +public class Upgrade430to440 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -163,12 +161,12 @@ public class Upgrade430to440 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e); } - s_logger.debug("Done updating vm nic secondary ip account and domain ids"); + logger.debug("Done updating vm nic secondary ip account and domain ids"); } private void moveCidrsToTheirOwnTable(Connection conn) { - s_logger.debug("Moving network acl item cidrs to a row per cidr"); + logger.debug("Moving network acl item cidrs to a row per cidr"); String networkAclItemSql = "SELECT id, cidr FROM `cloud`.`network_acl_item`"; String networkAclItemCidrSql = "INSERT INTO `cloud`.`network_acl_item_cidrs` (network_acl_item_id, cidr) VALUES (?,?)"; @@ -184,7 +182,7 @@ public class Upgrade430to440 implements DbUpgrade { long itemId = rsItems.getLong(1); // get the source cidr list String cidrList = rsItems.getString(2); - s_logger.debug("Moving '" + cidrList + "' to a row per cidr"); + logger.debug("Moving '" + cidrList + "' to a row per cidr"); // split it String[] cidrArray = cidrList.split(","); // insert a record per cidr @@ -197,11 +195,11 @@ public class Upgrade430to440 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Exception while Moving network acl item cidrs to a row per cidr", e); } - s_logger.debug("Done moving network acl item cidrs to a row per cidr"); + logger.debug("Done moving network acl item cidrs to a row per cidr"); } private void updateVlanUris(Connection conn) { - s_logger.debug("updating vlan URIs"); + logger.debug("updating vlan URIs"); try(PreparedStatement selectstatement = conn.prepareStatement("SELECT id, vlan_id FROM `cloud`.`vlan` where vlan_id not like '%:%'"); ResultSet results = selectstatement.executeQuery()) { @@ -224,7 +222,7 @@ public class Upgrade430to440 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Unable to update vlan URIs ", e); } - s_logger.debug("Done updating vlan URIs"); + logger.debug("Done updating vlan URIs"); } @Override diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade431to440.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade431to440.java index 98b52ac0aa9..54aa3b76d6f 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade431to440.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade431to440.java @@ -17,10 +17,8 @@ package com.cloud.upgrade.dao; -import org.apache.log4j.Logger; -public class Upgrade431to440 extends Upgrade430to440 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade431to440.class); +public class Upgrade431to440 extends Upgrade430to440 { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade432to440.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade432to440.java index ded0db474d5..3b934c1f344 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade432to440.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade432to440.java @@ -17,10 +17,8 @@ package com.cloud.upgrade.dao; -import org.apache.log4j.Logger; -public class Upgrade432to440 extends Upgrade431to440 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade432to440.class); +public class Upgrade432to440 extends Upgrade431to440 { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade440to441.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade440to441.java index a51f464a797..4309a1a53c5 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade440to441.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade440to441.java @@ -22,7 +22,7 @@ import java.sql.Connection; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade440to441 implements DbUpgrade { +public class Upgrade440to441 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade441to442.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade441to442.java index 4234428f72b..1993b15b640 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade441to442.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade441to442.java @@ -23,7 +23,7 @@ import java.sql.Connection; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade441to442 implements DbUpgrade { +public class Upgrade441to442 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade442to450.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade442to450.java index 54e8da5f6e9..803d521ac24 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade442to450.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade442to450.java @@ -28,13 +28,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade442to450 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade442to450.class); +public class Upgrade442to450 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -82,7 +80,7 @@ public class Upgrade442to450 implements DbUpgrade { } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt configuration values ", e); } - s_logger.debug("Done updating router.ram.size config to 256"); + logger.debug("Done updating router.ram.size config to 256"); } private void upgradeMemoryOfVirtualRoutervmOffering(Connection conn) { @@ -109,7 +107,7 @@ public class Upgrade442to450 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Unable to upgrade ram_size of service offering for domain router. ", e); } - s_logger.debug("Done upgrading RAM for service offering of domain router to " + newRamSize); + logger.debug("Done upgrading RAM for service offering of domain router to " + newRamSize); } private void upgradeMemoryOfInternalLoadBalancervmOffering(Connection conn) { @@ -134,7 +132,7 @@ public class Upgrade442to450 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Unable to upgrade ram_size of service offering for internal loadbalancer vm. ", e); } - s_logger.debug("Done upgrading RAM for service offering of internal loadbalancer vm to " + newRamSize); + logger.debug("Done upgrading RAM for service offering of internal loadbalancer vm to " + newRamSize); } @Override @@ -155,7 +153,7 @@ public class Upgrade442to450 implements DbUpgrade { keys.add("id_2"); uniqueKeys.put("storage_pool", keys); - s_logger.debug("Dropping id_2 key from storage_pool table"); + logger.debug("Dropping id_2 key from storage_pool table"); for (Map.Entry> entry: uniqueKeys.entrySet()) { DbUpgradeUtils.dropKeysIfExist(conn,entry.getKey(), entry.getValue(), false); } @@ -168,7 +166,7 @@ public class Upgrade442to450 implements DbUpgrade { keys.add("fk_async_job_join_map__join_job_id"); foreignKeys.put("async_job_join_map", keys); - s_logger.debug("Dropping fk_async_job_join_map__join_job_id key from async_job_join_map table"); + logger.debug("Dropping fk_async_job_join_map__join_job_id key from async_job_join_map table"); for (Map.Entry> entry: foreignKeys.entrySet()) { DbUpgradeUtils.dropKeysIfExist(conn,entry.getKey(), entry.getValue(), true); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade443to444.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade443to444.java index b8110546a13..61674d9870f 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade443to444.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade443to444.java @@ -22,7 +22,7 @@ import java.sql.Connection; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade443to444 implements DbUpgrade { +public class Upgrade443to444 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade443to450.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade443to450.java index 80b2c14e00c..9f571fedc2c 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade443to450.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade443to450.java @@ -17,7 +17,7 @@ package com.cloud.upgrade.dao; -public class Upgrade443to450 extends Upgrade442to450 implements DbUpgrade { +public class Upgrade443to450 extends Upgrade442to450 { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade444to450.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade444to450.java index 52fc7299810..d393e73f59a 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade444to450.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade444to450.java @@ -17,7 +17,7 @@ package com.cloud.upgrade.dao; -public class Upgrade444to450 extends Upgrade442to450 implements DbUpgrade { +public class Upgrade444to450 extends Upgrade442to450 { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade450to451.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade450to451.java index 015d463347a..ffdf2cc1273 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade450to451.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade450to451.java @@ -26,13 +26,11 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade450to451 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade450to451.class); +public class Upgrade450to451 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -97,7 +95,7 @@ public class Upgrade450to451 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Exception while encrypting key column in keystore table", e); } - s_logger.debug("Done encrypting keystore's key column"); + logger.debug("Done encrypting keystore's key column"); } private void encryptIpSecPresharedKeysOfRemoteAccessVpn(Connection conn) { @@ -111,7 +109,7 @@ public class Upgrade450to451 implements DbUpgrade { try { preSharedKey = DBEncryptionUtil.decrypt(preSharedKey); } catch (CloudRuntimeException ignored) { - s_logger.debug("The ipsec_psk preshared key id=" + rowId + "in remote_access_vpn is not encrypted, encrypting it."); + logger.debug("The ipsec_psk preshared key id=" + rowId + "in remote_access_vpn is not encrypted, encrypting it."); } try (PreparedStatement updateStatement = conn.prepareStatement("UPDATE `cloud`.`remote_access_vpn` SET ipsec_psk=? WHERE id=?");) { updateStatement.setString(1, DBEncryptionUtil.encrypt(preSharedKey)); @@ -122,7 +120,7 @@ public class Upgrade450to451 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Unable to update the remote_access_vpn's preshared key ipsec_psk column", e); } - s_logger.debug("Done encrypting remote_access_vpn's ipsec_psk column"); + logger.debug("Done encrypting remote_access_vpn's ipsec_psk column"); } private void encryptStoragePoolUserInfo(Connection conn) { @@ -151,7 +149,7 @@ public class Upgrade450to451 implements DbUpgrade { } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt storage pool user info ", e); } - s_logger.debug("Done encrypting storage_pool's user_info column"); + logger.debug("Done encrypting storage_pool's user_info column"); } private void updateUserVmDetailsWithNicAdapterType(Connection conn) { @@ -160,13 +158,13 @@ public class Upgrade450to451 implements DbUpgrade { } catch (SQLException e) { throw new CloudRuntimeException("Failed to update user_vm_details table with nicAdapter entries by copying from vm_template_detail table", e); } - s_logger.debug("Done. Updated user_vm_details table with nicAdapter entries by copying from vm_template_detail table. This affects only VM/templates with hypervisor_type as VMware."); + logger.debug("Done. Updated user_vm_details table with nicAdapter entries by copying from vm_template_detail table. This affects only VM/templates with hypervisor_type as VMware."); } private void upgradeVMWareLocalStorage(Connection conn) { try (PreparedStatement updatePstmt = conn.prepareStatement("UPDATE storage_pool SET pool_type='VMFS',host_address=@newaddress WHERE (@newaddress:=concat('VMFS datastore: ', path)) IS NOT NULL AND scope = 'HOST' AND pool_type = 'LVM' AND id IN (SELECT * FROM (SELECT storage_pool.id FROM storage_pool,cluster WHERE storage_pool.cluster_id = cluster.id AND cluster.hypervisor_type='VMware') AS t);");) { updatePstmt.executeUpdate(); - s_logger.debug("Done, upgraded VMWare local storage pool type to VMFS and host_address to the VMFS format"); + logger.debug("Done, upgraded VMWare local storage pool type to VMFS and host_address to the VMFS format"); } catch (SQLException e) { throw new CloudRuntimeException("Unable to upgrade VMWare local storage pool type", e); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade451to452.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade451to452.java index 788b6f28ef1..d019558a33c 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade451to452.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade451to452.java @@ -22,7 +22,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -public class Upgrade451to452 implements DbUpgrade { +public class Upgrade451to452 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade452to453.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade452to453.java index 3bc39ebc68f..17ec3414896 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade452to453.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade452to453.java @@ -22,7 +22,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -public class Upgrade452to453 implements DbUpgrade { +public class Upgrade452to453 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade452to460.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade452to460.java index 91fe345f4a1..d14d6c9e543 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade452to460.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade452to460.java @@ -25,12 +25,10 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade452to460 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade452to460.class); +public class Upgrade452to460 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -67,7 +65,7 @@ public class Upgrade452to460 implements DbUpgrade { public void updateVMInstanceUserId(final Connection conn) { // For schemas before this, copy first user from an account_id which // deployed already running VMs - s_logger.debug("Updating vm_instance column user_id using first user in vm_instance's account_id"); + logger.debug("Updating vm_instance column user_id using first user in vm_instance's account_id"); final String vmInstanceSql = "SELECT id, account_id FROM `cloud`.`vm_instance`"; final String userSql = "SELECT id FROM `cloud`.`user` where account_id=?"; final String userIdUpdateSql = "update `cloud`.`vm_instance` set user_id=? where id=?"; @@ -97,7 +95,7 @@ public class Upgrade452to460 implements DbUpgrade { } catch (final SQLException e) { throw new CloudRuntimeException("Unable to update user Ids for previously deployed VMs", e); } - s_logger.debug("Done updating user Ids for previously deployed VMs"); + logger.debug("Done updating user Ids for previously deployed VMs"); addRedundancyForNwAndVpc(conn); removeBumPriorityColumn(conn); } @@ -142,14 +140,14 @@ public class Upgrade452to460 implements DbUpgrade { private void addIndexForVMInstance(final Connection conn) { // Drop index if it exists final List indexList = new ArrayList(); - s_logger.debug("Dropping index i_vm_instance__instance_name from vm_instance table if it exists"); + logger.debug("Dropping index i_vm_instance__instance_name from vm_instance table if it exists"); indexList.add("i_vm_instance__instance_name"); DbUpgradeUtils.dropKeysIfExist(conn, "vm_instance", indexList, false); // Now add index try (PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`vm_instance` ADD INDEX `i_vm_instance__instance_name`(`instance_name`)");) { pstmt.executeUpdate(); - s_logger.debug("Added index i_vm_instance__instance_name to vm_instance table"); + logger.debug("Added index i_vm_instance__instance_name to vm_instance table"); } catch (final SQLException e) { throw new CloudRuntimeException("Unable to add index i_vm_instance__instance_name to vm_instance table for the column instance_name", e); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade453to460.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade453to460.java index 2dd4b0aad27..321d0304f9d 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade453to460.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade453to460.java @@ -17,7 +17,7 @@ package com.cloud.upgrade.dao; -public class Upgrade453to460 extends Upgrade452to460 implements DbUpgrade { +public class Upgrade453to460 extends Upgrade452to460 { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade460to461.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade460to461.java index 88bda4616c8..3642a59e516 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade460to461.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade460to461.java @@ -22,7 +22,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -public class Upgrade460to461 implements DbUpgrade { +public class Upgrade460to461 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade461to470.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade461to470.java index e7922cebf0a..d2241e0498c 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade461to470.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade461to470.java @@ -18,15 +18,13 @@ package com.cloud.upgrade.dao; import com.cloud.utils.exception.CloudRuntimeException; -import org.apache.log4j.Logger; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; -public class Upgrade461to470 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade461to470.class); +public class Upgrade461to470 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -58,10 +56,10 @@ public class Upgrade461to470 implements DbUpgrade { final String alterTableSql = "ALTER TABLE `cloud_usage`.`cloud_usage` ADD COLUMN `quota_calculated` tinyint(1) DEFAULT 0 NOT NULL COMMENT 'quota calculation status'"; try (PreparedStatement pstmt = conn.prepareStatement(alterTableSql)) { pstmt.executeUpdate(); - s_logger.info("Altered cloud_usage.cloud_usage table and added column quota_calculated"); + logger.info("Altered cloud_usage.cloud_usage table and added column quota_calculated"); } catch (SQLException e) { if (e.getMessage().contains("quota_calculated")) { - s_logger.warn("cloud_usage.cloud_usage table already has a column called quota_calculated"); + logger.warn("cloud_usage.cloud_usage table already has a column called quota_calculated"); } else { throw new CloudRuntimeException("Unable to create column quota_calculated in table cloud_usage.cloud_usage", e); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade470to471.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade470to471.java index 08cdfdd53f5..0464381dd60 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade470to471.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade470to471.java @@ -22,7 +22,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -public class Upgrade470to471 implements DbUpgrade { +public class Upgrade470to471 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade471to480.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade471to480.java index 3b3a0bba03e..614e1d8779e 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade471to480.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade471to480.java @@ -22,7 +22,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -public class Upgrade471to480 implements DbUpgrade { +public class Upgrade471to480 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade480to481.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade480to481.java index be33709dd92..d1aa4214837 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade480to481.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade480to481.java @@ -22,7 +22,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -public class Upgrade480to481 implements DbUpgrade { +public class Upgrade480to481 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade481to490.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade481to490.java index 2165d809f85..5c950a86b0e 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade481to490.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade481to490.java @@ -27,13 +27,11 @@ import java.sql.SQLException; import com.cloud.user.Account; import org.apache.cloudstack.acl.RoleType; -import org.apache.log4j.Logger; import com.cloud.utils.db.ScriptRunner; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade481to490 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade481to490.class); +public class Upgrade481to490 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { @@ -74,7 +72,7 @@ public class Upgrade481to490 implements DbUpgrade { final Integer accountType = selectResultSet.getInt(2); final Long roleId = RoleType.getByAccountType(Account.Type.getFromValue(accountType)).getId(); if (roleId < 1L || roleId > 4L) { - s_logger.warn("Skipping role ID migration due to invalid role_id resolved for account id=" + accountId); + logger.warn("Skipping role ID migration due to invalid role_id resolved for account id=" + accountId); continue; } try (final PreparedStatement updateStatement = conn.prepareStatement("UPDATE `cloud`.`account` SET account.role_id = ? WHERE account.id = ? ;")) { @@ -82,14 +80,14 @@ public class Upgrade481to490 implements DbUpgrade { updateStatement.setLong(2, accountId); updateStatement.executeUpdate(); } catch (SQLException e) { - s_logger.error("Failed to update cloud.account role_id for account id:" + accountId + " with exception: " + e.getMessage()); + logger.error("Failed to update cloud.account role_id for account id:" + accountId + " with exception: " + e.getMessage()); throw new CloudRuntimeException("Exception while updating cloud.account role_id", e); } } } catch (SQLException e) { throw new CloudRuntimeException("Exception while migrating existing account table's role_id column to a role based on account type", e); } - s_logger.debug("Done migrating existing accounts to use one of default roles based on account type"); + logger.debug("Done migrating existing accounts to use one of default roles based on account type"); } private void setupRolesAndPermissionsForDynamicChecker(final Connection conn) { @@ -101,7 +99,7 @@ public class Upgrade481to490 implements DbUpgrade { pstmt.executeUpdate(); } catch (SQLException e) { if (e.getMessage().contains("role_id")) { - s_logger.warn("cloud.account table already has the role_id column, skipping altering table and migration of accounts"); + logger.warn("cloud.account table already has the role_id column, skipping altering table and migration of accounts"); return; } else { throw new CloudRuntimeException("Unable to create column role_id in table cloud.account", e); @@ -116,20 +114,20 @@ public class Upgrade481to490 implements DbUpgrade { migrateAccountsToDefaultRoles(conn); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Configuring default role-api mappings, use migrate-dynamicroles.py instead if you want to migrate rules from an existing commands.properties file"); + if (logger.isDebugEnabled()) { + logger.debug("Configuring default role-api mappings, use migrate-dynamicroles.py instead if you want to migrate rules from an existing commands.properties file"); } final String scriptFile = "META-INF/db/create-default-role-api-mappings.sql"; final InputStream script = Thread.currentThread().getContextClassLoader().getResourceAsStream(scriptFile); if (script == null) { - s_logger.error("Unable to find default role-api mapping sql file, please configure api per role manually"); + logger.error("Unable to find default role-api mapping sql file, please configure api per role manually"); return; } try(final InputStreamReader reader = new InputStreamReader(script)) { ScriptRunner runner = new ScriptRunner(conn, false, true); runner.runScript(reader); } catch (SQLException | IOException e) { - s_logger.error("Unable to insert default api-role mappings from file: " + script + ". Please configure api per role manually, giving up!", e); + logger.error("Unable to insert default api-role mappings from file: " + script + ". Please configure api per role manually, giving up!", e); } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade490to4910.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade490to4910.java index 8757d7fa539..fdb5fd261b9 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade490to4910.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade490to4910.java @@ -22,7 +22,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -public class Upgrade490to4910 implements DbUpgrade { +public class Upgrade490to4910 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4910to4920.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4910to4920.java index 1950c8f28b8..69cd5b796a8 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4910to4920.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4910to4920.java @@ -22,7 +22,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -public class Upgrade4910to4920 implements DbUpgrade { +public class Upgrade4910to4920 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4920to4930.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4920to4930.java index bc02c95064c..9f5437e8d87 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4920to4930.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4920to4930.java @@ -22,7 +22,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import java.io.InputStream; import java.sql.Connection; -public class Upgrade4920to4930 implements DbUpgrade { +public class Upgrade4920to4930 extends DbUpgradeAbstractImpl { @Override public String[] getUpgradableVersionRange() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4930to41000.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4930to41000.java index 46abd44aa6a..631308a975e 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4930to41000.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade4930to41000.java @@ -23,12 +23,10 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.HashMap; -import org.apache.log4j.Logger; import com.cloud.utils.exception.CloudRuntimeException; -public class Upgrade4930to41000 implements DbUpgrade { - final static Logger s_logger = Logger.getLogger(Upgrade4930to41000.class); +public class Upgrade4930to41000 extends DbUpgradeAbstractImpl { public static class MemoryValues { long max; diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/UpgradeSnapshot217to224.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/UpgradeSnapshot217to224.java index 3e39f81f761..4c856ab154e 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/UpgradeSnapshot217to224.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/UpgradeSnapshot217to224.java @@ -21,7 +21,7 @@ import java.sql.Connection; import com.cloud.utils.exception.CloudRuntimeException; -public class UpgradeSnapshot217to224 implements DbUpgrade { +public class UpgradeSnapshot217to224 extends DbUpgradeAbstractImpl { @Override public InputStream[] getPrepareScripts() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/UpgradeSnapshot223to224.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/UpgradeSnapshot223to224.java index 8e546e7dd4d..7a5b7de17b5 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/UpgradeSnapshot223to224.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/UpgradeSnapshot223to224.java @@ -21,7 +21,7 @@ import java.sql.Connection; import com.cloud.utils.exception.CloudRuntimeException; -public class UpgradeSnapshot223to224 implements DbUpgrade { +public class UpgradeSnapshot223to224 extends DbUpgradeAbstractImpl { @Override public InputStream[] getPrepareScripts() { diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/VersionDaoImpl.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/VersionDaoImpl.java index 67fe70fdb29..90e1912408c 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/VersionDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/VersionDaoImpl.java @@ -23,7 +23,6 @@ import java.sql.SQLException; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.upgrade.dao.VersionVO.Step; @@ -40,7 +39,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component @DB() public class VersionDaoImpl extends GenericDaoBase implements VersionDao { - private static final Logger s_logger = Logger.getLogger(VersionDaoImpl.class); final GenericSearchBuilder CurrentVersionSearch; final SearchBuilder AllFieldsSearch; @@ -74,7 +72,7 @@ public class VersionDaoImpl extends GenericDaoBase implements V @DB public String getCurrentVersion() { try (Connection conn = TransactionLegacy.getStandaloneConnection();) { - s_logger.debug("Checking to see if the database is at a version before it was the version table is created"); + logger.debug("Checking to see if the database is at a version before it was the version table is created"); try ( PreparedStatement pstmt = conn.prepareStatement("SHOW TABLES LIKE 'version'"); @@ -89,8 +87,8 @@ public class VersionDaoImpl extends GenericDaoBase implements V pstmt_domain.executeQuery(); return "2.1.8"; } catch (final SQLException e) { - s_logger.debug("Assuming the exception means domain_id is not there."); - s_logger.debug("No version table and no nics table, returning 2.1.7"); + logger.debug("Assuming the exception means domain_id is not there."); + logger.debug("No version table and no nics table, returning 2.1.7"); return "2.1.7"; } } else { @@ -98,7 +96,7 @@ public class VersionDaoImpl extends GenericDaoBase implements V ResultSet rs_static_nat = pstmt_static_nat.executeQuery();){ return "2.2.1"; } catch (final SQLException e) { - s_logger.debug("Assuming the exception means static_nat field doesn't exist in firewall_rules table, returning version 2.2.2"); + logger.debug("Assuming the exception means static_nat field doesn't exist in firewall_rules table, returning version 2.2.2"); return "2.2.2"; } } @@ -125,7 +123,7 @@ public class VersionDaoImpl extends GenericDaoBase implements V } // Use nics table information and is_static_nat field from firewall_rules table to determine version information - s_logger.debug("Version table exists, but it's empty; have to confirm that version is 2.2.2"); + logger.debug("Version table exists, but it's empty; have to confirm that version is 2.2.2"); try (PreparedStatement pstmt = conn.prepareStatement("SHOW TABLES LIKE 'nics'"); ResultSet rs = pstmt.executeQuery();){ if (!rs.next()) { @@ -136,7 +134,7 @@ public class VersionDaoImpl extends GenericDaoBase implements V throw new CloudRuntimeException("Unable to determine the current version, version table exists and empty, " + "nics table doesn't exist, is_static_nat field exists in firewall_rules table"); } catch (final SQLException e) { - s_logger.debug("Assuming the exception means static_nat field doesn't exist in firewall_rules table, returning version 2.2.2"); + logger.debug("Assuming the exception means static_nat field doesn't exist in firewall_rules table, returning version 2.2.2"); return "2.2.2"; } } diff --git a/engine/schema/src/main/java/com/cloud/usage/UsageVO.java b/engine/schema/src/main/java/com/cloud/usage/UsageVO.java index 054ec52e281..b1f6d295fdd 100644 --- a/engine/schema/src/main/java/com/cloud/usage/UsageVO.java +++ b/engine/schema/src/main/java/com/cloud/usage/UsageVO.java @@ -17,6 +17,7 @@ package com.cloud.usage; import java.util.Date; +import java.util.TimeZone; import javax.persistence.Column; import javax.persistence.Entity; @@ -27,9 +28,11 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; +import com.cloud.utils.DateUtil; import org.apache.cloudstack.api.InternalIdentity; import org.apache.cloudstack.usage.Usage; import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; +import org.apache.commons.lang3.StringUtils; @Entity @Table(name = "cloud_usage") @@ -411,6 +414,12 @@ public class UsageVO implements Usage, InternalIdentity { @Override public String toString() { - return ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "usageId", "usageType", "startDate", "endDate"); + return ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "usageId", "usageType"); + } + + public String toString(TimeZone timeZone) { + String startDateString = DateUtil.displayDateInTimezone(timeZone, getStartDate()); + String endDateString = DateUtil.displayDateInTimezone(timeZone, getEndDate()); + return String.format("%s,\"startDate\":\"%s\",\"endDate\":\"%s\"}", StringUtils.chop(this.toString()), startDateString, endDateString); } } diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/BucketStatisticsDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/BucketStatisticsDaoImpl.java index 2261389eab6..1df24079cee 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/BucketStatisticsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/BucketStatisticsDaoImpl.java @@ -20,14 +20,12 @@ import com.cloud.usage.BucketStatisticsVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import java.util.List; @Component public class BucketStatisticsDaoImpl extends GenericDaoBase implements BucketStatisticsDao { - private static final Logger s_logger = Logger.getLogger(BucketStatisticsDaoImpl.class); private final SearchBuilder AllFieldsSearch; private final SearchBuilder AccountSearch; diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsageBackupDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsageBackupDaoImpl.java index 712f81807c7..3403a8dfe5b 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsageBackupDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsageBackupDaoImpl.java @@ -25,7 +25,6 @@ import java.util.Date; import java.util.List; import java.util.TimeZone; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.exception.CloudException; @@ -37,7 +36,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class UsageBackupDaoImpl extends GenericDaoBase implements UsageBackupDao { - public static final Logger LOGGER = Logger.getLogger(UsageBackupDaoImpl.class); protected static final String UPDATE_DELETED = "UPDATE usage_backup SET removed = ? WHERE account_id = ? AND vm_id = ? and removed IS NULL"; protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, vm_id, backup_offering_id, size, protected_size, created, removed FROM usage_backup WHERE " + " account_id = ? AND ((removed IS NULL AND created <= ?) OR (created BETWEEN ? AND ?) OR (removed BETWEEN ? AND ?) " + @@ -55,7 +53,7 @@ public class UsageBackupDaoImpl extends GenericDaoBase impl update(vo.getId(), vo); } } catch (final Exception e) { - LOGGER.error("Error updating backup metrics: " + e.getMessage(), e); + logger.error("Error updating backup metrics: " + e.getMessage(), e); } } @@ -72,13 +70,13 @@ public class UsageBackupDaoImpl extends GenericDaoBase impl pstmt.executeUpdate(); } } catch (SQLException e) { - LOGGER.error("Error removing UsageBackupVO: " + e.getMessage(), e); + logger.error("Error removing UsageBackupVO: " + e.getMessage(), e); throw new CloudException("Remove backup usage exception: " + e.getMessage(), e); } txn.commit(); } catch (Exception e) { txn.rollback(); - LOGGER.error("Exception caught while removing UsageBackupVO: " + e.getMessage(), e); + logger.error("Exception caught while removing UsageBackupVO: " + e.getMessage(), e); } finally { txn.close(); } @@ -128,7 +126,7 @@ public class UsageBackupDaoImpl extends GenericDaoBase impl } } catch (Exception e) { txn.rollback(); - LOGGER.warn("Error getting VM backup usage records", e); + logger.warn("Error getting VM backup usage records", e); } finally { txn.close(); } diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsageDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsageDaoImpl.java index bc98652c95d..fb925a28513 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsageDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsageDaoImpl.java @@ -35,7 +35,6 @@ import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.exception.CloudRuntimeException; import org.apache.cloudstack.acl.RoleType; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import java.sql.PreparedStatement; @@ -50,7 +49,6 @@ import java.util.TimeZone; @Component public class UsageDaoImpl extends GenericDaoBase implements UsageDao { - public static final Logger s_logger = Logger.getLogger(UsageDaoImpl.class.getName()); private static final String DELETE_ALL = "DELETE FROM cloud_usage"; private static final String DELETE_ALL_BY_ACCOUNTID = "DELETE FROM cloud_usage WHERE account_id = ?"; private static final String DELETE_ALL_BY_INTERVAL = "DELETE FROM cloud_usage WHERE end_date < DATE_SUB(CURRENT_DATE(), INTERVAL ? DAY)"; @@ -109,7 +107,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error retrieving usage vm instances for account id: " + accountId, ex); + logger.error("error retrieving usage vm instances for account id: " + accountId, ex); } finally { txn.close(); } @@ -157,7 +155,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error saving account to cloud_usage db", ex); + logger.error("error saving account to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } } @@ -187,7 +185,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error updating account to cloud_usage db", ex); + logger.error("error updating account to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } } @@ -228,7 +226,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error saving user stats to cloud_usage db", ex); + logger.error("error saving user stats to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } } @@ -255,7 +253,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error updating user stats to cloud_usage db", ex); + logger.error("error updating user stats to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } } @@ -272,7 +270,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage return Long.valueOf(rs.getLong(1)); } } catch (Exception ex) { - s_logger.error("error getting last account id", ex); + logger.error("error getting last account id", ex); } return null; } @@ -289,7 +287,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage return Long.valueOf(rs.getLong(1)); } } catch (Exception ex) { - s_logger.error("error getting last user stats id", ex); + logger.error("error getting last user stats id", ex); } return null; } @@ -306,7 +304,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage return Long.valueOf(rs.getLong(1)); } } catch (Exception ex) { - s_logger.error("error getting last bucket stats id", ex); + logger.error("error getting last bucket stats id", ex); } return null; } @@ -330,7 +328,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error saving bucket stats to cloud_usage db", ex); + logger.error("error saving bucket stats to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } } @@ -352,7 +350,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error updating bucket stats to cloud_usage db", ex); + logger.error("error updating bucket stats to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } } @@ -371,7 +369,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage templateList.add(Long.valueOf(rs.getLong(1))); } } catch (Exception ex) { - s_logger.error("error listing public templates", ex); + logger.error("error listing public templates", ex); } return templateList; } @@ -388,7 +386,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage return Long.valueOf(rs.getLong(1)); } } catch (Exception ex) { - s_logger.error("error getting last vm disk stats id", ex); + logger.error("error getting last vm disk stats id", ex); } return null; } @@ -421,7 +419,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error updating vm disk stats to cloud_usage db", ex); + logger.error("error updating vm disk stats to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } @@ -467,7 +465,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error saving vm disk stats to cloud_usage db", ex); + logger.error("error saving vm disk stats to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } @@ -534,7 +532,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error saving usage records to cloud_usage db", ex); + logger.error("error saving usage records to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } } @@ -551,7 +549,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage pstmt.setLong(1, days); pstmt.executeUpdate(); } catch (Exception ex) { - s_logger.error("error removing old cloud_usage records for interval: " + days); + logger.error("error removing old cloud_usage records for interval: " + days); } } }); @@ -568,7 +566,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage @Override public Pair, Integer> listUsageRecordsPendingForQuotaAggregation(long accountId, long domainId) { - s_logger.debug(String.format("Retrieving pending usage records for accountId [%s] and domainId [%s].", accountId, domainId)); + logger.debug(String.format("Retrieving pending usage records for accountId [%s] and domainId [%s].", accountId, domainId)); return Transaction.execute(TransactionLegacy.USAGE_DB, (TransactionCallback, Integer>>) status -> { Filter usageFilter = new Filter(UsageVO.class, "startDate", true, null, null); @@ -594,7 +592,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage String startDateString = DateUtil.getOutputString(startDate); String endDateString = DateUtil.getOutputString(endDate); - s_logger.debug(String.format("Retrieving account resources between [%s] and [%s] for accountId [%s] and usageType [%s].", startDateString, endDateString, accountId, + logger.debug(String.format("Retrieving account resources between [%s] and [%s] for accountId [%s] and usageType [%s].", startDateString, endDateString, accountId, usageType)); TransactionLegacy txn = TransactionLegacy.currentTxn(); @@ -617,7 +615,7 @@ public class UsageDaoImpl extends GenericDaoBase implements Usage return accountResourcesOfTheLastDay; } catch (SQLException e) { - s_logger.error(String.format("Failed to retrieve account resources between [%s] and [%s] for accountId [%s] and usageType [%s] due to [%s]. Returning an empty list of" + logger.error(String.format("Failed to retrieve account resources between [%s] and [%s] for accountId [%s] and usageType [%s] due to [%s]. Returning an empty list of" + " resources.", startDateString, endDateString, accountId, usageType, e.getMessage()), e); return new ArrayList<>(); diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsageIPAddressDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsageIPAddressDaoImpl.java index 2dcb181c6c7..9c0b8f87ab0 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsageIPAddressDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsageIPAddressDaoImpl.java @@ -26,7 +26,6 @@ import java.util.TimeZone; import com.cloud.exception.CloudException; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.usage.UsageIPAddressVO; @@ -36,7 +35,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class UsageIPAddressDaoImpl extends GenericDaoBase implements UsageIPAddressDao { - public static final Logger s_logger = Logger.getLogger(UsageIPAddressDaoImpl.class.getName()); protected static final String UPDATE_RELEASED = "UPDATE usage_ip_address SET released = ? WHERE account_id = ? AND public_ip_address = ? and released IS NULL"; protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = @@ -79,7 +77,7 @@ public class UsageIPAddressDaoImpl extends GenericDaoBase implements UsageJobDao { - private static final Logger s_logger = Logger.getLogger(UsageJobDaoImpl.class.getName()); private static final String GET_LAST_JOB_SUCCESS_DATE_MILLIS = "SELECT end_millis FROM cloud_usage.usage_job WHERE end_millis > 0 and success = 1 ORDER BY end_millis DESC LIMIT 1"; @@ -52,7 +50,7 @@ public class UsageJobDaoImpl extends GenericDaoBase implements return rs.getLong(1); } } catch (Exception ex) { - s_logger.error("error getting last usage job success date", ex); + logger.error("error getting last usage job success date", ex); } finally { txn.close(); } @@ -78,7 +76,7 @@ public class UsageJobDaoImpl extends GenericDaoBase implements txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error updating job success date", ex); + logger.error("error updating job success date", ex); throw new CloudRuntimeException(ex.getMessage()); } finally { txn.close(); @@ -218,10 +216,10 @@ public class UsageJobDaoImpl extends GenericDaoBase implements try { List jobs = getLastOpenJobsOwned(hostname, pid); if (CollectionUtils.isNotEmpty(jobs)) { - s_logger.info(String.format("Found %s opens job, to remove", jobs.size())); + logger.info("Found {} opens job, to remove", jobs.size()); for (UsageJobVO job : jobs) { - s_logger.debug(String.format("Removing job - id: %d, pid: %d, job type: %d, scheduled: %d, heartbeat: %s", - job.getId(), job.getPid(), job.getJobType(), job.getScheduled(), job.getHeartbeat())); + logger.debug("Removing job - id: {}, pid: {}, job type: {}, scheduled: {}, heartbeat: {}", + job.getId(), job.getPid(), job.getJobType(), job.getScheduled(), job.getHeartbeat()); remove(job.getId()); } } diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsageLoadBalancerPolicyDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsageLoadBalancerPolicyDaoImpl.java index 7260caecd1a..ba5c70fbc32 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsageLoadBalancerPolicyDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsageLoadBalancerPolicyDaoImpl.java @@ -26,7 +26,6 @@ import java.util.TimeZone; import com.cloud.exception.CloudException; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.usage.UsageLoadBalancerPolicyVO; @@ -36,7 +35,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class UsageLoadBalancerPolicyDaoImpl extends GenericDaoBase implements UsageLoadBalancerPolicyDao { - public static final Logger s_logger = Logger.getLogger(UsageLoadBalancerPolicyDaoImpl.class.getName()); protected static final String REMOVE_BY_USERID_LBID = "DELETE FROM usage_load_balancer_policy WHERE account_id = ? AND lb_id = ?"; protected static final String UPDATE_DELETED = "UPDATE usage_load_balancer_policy SET deleted = ? WHERE account_id = ? AND lb_id = ? and deleted IS NULL"; @@ -64,7 +62,7 @@ public class UsageLoadBalancerPolicyDaoImpl extends GenericDaoBase implements UsageNetworkDao { - private static final Logger s_logger = Logger.getLogger(UsageNetworkDaoImpl.class.getName()); private static final String SELECT_LATEST_STATS = "SELECT u.account_id, u.zone_id, u.host_id, u.host_type, u.network_id, u.bytes_sent, u.bytes_received, u.agg_bytes_received, u.agg_bytes_sent, u.event_time_millis " + "FROM cloud_usage.usage_network u INNER JOIN (SELECT netusage.account_id as acct_id, netusage.zone_id as z_id, max(netusage.event_time_millis) as max_date " @@ -77,7 +75,7 @@ public class UsageNetworkDaoImpl extends GenericDaoBase im } return returnMap; } catch (Exception ex) { - s_logger.error("error getting recent usage network stats", ex); + logger.error("error getting recent usage network stats", ex); } finally { txn.close(); } @@ -97,7 +95,7 @@ public class UsageNetworkDaoImpl extends GenericDaoBase im txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error deleting old usage network stats", ex); + logger.error("error deleting old usage network stats", ex); } } @@ -126,7 +124,7 @@ public class UsageNetworkDaoImpl extends GenericDaoBase im txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error saving usage_network to cloud_usage db", ex); + logger.error("error saving usage_network to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } } diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsageNetworkOfferingDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsageNetworkOfferingDaoImpl.java index 23931f0a84e..b3bc06e8af4 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsageNetworkOfferingDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsageNetworkOfferingDaoImpl.java @@ -26,7 +26,6 @@ import java.util.TimeZone; import com.cloud.exception.CloudException; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.usage.UsageNetworkOfferingVO; @@ -36,7 +35,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class UsageNetworkOfferingDaoImpl extends GenericDaoBase implements UsageNetworkOfferingDao { - public static final Logger s_logger = Logger.getLogger(UsageNetworkOfferingDaoImpl.class.getName()); protected static final String UPDATE_DELETED = "UPDATE usage_network_offering SET deleted = ? WHERE account_id = ? AND vm_instance_id = ? AND network_offering_id = ? and deleted IS NULL"; @@ -74,7 +72,7 @@ public class UsageNetworkOfferingDaoImpl extends GenericDaoBase implements UsageNetworksDao { - private static final Logger LOGGER = Logger.getLogger(UsageNetworksDaoImpl.class); + private static final Logger LOGGER = LogManager.getLogger(UsageNetworksDaoImpl.class); protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, network_id, network_offering_id, zone_id, account_id, domain_id, state, created, removed FROM usage_networks WHERE " + " account_id = ? AND ((removed IS NULL AND created <= ?) OR (created BETWEEN ? AND ?) OR (removed BETWEEN ? AND ?) " + " OR ((created <= ?) AND (removed >= ?)))"; diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsagePortForwardingRuleDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsagePortForwardingRuleDaoImpl.java index 99216420a0d..e66b47f74fa 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsagePortForwardingRuleDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsagePortForwardingRuleDaoImpl.java @@ -26,7 +26,6 @@ import java.util.TimeZone; import com.cloud.exception.CloudException; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.usage.UsagePortForwardingRuleVO; @@ -36,7 +35,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class UsagePortForwardingRuleDaoImpl extends GenericDaoBase implements UsagePortForwardingRuleDao { - public static final Logger s_logger = Logger.getLogger(UsagePortForwardingRuleDaoImpl.class.getName()); protected static final String REMOVE_BY_USERID_PFID = "DELETE FROM usage_port_forwarding WHERE account_id = ? AND pf_id = ?"; protected static final String UPDATE_DELETED = "UPDATE usage_port_forwarding SET deleted = ? WHERE account_id = ? AND pf_id = ? and deleted IS NULL"; @@ -64,7 +62,7 @@ public class UsagePortForwardingRuleDaoImpl extends GenericDaoBase implements UsageSecurityGroupDao { - public static final Logger s_logger = Logger.getLogger(UsageSecurityGroupDaoImpl.class.getName()); protected static final String UPDATE_DELETED = "UPDATE usage_security_group SET deleted = ? WHERE account_id = ? AND vm_instance_id = ? AND security_group_id = ? and deleted IS NULL"; @@ -74,7 +72,7 @@ public class UsageSecurityGroupDaoImpl extends GenericDaoBase implements UsageStorageDao { - public static final Logger s_logger = Logger.getLogger(UsageStorageDaoImpl.class.getName()); protected static final String REMOVE_BY_USERID_STORAGEID = "DELETE FROM usage_storage WHERE account_id = ? AND entity_id = ? AND storage_type = ?"; protected static final String UPDATE_DELETED = "UPDATE usage_storage SET deleted = ? WHERE account_id = ? AND entity_id = ? AND storage_type = ? AND zone_id = ? and deleted IS NULL"; @@ -108,7 +106,7 @@ public class UsageStorageDaoImpl extends GenericDaoBase im txn.commit(); } catch (Exception e) { txn.rollback(); - s_logger.error("Error removing usageStorageVO", e); + logger.error("Error removing usageStorageVO", e); } finally { txn.close(); } @@ -137,7 +135,7 @@ public class UsageStorageDaoImpl extends GenericDaoBase im txn.commit(); } catch (Exception e) { txn.rollback(); - s_logger.error("Error updating UsageStorageVO:"+e.getMessage(), e); + logger.error("Error updating UsageStorageVO:"+e.getMessage(), e); } finally { txn.close(); } @@ -211,7 +209,7 @@ public class UsageStorageDaoImpl extends GenericDaoBase im } }catch (Exception e) { txn.rollback(); - s_logger.error("getUsageRecords:Exception:"+e.getMessage(), e); + logger.error("getUsageRecords:Exception:"+e.getMessage(), e); } finally { txn.close(); } diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java index d330267d0b4..2fd453013bd 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.TimeZone; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.usage.UsageVMInstanceVO; @@ -34,7 +33,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class UsageVMInstanceDaoImpl extends GenericDaoBase implements UsageVMInstanceDao { - public static final Logger s_logger = Logger.getLogger(UsageVMInstanceDaoImpl.class.getName()); protected static final String UPDATE_USAGE_INSTANCE_SQL = "UPDATE usage_vm_instance SET end_date = ? " + "WHERE account_id = ? and vm_instance_id = ? and usage_type = ? and end_date IS NULL"; @@ -62,7 +60,7 @@ public class UsageVMInstanceDaoImpl extends GenericDaoBase implements UsageVMSnapshotDao { - public static final Logger s_logger = Logger.getLogger(UsageVMSnapshotDaoImpl.class.getName()); protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT volume_id, zone_id, account_id, domain_id, vm_id, disk_offering_id, size, created, processed, vm_snapshot_id " + " FROM usage_vmsnapshot" + " WHERE account_id = ? " + " AND ( (created BETWEEN ? AND ?) OR " + " (created < ? AND processed is NULL) ) ORDER BY created asc"; @@ -61,7 +59,7 @@ public class UsageVMSnapshotDaoImpl extends GenericDaoBase implements UsageVMSnapshotOnPrimaryDao { - public static final Logger s_logger = Logger.getLogger(UsageVMSnapshotOnPrimaryDaoImpl.class.getName()); protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT volume_id, zone_id, account_id, domain_id, vm_id, name, type, physicalsize, virtualsize, created, deleted, vm_snapshot_id " + " FROM usage_snapshot_on_primary" + " WHERE account_id = ? " + " AND ( (created < ? AND deleted is NULL)" + " OR ( deleted BETWEEN ? AND ?)) ORDER BY created asc"; @@ -58,7 +56,7 @@ public class UsageVMSnapshotOnPrimaryDaoImpl extends GenericDaoBase implements UsageVPNUserDao { - public static final Logger s_logger = Logger.getLogger(UsageVPNUserDaoImpl.class.getName()); protected static final String UPDATE_DELETED = "UPDATE usage_vpn_user SET deleted = ? WHERE account_id = ? AND user_id = ? and deleted IS NULL"; protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT zone_id, account_id, domain_id, user_id, user_name, created, deleted " + "FROM usage_vpn_user " @@ -69,7 +67,7 @@ public class UsageVPNUserDaoImpl extends GenericDaoBase im txn.commit(); } catch (Exception e) { txn.rollback(); - s_logger.error("Error updating UsageVPNUserVO:"+e.getMessage(), e); + logger.error("Error updating UsageVPNUserVO:"+e.getMessage(), e); } finally { txn.close(); } @@ -139,7 +137,7 @@ public class UsageVPNUserDaoImpl extends GenericDaoBase im } } catch (Exception e) { txn.rollback(); - s_logger.warn("Error getting usage records", e); + logger.warn("Error getting usage records", e); } finally { txn.close(); } diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsageVmDiskDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsageVmDiskDaoImpl.java index 2b934770b7d..bc1cb06cfec 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsageVmDiskDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsageVmDiskDaoImpl.java @@ -23,7 +23,6 @@ import java.util.List; import java.util.Map; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.usage.UsageVmDiskVO; @@ -33,7 +32,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class UsageVmDiskDaoImpl extends GenericDaoBase implements UsageVmDiskDao { - private static final Logger s_logger = Logger.getLogger(UsageVmDiskDaoImpl.class.getName()); private static final String SELECT_LATEST_STATS = "SELECT uvd.account_id, uvd.zone_id, uvd.vm_id, uvd.volume_id, uvd.io_read, uvd.io_write, uvd.agg_io_read, uvd.agg_io_write, " + "uvd.bytes_read, uvd.bytes_write, uvd.agg_bytes_read, uvd.agg_bytes_write, uvd.event_time_millis " @@ -81,7 +79,7 @@ public class UsageVmDiskDaoImpl extends GenericDaoBase impl } return returnMap; } catch (Exception ex) { - s_logger.error("error getting recent usage disk stats", ex); + logger.error("error getting recent usage disk stats", ex); } finally { txn.close(); } @@ -101,7 +99,7 @@ public class UsageVmDiskDaoImpl extends GenericDaoBase impl txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error deleting old usage disk stats", ex); + logger.error("error deleting old usage disk stats", ex); } } @@ -133,7 +131,7 @@ public class UsageVmDiskDaoImpl extends GenericDaoBase impl txn.commit(); } catch (Exception ex) { txn.rollback(); - s_logger.error("error saving usage_vm_disk to cloud_usage db", ex); + logger.error("error saving usage_vm_disk to cloud_usage db", ex); throw new CloudRuntimeException(ex.getMessage()); } } diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsageVolumeDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsageVolumeDaoImpl.java index 0c35c118006..4662a6f26ce 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsageVolumeDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsageVolumeDaoImpl.java @@ -26,7 +26,6 @@ import java.util.TimeZone; import com.cloud.exception.CloudException; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.usage.UsageVolumeVO; @@ -36,7 +35,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class UsageVolumeDaoImpl extends GenericDaoBase implements UsageVolumeDao { - public static final Logger s_logger = Logger.getLogger(UsageVolumeDaoImpl.class.getName()); protected static final String REMOVE_BY_USERID_VOLID = "DELETE FROM usage_volume WHERE account_id = ? AND volume_id = ?"; protected static final String UPDATE_DELETED = "UPDATE usage_volume SET deleted = ? WHERE account_id = ? AND volume_id = ? and deleted IS NULL"; @@ -69,7 +67,7 @@ public class UsageVolumeDaoImpl extends GenericDaoBase impl txn.commit(); } catch (Exception e) { txn.rollback(); - s_logger.warn("Error removing usageVolumeVO:"+e.getMessage(), e); + logger.warn("Error removing usageVolumeVO:"+e.getMessage(), e); } finally { txn.close(); } @@ -91,7 +89,7 @@ public class UsageVolumeDaoImpl extends GenericDaoBase impl txn.commit(); } catch (Exception e) { txn.rollback(); - s_logger.warn("Error updating UsageVolumeVO", e); + logger.warn("Error updating UsageVolumeVO", e); } finally { txn.close(); } @@ -169,7 +167,7 @@ public class UsageVolumeDaoImpl extends GenericDaoBase impl } } catch (Exception e) { txn.rollback(); - s_logger.warn("Error getting usage records", e); + logger.warn("Error getting usage records", e); } finally { txn.close(); } diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsageVpcDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsageVpcDaoImpl.java index e7ebf706cf3..b5d8e46ef09 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsageVpcDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsageVpcDaoImpl.java @@ -22,7 +22,6 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.TransactionLegacy; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -35,7 +34,6 @@ import java.util.TimeZone; @Component public class UsageVpcDaoImpl extends GenericDaoBase implements UsageVpcDao { - private static final Logger LOGGER = Logger.getLogger(UsageVpcDaoImpl.class); protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, vpc_id, zone_id, account_id, domain_id, state, created, removed FROM usage_vpc WHERE " + " account_id = ? AND ((removed IS NULL AND created <= ?) OR (created BETWEEN ? AND ?) OR (removed BETWEEN ? AND ?) " + " OR ((created <= ?) AND (removed >= ?)))"; @@ -62,7 +60,7 @@ public class UsageVpcDaoImpl extends GenericDaoBase implements update(vo.getId(), vo); } } catch (final Exception e) { - LOGGER.error(String.format("Error updating usage of VPC due to [%s].", e.getMessage()), e); + logger.error(String.format("Error updating usage of VPC due to [%s].", e.getMessage()), e); txn.rollback(); } finally { txn.close(); @@ -83,7 +81,7 @@ public class UsageVpcDaoImpl extends GenericDaoBase implements } } catch (final Exception e) { txn.rollback(); - LOGGER.error(String.format("Error updating usage of VPC due to [%s].", e.getMessage()), e); + logger.error(String.format("Error updating usage of VPC due to [%s].", e.getMessage()), e); } finally { txn.close(); } @@ -130,7 +128,7 @@ public class UsageVpcDaoImpl extends GenericDaoBase implements } } catch (Exception e) { txn.rollback(); - LOGGER.warn("Error getting VPC usage records", e); + logger.warn("Error getting VPC usage records", e); } finally { txn.close(); } diff --git a/engine/schema/src/main/java/com/cloud/user/AccountDetailsDaoImpl.java b/engine/schema/src/main/java/com/cloud/user/AccountDetailsDaoImpl.java index 8cea616b97d..535b5eae390 100644 --- a/engine/schema/src/main/java/com/cloud/user/AccountDetailsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/user/AccountDetailsDaoImpl.java @@ -26,19 +26,18 @@ import javax.inject.Inject; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.ConfigKey.Scope; import org.apache.cloudstack.framework.config.ScopedConfigStorage; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import com.cloud.domain.DomainDetailVO; import com.cloud.domain.DomainVO; -import com.cloud.domain.dao.DomainDetailsDao; import com.cloud.domain.dao.DomainDao; +import com.cloud.domain.dao.DomainDetailsDao; import com.cloud.user.dao.AccountDao; - import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.TransactionLegacy; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; public class AccountDetailsDaoImpl extends ResourceDetailsDaoBase implements AccountDetailsDao, ScopedConfigStorage { @@ -64,7 +63,7 @@ public class AccountDetailsDaoImpl extends ResourceDetailsDaoBase sc = QueryBuilder.create(AccountDetailVO.class); sc.and(sc.entity().getResourceId(), Op.EQ, accountId); List results = sc.list(); - Map details = new HashMap(results.size()); + Map details = new HashMap<>(results.size()); for (AccountDetailVO r : results) { details.put(r.getName(), r.getValue()); } @@ -121,9 +120,9 @@ public class AccountDetailsDaoImpl extends ResourceDetailsDaoBase key) { + public String getConfigValue(long id, String key) { // check if account level setting is configured - AccountDetailVO vo = findDetail(id, key.key()); + AccountDetailVO vo = findDetail(id, key); String value = vo == null ? null : getActualValue(vo); if (value != null) { return value; @@ -143,7 +142,7 @@ public class AccountDetailsDaoImpl extends ResourceDetailsDaoBase getDetails() { + if (details == null) { + details = new HashMap<>(); + } return details; } @@ -373,6 +376,7 @@ public class UserAccountVO implements UserAccount, InternalIdentity { @Override public String toString() { - return String.format("User %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "name", "uuid")); + return String.format("UserAccount %s.", ReflectionToStringBuilderUtils.reflectOnlySelectedFields + (this, "id", "uuid", "username", "accountName")); } } diff --git a/engine/schema/src/main/java/com/cloud/user/UserVO.java b/engine/schema/src/main/java/com/cloud/user/UserVO.java index 69970bf2d2c..6e355e102e6 100644 --- a/engine/schema/src/main/java/com/cloud/user/UserVO.java +++ b/engine/schema/src/main/java/com/cloud/user/UserVO.java @@ -115,6 +115,9 @@ public class UserVO implements User, Identity, InternalIdentity { @Column(name = "key_for_2fa") private String keyFor2fa; + @Column(name = "api_key_access") + private Boolean apiKeyAccess; + public UserVO() { this.uuid = UUID.randomUUID().toString(); } @@ -293,7 +296,7 @@ public class UserVO implements User, Identity, InternalIdentity { @Override public String toString() { - return String.format("User %s.", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "username", "uuid")); + return String.format("User %s.", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "uuid", "username")); } @Override @@ -350,4 +353,13 @@ public class UserVO implements User, Identity, InternalIdentity { this.user2faProvider = user2faProvider; } + @Override + public void setApiKeyAccess(Boolean apiKeyAccess) { + this.apiKeyAccess = apiKeyAccess; + } + + @Override + public Boolean getApiKeyAccess() { + return apiKeyAccess; + } } diff --git a/engine/schema/src/main/java/com/cloud/user/dao/AccountDaoImpl.java b/engine/schema/src/main/java/com/cloud/user/dao/AccountDaoImpl.java index be5ac2e8204..f5f95d5da1f 100644 --- a/engine/schema/src/main/java/com/cloud/user/dao/AccountDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/user/dao/AccountDaoImpl.java @@ -22,7 +22,6 @@ import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.user.Account; @@ -43,9 +42,8 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class AccountDaoImpl extends GenericDaoBase implements AccountDao { - private static final Logger s_logger = Logger.getLogger(AccountDaoImpl.class); - private static final String FIND_USER_ACCOUNT_BY_API_KEY = "SELECT u.id, u.username, u.account_id, u.secret_key, u.state, " - + "a.id, a.account_name, a.type, a.role_id, a.domain_id, a.state " + "FROM `cloud`.`user` u, `cloud`.`account` a " + private static final String FIND_USER_ACCOUNT_BY_API_KEY = "SELECT u.id, u.username, u.account_id, u.secret_key, u.state, u.api_key_access, " + + "a.id, a.account_name, a.type, a.role_id, a.domain_id, a.state, a.api_key_access " + "FROM `cloud`.`user` u, `cloud`.`account` a " + "WHERE u.account_id = a.id AND u.api_key = ? and u.removed IS NULL"; protected final SearchBuilder AllFieldsSearch; @@ -151,18 +149,30 @@ public class AccountDaoImpl extends GenericDaoBase implements A u.setAccountId(rs.getLong(3)); u.setSecretKey(DBEncryptionUtil.decrypt(rs.getString(4))); u.setState(State.getValueOf(rs.getString(5))); + boolean apiKeyAccess = rs.getBoolean(6); + if (rs.wasNull()) { + u.setApiKeyAccess(null); + } else { + u.setApiKeyAccess(apiKeyAccess); + } - AccountVO a = new AccountVO(rs.getLong(6)); - a.setAccountName(rs.getString(7)); - a.setType(Account.Type.getFromValue(rs.getInt(8))); - a.setRoleId(rs.getLong(9)); - a.setDomainId(rs.getLong(10)); - a.setState(State.getValueOf(rs.getString(11))); + AccountVO a = new AccountVO(rs.getLong(7)); + a.setAccountName(rs.getString(8)); + a.setType(Account.Type.getFromValue(rs.getInt(9))); + a.setRoleId(rs.getLong(10)); + a.setDomainId(rs.getLong(11)); + a.setState(State.getValueOf(rs.getString(12))); + apiKeyAccess = rs.getBoolean(13); + if (rs.wasNull()) { + a.setApiKeyAccess(null); + } else { + a.setApiKeyAccess(apiKeyAccess); + } userAcctPair = new Pair(u, a); } } catch (Exception e) { - s_logger.warn("Exception finding user/acct by api key: " + apiKey, e); + logger.warn("Exception finding user/acct by api key: " + apiKey, e); } return userAcctPair; } @@ -311,7 +321,7 @@ public class AccountDaoImpl extends GenericDaoBase implements A if (!account.getNeedsCleanup()) { account.setNeedsCleanup(true); if (!update(accountId, account)) { - s_logger.warn("Failed to mark account id=" + accountId + " for cleanup"); + logger.warn("Failed to mark account {} for cleanup", account); } } } @@ -331,7 +341,7 @@ public class AccountDaoImpl extends GenericDaoBase implements A domain_id = account_vo.getDomainId(); } catch (Exception e) { - s_logger.warn("getDomainIdForGivenAccountId: Exception :" + e.getMessage()); + logger.warn("getDomainIdForGivenAccountId: Exception :" + e.getMessage()); } finally { return domain_id; diff --git a/engine/schema/src/main/java/com/cloud/user/dao/UserStatisticsDaoImpl.java b/engine/schema/src/main/java/com/cloud/user/dao/UserStatisticsDaoImpl.java index acadc2f0908..6f10c5d2a1b 100644 --- a/engine/schema/src/main/java/com/cloud/user/dao/UserStatisticsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/user/dao/UserStatisticsDaoImpl.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.TimeZone; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.user.UserStatisticsVO; @@ -36,7 +35,6 @@ import com.cloud.utils.db.TransactionLegacy; @Component public class UserStatisticsDaoImpl extends GenericDaoBase implements UserStatisticsDao { - private static final Logger s_logger = Logger.getLogger(UserStatisticsDaoImpl.class); private static final String ACTIVE_AND_RECENTLY_DELETED_SEARCH = "SELECT us.id, us.data_center_id, us.account_id, us.public_ip_address, us.device_id, us.device_type, us.network_id, us.agg_bytes_received, us.agg_bytes_sent " + "FROM user_statistics us, account a " + "WHERE us.account_id = a.id AND (a.removed IS NULL OR a.removed >= ?) " + "ORDER BY us.id"; @@ -109,7 +107,7 @@ public class UserStatisticsDaoImpl extends GenericDaoBase implements VmDiskStatisticsDao { - private static final Logger s_logger = Logger.getLogger(VmDiskStatisticsDaoImpl.class); private static final String ACTIVE_AND_RECENTLY_DELETED_SEARCH = "SELECT bcf.id, bcf.data_center_id, bcf.account_id, bcf.vm_id, bcf.volume_id, bcf.agg_io_read, bcf.agg_io_write, bcf.agg_bytes_read, bcf.agg_bytes_write " + "FROM vm_disk_statistics bcf, account a " + "WHERE bcf.account_id = a.id AND (a.removed IS NULL OR a.removed >= ?) " + "ORDER BY bcf.id"; @@ -104,7 +102,7 @@ public class VmDiskStatisticsDaoImpl extends GenericDaoBase { + @Override + public String convertToDatabaseColumn(StoragePoolType attribute) { + return attribute != null ? attribute.name() : null; + } + + @Override + public StoragePoolType convertToEntityAttribute(String dbData) { + return dbData != null ? StoragePoolType.valueOf(dbData) : null; + } +} diff --git a/engine/schema/src/main/java/com/cloud/vm/InstanceGroupVO.java b/engine/schema/src/main/java/com/cloud/vm/InstanceGroupVO.java index 4437af29bc1..d5bd8c5aaae 100644 --- a/engine/schema/src/main/java/com/cloud/vm/InstanceGroupVO.java +++ b/engine/schema/src/main/java/com/cloud/vm/InstanceGroupVO.java @@ -32,6 +32,7 @@ import javax.persistence.Table; import com.cloud.user.Account; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "instance_group") @@ -74,6 +75,12 @@ public class InstanceGroupVO implements InstanceGroup { super(); } + @Override + public String toString() { + return String.format("InstanceGroup %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "uuid", "name")); + } + + @Override public long getId() { return id; diff --git a/engine/schema/src/main/java/com/cloud/vm/ItWorkDao.java b/engine/schema/src/main/java/com/cloud/vm/ItWorkDao.java index 2d4a5e138fe..ab07d6989fa 100644 --- a/engine/schema/src/main/java/com/cloud/vm/ItWorkDao.java +++ b/engine/schema/src/main/java/com/cloud/vm/ItWorkDao.java @@ -41,5 +41,6 @@ public interface ItWorkDao extends GenericDao { boolean updateStep(ItWorkVO work, Step step); List listWorkInProgressFor(long nodeId); + int expungeByVmList(List vmIds, Long batchSize); } diff --git a/engine/schema/src/main/java/com/cloud/vm/ItWorkDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/ItWorkDaoImpl.java index ff727904dcb..0cc0a084443 100644 --- a/engine/schema/src/main/java/com/cloud/vm/ItWorkDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/ItWorkDaoImpl.java @@ -18,7 +18,7 @@ package com.cloud.vm; import java.util.List; - +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; import com.cloud.utils.db.GenericDaoBase; @@ -103,4 +103,16 @@ public class ItWorkDaoImpl extends GenericDaoBase implements I return search(sc, null); } + + @Override + public int expungeByVmList(List vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getInstanceId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + return batchExpunge(sc, batchSize); + } } diff --git a/engine/schema/src/main/java/com/cloud/vm/NicVO.java b/engine/schema/src/main/java/com/cloud/vm/NicVO.java index 936efd112b7..6c569e22dd9 100644 --- a/engine/schema/src/main/java/com/cloud/vm/NicVO.java +++ b/engine/schema/src/main/java/com/cloud/vm/NicVO.java @@ -330,7 +330,10 @@ public class NicVO implements Nic { @Override public String toString() { - return String.format("Nic %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "instanceId", "deviceId", "broadcastUri", "reservationId", "iPv4Address")); + return String.format("Nic %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "instanceId", + "deviceId", "broadcastUri", "reservationId", "iPv4Address")); } @Override diff --git a/engine/schema/src/main/java/com/cloud/vm/VMInstanceVO.java b/engine/schema/src/main/java/com/cloud/vm/VMInstanceVO.java index 320c9a30fb4..9d5e1b0ff50 100644 --- a/engine/schema/src/main/java/com/cloud/vm/VMInstanceVO.java +++ b/engine/schema/src/main/java/com/cloud/vm/VMInstanceVO.java @@ -26,6 +26,7 @@ import java.util.Map; import java.util.UUID; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.Entity; @@ -41,9 +42,11 @@ import javax.persistence.TemporalType; import javax.persistence.Transient; import org.apache.cloudstack.backup.Backup; +import org.apache.cloudstack.util.HypervisorTypeConverter; import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.db.Encrypt; @@ -59,7 +62,7 @@ import com.google.gson.Gson; @Inheritance(strategy = InheritanceType.JOINED) @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING, length = 32) public class VMInstanceVO implements VirtualMachine, FiniteStateObject { - private static final Logger s_logger = Logger.getLogger(VMInstanceVO.class); + protected transient Logger logger = LogManager.getLogger(getClass()); @Id @TableGenerator(name = "vm_instance_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "vm_instance_seq", allocationSize = 1) @Column(name = "id", updatable = false, nullable = false) @@ -158,16 +161,14 @@ public class VMInstanceVO implements VirtualMachine, FiniteStateObject details; @@ -225,7 +226,7 @@ public class VMInstanceVO implements VirtualMachine, FiniteStateObject getEntityType() { return VirtualMachine.class; diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleProxyDao.java b/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleProxyDao.java index cb19748fda4..af32163b4c7 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleProxyDao.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleProxyDao.java @@ -45,7 +45,7 @@ public interface ConsoleProxyDao extends GenericDao { public List getDatacenterSessionLoadMatrix(); - public List> getDatacenterStoragePoolHostInfo(long dcId, boolean countAllPoolTypes); + public boolean hasDatacenterStoragePoolHostInfo(long dcId, boolean sharedOnly); public List> getProxyLoadMatrix(); diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleProxyDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleProxyDaoImpl.java index 5b5c3505cb3..bc79194a10f 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleProxyDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleProxyDaoImpl.java @@ -23,8 +23,6 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; - -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.info.ConsoleProxyLoadInfo; @@ -40,7 +38,6 @@ import com.cloud.vm.VirtualMachine.State; @Component public class ConsoleProxyDaoImpl extends GenericDaoBase implements ConsoleProxyDao { - private static final Logger s_logger = Logger.getLogger(ConsoleProxyDaoImpl.class); // // query SQL for returning console proxy assignment info as following @@ -78,11 +75,11 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase im private static final String GET_PROXY_ACTIVE_LOAD = "SELECT active_session AS count" + " FROM console_proxy" + " WHERE id=?"; - private static final String STORAGE_POOL_HOST_INFO = "SELECT p.data_center_id, count(ph.host_id) " + " FROM storage_pool p, storage_pool_host_ref ph " - + " WHERE p.id = ph.pool_id AND p.data_center_id = ? " + " GROUP by p.data_center_id"; + protected static final String STORAGE_POOL_HOST_INFO = "SELECT (SELECT id FROM storage_pool_host_ref ph WHERE " + + "ph.pool_id=p.id limit 1) AS sphr FROM storage_pool p WHERE p.data_center_id = ?"; - private static final String SHARED_STORAGE_POOL_HOST_INFO = "SELECT p.data_center_id, count(ph.host_id) " + " FROM storage_pool p, storage_pool_host_ref ph " - + " WHERE p.pool_type <> 'LVM' AND p.id = ph.pool_id AND p.data_center_id = ? " + " GROUP by p.data_center_id"; + protected static final String SHARED_STORAGE_POOL_HOST_INFO = "SELECT (SELECT id FROM storage_pool_host_ref ph " + + "WHERE ph.pool_id=p.id limit 1) AS sphr FROM storage_pool p WHERE p.data_center_id = ? AND p.pool_type NOT IN ('LVM', 'Filesystem')"; protected SearchBuilder DataCenterStatusSearch; protected SearchBuilder StateSearch; @@ -215,34 +212,29 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase im l.add(new Pair(rs.getLong(1), rs.getInt(2))); } } catch (SQLException e) { - s_logger.debug("Caught SQLException: ", e); + logger.debug("Caught SQLException: ", e); } return l; } @Override - public List> getDatacenterStoragePoolHostInfo(long dcId, boolean countAllPoolTypes) { - ArrayList> l = new ArrayList>(); - + public boolean hasDatacenterStoragePoolHostInfo(long dcId, boolean sharedOnly) { + Long poolCount = 0L; + String sql = sharedOnly ? SHARED_STORAGE_POOL_HOST_INFO : STORAGE_POOL_HOST_INFO; TransactionLegacy txn = TransactionLegacy.currentTxn(); - ; - PreparedStatement pstmt = null; - try { - if (countAllPoolTypes) { - pstmt = txn.prepareAutoCloseStatement(STORAGE_POOL_HOST_INFO); - } else { - pstmt = txn.prepareAutoCloseStatement(SHARED_STORAGE_POOL_HOST_INFO); - } + try (PreparedStatement pstmt = txn.prepareAutoCloseStatement(sql)) { pstmt.setLong(1, dcId); - ResultSet rs = pstmt.executeQuery(); while (rs.next()) { - l.add(new Pair(rs.getLong(1), rs.getInt(2))); + poolCount = rs.getLong(1); + if (poolCount > 0) { + return true; + } } } catch (SQLException e) { - s_logger.debug("Caught SQLException: ", e); + logger.debug("Caught SQLException: ", e); } - return l; + return false; } @Override @@ -259,7 +251,7 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase im return rs.getInt(1); } } catch (SQLException e) { - s_logger.debug("Caught SQLException: ", e); + logger.debug("Caught SQLException: ", e); } return 0; } @@ -277,7 +269,7 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase im return rs.getInt(1); } } catch (SQLException e) { - s_logger.debug("Caught SQLException: ", e); + logger.debug("Caught SQLException: ", e); } return 0; } @@ -299,7 +291,7 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase im l.add(info); } } catch (SQLException e) { - s_logger.debug("Exception: ", e); + logger.debug("Exception: ", e); } return l; } @@ -321,7 +313,7 @@ public class ConsoleProxyDaoImpl extends GenericDaoBase im l.add(rs.getLong(1)); } } catch (SQLException e) { - s_logger.debug("Caught SQLException: ", e); + logger.debug("Caught SQLException: ", e); } return l; } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleSessionDao.java b/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleSessionDao.java index 71b1aed1938..79158dd13b2 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleSessionDao.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleSessionDao.java @@ -23,6 +23,7 @@ import com.cloud.vm.ConsoleSessionVO; import com.cloud.utils.db.GenericDao; import java.util.Date; +import java.util.List; public interface ConsoleSessionDao extends GenericDao { @@ -33,4 +34,6 @@ public interface ConsoleSessionDao extends GenericDao { int expungeSessionsOlderThanDate(Date date); void acquireSession(String sessionUuid); + + int expungeByVmList(List vmIds, Long batchSize); } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleSessionDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleSessionDaoImpl.java index 8e7e229622e..48709674451 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleSessionDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/ConsoleSessionDaoImpl.java @@ -20,6 +20,9 @@ package com.cloud.vm.dao; import java.util.Date; +import java.util.List; + +import org.apache.commons.collections.CollectionUtils; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; @@ -65,5 +68,15 @@ public class ConsoleSessionDaoImpl extends GenericDaoBase vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getInstanceId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + return batchExpunge(sc, batchSize); + } } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/NicDao.java b/engine/schema/src/main/java/com/cloud/vm/dao/NicDao.java index 68f57329d77..d34b03c4cb0 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/NicDao.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/NicDao.java @@ -44,6 +44,8 @@ public interface NicDao extends GenericDao { NicVO findByNetworkIdAndType(long networkId, VirtualMachine.Type vmType); + NicVO findByNetworkIdAndTypeIncludingRemoved(long networkId, VirtualMachine.Type vmType); + NicVO findByIp4AddressAndNetworkId(String ip4Address, long networkId); NicVO findByNetworkIdAndMacAddress(long networkId, String mac); @@ -98,4 +100,5 @@ public interface NicDao extends GenericDao { NicVO findByIpAddressAndVmType(String ip, VirtualMachine.Type vmType); List listByNetworkIdAndType(long networkId, VirtualMachine.Type vmType); + List searchRemovedByVms(List vmIds, Long batchSize); } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/NicDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/NicDaoImpl.java index 59d2417b073..7d1af1982ae 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/NicDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/NicDaoImpl.java @@ -17,11 +17,13 @@ package com.cloud.vm.dao; import java.net.URI; +import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; import com.cloud.utils.db.Filter; @@ -176,12 +178,21 @@ public class NicDaoImpl extends GenericDaoBase implements NicDao { return findOneIncludingRemovedBy(sc); } - @Override - public NicVO findByNetworkIdAndType(long networkId, VirtualMachine.Type vmType) { + private NicVO findByNetworkIdAndTypeInternal(long networkId, VirtualMachine.Type vmType, boolean includingRemoved) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("network", networkId); sc.setParameters("vmType", vmType); - return findOneBy(sc); + return includingRemoved ? findOneIncludingRemovedBy(sc) : findOneBy(sc); + } + + @Override + public NicVO findByNetworkIdAndType(long networkId, VirtualMachine.Type vmType) { + return findByNetworkIdAndTypeInternal(networkId, vmType, false); + } + + @Override + public NicVO findByNetworkIdAndTypeIncludingRemoved(long networkId, VirtualMachine.Type vmType) { + return findByNetworkIdAndTypeInternal(networkId, vmType, true); } @Override @@ -419,4 +430,18 @@ public class NicDaoImpl extends GenericDaoBase implements NicDao { sc.setParameters("vmType", vmType); return listBy(sc); } + + @Override + public List searchRemovedByVms(List vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return new ArrayList<>(); + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getInstanceId(), SearchCriteria.Op.IN); + sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.NNULL); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + Filter filter = new Filter(NicVO.class, "id", true, 0L, batchSize); + return searchIncludingRemoved(sc, filter, null, false); + } } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/NicExtraDhcpOptionDao.java b/engine/schema/src/main/java/com/cloud/vm/dao/NicExtraDhcpOptionDao.java index 69d9c00e1e0..7bae64a6acb 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/NicExtraDhcpOptionDao.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/NicExtraDhcpOptionDao.java @@ -29,4 +29,5 @@ public interface NicExtraDhcpOptionDao extends GenericDao extraDhcpOptions); + int expungeByNicList(List nicIds, Long batchSize); } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/NicExtraDhcpOptionDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/NicExtraDhcpOptionDaoImpl.java index 3056c73938e..0f3679d66a3 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/NicExtraDhcpOptionDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/NicExtraDhcpOptionDaoImpl.java @@ -16,13 +16,13 @@ // under the License. package com.cloud.vm.dao; -import org.springframework.stereotype.Component; - import java.util.List; +import org.apache.commons.collections.CollectionUtils; +import org.springframework.stereotype.Component; + import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; - import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.vm.NicExtraDhcpOption; @@ -74,4 +74,15 @@ public class NicExtraDhcpOptionDaoImpl extends GenericDaoBase nicIds, Long batchSize) { + if (CollectionUtils.isEmpty(nicIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("nicIds", sb.entity().getNicId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("nicIds", nicIds.toArray()); + return batchExpunge(sc, batchSize); + } } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/NicIpAliasDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/NicIpAliasDaoImpl.java index 887b3d73087..44866c0a358 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/NicIpAliasDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/NicIpAliasDaoImpl.java @@ -170,8 +170,7 @@ public class NicIpAliasDaoImpl extends GenericDaoBase implem public Integer countAliasIps(long id) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("instanceId", id); - List list = listBy(sc); - return list.size(); + return getCount(sc); } @Override diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpDao.java b/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpDao.java index cbb52e57282..ff7089ca427 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpDao.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpDao.java @@ -55,4 +55,5 @@ public interface NicSecondaryIpDao extends GenericDao { List listSecondaryIpUsingKeyword(long nicId, String keyword); int moveSecondaryIps(long fromNicId, long toNicId); + int expungeByVmList(List vmIds, Long batchSize); } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpDaoImpl.java index a56d35d5a63..563b3279520 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpDaoImpl.java @@ -19,6 +19,7 @@ package com.cloud.vm.dao; import java.util.ArrayList; import java.util.List; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; @@ -192,4 +193,16 @@ public class NicSecondaryIpDaoImpl extends GenericDaoBase vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getVmId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + return batchExpunge(sc, batchSize); + } } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpVO.java b/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpVO.java index 093434052bc..4c8208b4be8 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpVO.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/NicSecondaryIpVO.java @@ -28,6 +28,7 @@ import javax.persistence.Table; import com.cloud.utils.db.GenericDao; import com.cloud.vm.NicSecondaryIp; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "nic_secondary_ips") @@ -87,6 +88,14 @@ public class NicSecondaryIpVO implements NicSecondaryIp { @Column(name = "vmId") long vmId; + @Override + public String toString() { + return String.format("NicSecondaryIp %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "vmId", + "nicId", "ip4Address", "ip6Address", "networkId")); + } + @Override public long getId() { return id; diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java index 2b3c0289b23..b2b719cd12e 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/SecondaryStorageVmDaoImpl.java @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.Attribute; @@ -38,7 +37,6 @@ import com.cloud.vm.VirtualMachine.State; @Component public class SecondaryStorageVmDaoImpl extends GenericDaoBase implements SecondaryStorageVmDao { - private static final Logger s_logger = Logger.getLogger(SecondaryStorageVmDaoImpl.class); protected SearchBuilder DataCenterStatusSearch; protected SearchBuilder StateSearch; @@ -193,7 +191,7 @@ public class SecondaryStorageVmDaoImpl extends GenericDaoBase implements UserVmCloneSettingDao { - public static final Logger s_logger = Logger.getLogger(UserVmCloneSettingDaoImpl.class); protected SearchBuilder vmIdSearch; protected SearchBuilder cloneTypeSearch; diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDao.java b/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDao.java index 39c65866658..7de543e69d3 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDao.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDao.java @@ -53,7 +53,11 @@ public interface UserVmDao extends GenericDao { * @param hostName TODO * @param instanceName */ - void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData, Long userDataId, String userDataDetails, boolean displayVm, boolean isDynamicallyScalable, String customId, String hostName, String instanceName); + void updateVM(long id, String displayName, boolean enable, Long osTypeId, + String userData, Long userDataId, String userDataDetails, + boolean displayVm, boolean isDynamicallyScalable, + boolean deleteProtection, String customId, String hostName, + String instanceName); List findDestroyedVms(Date date); diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDaoImpl.java index 80fabf6a7f7..088a2b60b58 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDaoImpl.java @@ -26,12 +26,17 @@ import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.inject.Inject; +import com.cloud.configuration.Resource; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallback; +import org.apache.cloudstack.reservation.ReservationVO; +import org.apache.cloudstack.reservation.dao.ReservationDao; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import com.cloud.network.Network; import com.cloud.network.dao.NetworkDao; @@ -60,7 +65,6 @@ import com.cloud.vm.dao.UserVmData.NicData; import com.cloud.vm.dao.UserVmData.SecurityGroupData; public class UserVmDaoImpl extends GenericDaoBase implements UserVmDao { - public static final Logger s_logger = Logger.getLogger(UserVmDaoImpl.class); protected SearchBuilder AccountPodSearch; protected SearchBuilder AccountDataCenterSearch; @@ -93,9 +97,11 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use NetworkDao networkDao; @Inject NetworkOfferingServiceMapDao networkOfferingServiceMapDao; + @Inject + ReservationDao reservationDao; private static final String LIST_PODS_HAVING_VMS_FOR_ACCOUNT = - "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND (state = 'Running' OR state = 'Stopped') " + "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND state IN ('Starting', 'Running', 'Stopped') " + "GROUP BY pod_id HAVING count(id) > 0 ORDER BY count(id) DESC"; private static final String VM_DETAILS = "select vm_instance.id, " @@ -200,6 +206,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use CountByAccount.and("type", CountByAccount.entity().getType(), SearchCriteria.Op.EQ); CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN); CountByAccount.and("displayVm", CountByAccount.entity().isDisplayVm(), SearchCriteria.Op.EQ); + CountByAccount.and("idNIN", CountByAccount.entity().getId(), SearchCriteria.Op.NIN); CountByAccount.done(); CountActiveAccount = createSearchBuilder(Long.class); @@ -267,8 +274,11 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use } @Override - public void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData, Long userDataId, String userDataDetails, boolean displayVm, - boolean isDynamicallyScalable, String customId, String hostName, String instanceName) { + public void updateVM(long id, String displayName, boolean enable, Long osTypeId, + String userData, Long userDataId, String userDataDetails, + boolean displayVm, boolean isDynamicallyScalable, + boolean deleteProtection, String customId, String hostName, + String instanceName) { UserVmVO vo = createForUpdate(); vo.setDisplayName(displayName); vo.setHaEnabled(enable); @@ -278,6 +288,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use vo.setUserDataDetails(userDataDetails); vo.setDisplayVm(displayVm); vo.setDynamicallyScalable(isDynamicallyScalable); + vo.setDeleteProtection(deleteProtection); if (hostName != null) { vo.setHostName(hostName); } @@ -459,13 +470,13 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use } } catch (Exception e) { - s_logger.error("listPodIdsHavingVmsforAccount:Exception: " + e.getMessage()); + logger.error("listPodIdsHavingVmsforAccount:Exception: " + e.getMessage()); throw new CloudRuntimeException("listPodIdsHavingVmsforAccount:Exception: " + e.getMessage(), e); } txn.commit(); return result; } catch (Exception e) { - s_logger.error("listPodIdsHavingVmsforAccount:Exception : " + e.getMessage()); + logger.error("listPodIdsHavingVmsforAccount:Exception : " + e.getMessage()); throw new CloudRuntimeException("listPodIdsHavingVmsforAccount:Exception: " + e.getMessage(), e); } finally { @@ -477,7 +488,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use } catch (Exception e) { - s_logger.error("listPodIdsHavingVmsforAccount:Exception:" + e.getMessage()); + logger.error("listPodIdsHavingVmsforAccount:Exception:" + e.getMessage()); } } @@ -514,7 +525,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use } catch (Exception e) { - s_logger.error("listVmDetails:Exception:" + e.getMessage()); + logger.error("listVmDetails:Exception:" + e.getMessage()); throw new CloudRuntimeException("listVmDetails: Exception:" + e.getMessage(),e); } curr_index += VM_DETAILS_BATCH_SIZE; @@ -522,7 +533,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use } catch (Exception e) { - s_logger.error("listVmDetails:Exception:" + e.getMessage()); + logger.error("listVmDetails:Exception:" + e.getMessage()); throw new CloudRuntimeException("listVmDetails: Exception:" + e.getMessage(),e); } } @@ -550,20 +561,20 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use } catch (Exception e) { - s_logger.error("listVmDetails: Exception:" + e.getMessage()); + logger.error("listVmDetails: Exception:" + e.getMessage()); throw new CloudRuntimeException("listVmDetails: Exception:" + e.getMessage(),e); } } catch (Exception e) { - s_logger.error("listVmDetails:Exception:" + e.getMessage()); + logger.error("listVmDetails:Exception:" + e.getMessage()); throw new CloudRuntimeException("listVmDetails: Exception:" + e.getMessage(),e); } } txn.commit(); return userVmDataHash; } catch (Exception e) { - s_logger.error("listVmDetails:Exception:" + e.getMessage()); + logger.error("listVmDetails:Exception:" + e.getMessage()); throw new CloudRuntimeException("listVmDetails:Exception : ", e); } finally { @@ -575,7 +586,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use } catch (Exception e) { - s_logger.error("listVmDetails:Exception:" + e.getMessage()); + logger.error("listVmDetails:Exception:" + e.getMessage()); } } @@ -699,6 +710,9 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use @Override public Long countAllocatedVMsForAccount(long accountId, boolean runningVMsonly) { + List reservations = reservationDao.getReservationsForAccount(accountId, Resource.ResourceType.user_vm, null); + List reservedResourceIds = reservations.stream().filter(reservation -> reservation.getReservedAmount() > 0).map(ReservationVO::getResourceId).collect(Collectors.toList()); + SearchCriteria sc = CountByAccount.create(); sc.setParameters("account", accountId); sc.setParameters("type", VirtualMachine.Type.User); @@ -707,6 +721,11 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use else sc.setParameters("state", new Object[] {State.Destroyed, State.Error, State.Expunging}); sc.setParameters("displayVm", 1); + + if (CollectionUtils.isNotEmpty(reservedResourceIds)) { + sc.setParameters("idNIN", reservedResourceIds.toArray()); + } + return customSearch(sc, null).get(0); } @@ -740,7 +759,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use } } } catch (SQLException e) { - s_logger.error("GetVmsDetailsByNames: Exception in sql: " + e.getMessage()); + logger.error("GetVmsDetailsByNames: Exception in sql: " + e.getMessage()); throw new CloudRuntimeException("GetVmsDetailsByNames: Exception: " + e.getMessage()); } @@ -763,7 +782,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use result.add(new Ternary(rs.getInt(1), rs.getInt(2), rs.getInt(3))); } } catch (Exception e) { - s_logger.warn("Error counting vms by size for dcId= " + dcId, e); + logger.warn("Error counting vms by size for dcId= " + dcId, e); } return result; } @@ -794,4 +813,15 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use sc.setParameters("ids", ids.toArray()); return listBy(sc); } + + @Override + public UserVmVO persist(UserVmVO entity) { + return Transaction.execute((TransactionCallback) status -> { + UserVmVO userVM = super.persist(entity); + reservationDao.setResourceId(Resource.ResourceType.user_vm, userVM.getId()); + reservationDao.setResourceId(Resource.ResourceType.cpu, userVM.getId()); + reservationDao.setResourceId(Resource.ResourceType.memory, userVM.getId()); + return userVM; + }); + } } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDao.java b/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDao.java index 63f7ad974e6..823642d8c3d 100755 --- a/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDao.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDao.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.vm.dao; +import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -81,7 +82,7 @@ public interface VMInstanceDao extends GenericDao, StateDao< List listByHostAndState(long hostId, State... states); - List listByTypes(VirtualMachine.Type... types); + int countByTypes(VirtualMachine.Type... types); VMInstanceVO findByIdTypes(long id, VirtualMachine.Type... types); @@ -144,21 +145,28 @@ public interface VMInstanceDao extends GenericDao, StateDao< */ List listDistinctHostNames(long networkId, VirtualMachine.Type... types); + List findByHostInStatesExcluding(Long hostId, Collection excludingIds, State... states); + List findByHostInStates(Long hostId, State... states); List listStartingWithNoHostId(); boolean updatePowerState(long instanceId, long powerHostId, VirtualMachine.PowerState powerState, Date wisdomEra); + Map updatePowerState(Map instancePowerStates, + long powerHostId, Date wisdomEra); + void resetVmPowerStateTracking(long instanceId); + void resetVmPowerStateTracking(List instanceId); + void resetHostPowerStateTracking(long hostId); HashMap countVgpuVMs(Long dcId, Long podId, Long clusterId); VMInstanceVO findVMByHostNameInZone(String hostName, long zoneId); - boolean isPowerStateUpToDate(long instanceId); + boolean isPowerStateUpToDate(VMInstanceVO instance); List listNonMigratingVmsByHostEqualsLastHost(long hostId); @@ -166,5 +174,17 @@ public interface VMInstanceDao extends GenericDao, StateDao< List listByHostOrLastHostOrHostPod(List hostIds, long podId); + List searchRemovedByRemoveDate(final Date startDate, final Date endDate, final Long batchSize, + List skippedVmIds); + Pair, Integer> listByVmsNotInClusterUsingPool(long clusterId, long poolId); + + List listIdServiceOfferingForUpVmsByHostId(Long hostId); + + List listIdServiceOfferingForVmsMigratingFromHost(Long hostId); + + Map getNameIdMapForVmInstanceNames(Collection names); + + Map getNameIdMapForVmIds(Collection ids); + } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDaoImpl.java index a1bd25c2fbc..e6405fd34db 100755 --- a/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDaoImpl.java @@ -20,6 +20,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -29,7 +30,7 @@ import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.inject.Inject; -import org.apache.log4j.Logger; +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; import com.cloud.host.HostVO; @@ -43,6 +44,7 @@ import com.cloud.utils.DateUtil; import com.cloud.utils.Pair; import com.cloud.utils.db.Attribute; import com.cloud.utils.db.DB; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.JoinBuilder; @@ -68,13 +70,13 @@ import com.cloud.vm.VirtualMachine.Type; @Component public class VMInstanceDaoImpl extends GenericDaoBase implements VMInstanceDao { - public static final Logger s_logger = Logger.getLogger(VMInstanceDaoImpl.class); static final int MAX_CONSECUTIVE_SAME_STATE_UPDATE_COUNT = 3; protected SearchBuilder VMClusterSearch; protected SearchBuilder LHVMClusterSearch; protected SearchBuilder IdStatesSearch; protected SearchBuilder AllFieldsSearch; + protected SearchBuilder IdServiceOfferingIdSelectSearch; protected SearchBuilder ZoneTemplateNonExpungedSearch; protected SearchBuilder TemplateNonExpungedSearch; protected SearchBuilder NameLikeSearch; @@ -101,6 +103,7 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem protected SearchBuilder BackupSearch; protected SearchBuilder LastHostAndStatesSearch; protected SearchBuilder VmsNotInClusterUsingPool; + protected SearchBuilder IdsPowerStateSelectSearch; @Inject ResourceTagDao tagsDao; @@ -109,21 +112,21 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem @Inject VolumeDao volumeDao; @Inject - HostDao hostDao; + protected HostDao hostDao; protected Attribute _updateTimeAttr; - private static final String ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART1 = "SELECT host.cluster_id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) " + + private static final String ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART1 = "SELECT host.cluster_id, SUM(IF(vm.state IN ('Running', 'Starting') AND vm.account_id = ?, 1, 0)) " + "FROM `cloud`.`host` host LEFT JOIN `cloud`.`vm_instance` vm ON host.id = vm.host_id WHERE "; private static final String ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART2 = " AND host.type = 'Routing' AND host.removed is null GROUP BY host.cluster_id " + "ORDER BY 2 ASC "; - private static final String ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT = "SELECT pod.id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) FROM `cloud`.`" + + private static final String ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT = "SELECT pod.id, SUM(IF(vm.state IN ('Running', 'Starting') AND vm.account_id = ?, 1, 0)) FROM `cloud`.`" + "host_pod_ref` pod LEFT JOIN `cloud`.`vm_instance` vm ON pod.id = vm.pod_id WHERE pod.data_center_id = ? AND pod.removed is null " + " GROUP BY pod.id ORDER BY 2 ASC "; private static final String ORDER_HOSTS_NUMBER_OF_VMS_FOR_ACCOUNT = - "SELECT host.id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) FROM `cloud`.`host` host LEFT JOIN `cloud`.`vm_instance` vm ON host.id = vm.host_id " + + "SELECT host.id, SUM(IF(vm.state IN ('Running', 'Starting') AND vm.account_id = ?, 1, 0)) FROM `cloud`.`host` host LEFT JOIN `cloud`.`vm_instance` vm ON host.id = vm.host_id " + "WHERE host.data_center_id = ? AND host.type = 'Routing' AND host.removed is null "; private static final String ORDER_HOSTS_NUMBER_OF_VMS_FOR_ACCOUNT_PART2 = " GROUP BY host.id ORDER BY 2 ASC "; @@ -140,8 +143,6 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem private static final String COUNT_VMS_BY_ZONE_AND_STATE_AND_HOST_TAG = "SELECT COUNT(1) FROM vm_instance vi JOIN service_offering so ON vi.service_offering_id=so.id " + "JOIN vm_template vt ON vi.vm_template_id = vt.id WHERE vi.data_center_id = ? AND vi.state = ? AND vi.removed IS NULL AND (so.host_tag = ? OR vt.template_tag = ?)"; - @Inject - protected HostDao _hostDao; public VMInstanceDaoImpl() { } @@ -155,13 +156,13 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem IdStatesSearch.done(); VMClusterSearch = createSearchBuilder(); - SearchBuilder hostSearch = _hostDao.createSearchBuilder(); + SearchBuilder hostSearch = hostDao.createSearchBuilder(); VMClusterSearch.join("hostSearch", hostSearch, hostSearch.entity().getId(), VMClusterSearch.entity().getHostId(), JoinType.INNER); hostSearch.and("clusterId", hostSearch.entity().getClusterId(), SearchCriteria.Op.EQ); VMClusterSearch.done(); LHVMClusterSearch = createSearchBuilder(); - SearchBuilder hostSearch1 = _hostDao.createSearchBuilder(); + SearchBuilder hostSearch1 = hostDao.createSearchBuilder(); LHVMClusterSearch.join("hostSearch1", hostSearch1, hostSearch1.entity().getId(), LHVMClusterSearch.entity().getLastHostId(), JoinType.INNER); LHVMClusterSearch.and("hostid", LHVMClusterSearch.entity().getHostId(), Op.NULL); hostSearch1.and("clusterId", hostSearch1.entity().getClusterId(), SearchCriteria.Op.EQ); @@ -177,6 +178,14 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), Op.EQ); AllFieldsSearch.done(); + IdServiceOfferingIdSelectSearch = createSearchBuilder(); + IdServiceOfferingIdSelectSearch.and("host", IdServiceOfferingIdSelectSearch.entity().getHostId(), Op.EQ); + IdServiceOfferingIdSelectSearch.and("lastHost", IdServiceOfferingIdSelectSearch.entity().getLastHostId(), Op.EQ); + IdServiceOfferingIdSelectSearch.and("state", IdServiceOfferingIdSelectSearch.entity().getState(), Op.EQ); + IdServiceOfferingIdSelectSearch.and("states", IdServiceOfferingIdSelectSearch.entity().getState(), Op.IN); + IdServiceOfferingIdSelectSearch.selectFields(IdServiceOfferingIdSelectSearch.entity().getId(), IdServiceOfferingIdSelectSearch.entity().getServiceOfferingId()); + IdServiceOfferingIdSelectSearch.done(); + ZoneTemplateNonExpungedSearch = createSearchBuilder(); ZoneTemplateNonExpungedSearch.and("zone", ZoneTemplateNonExpungedSearch.entity().getDataCenterId(), Op.EQ); ZoneTemplateNonExpungedSearch.and("template", ZoneTemplateNonExpungedSearch.entity().getTemplateId(), Op.EQ); @@ -276,6 +285,7 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem HostAndStateSearch = createSearchBuilder(); HostAndStateSearch.and("host", HostAndStateSearch.entity().getHostId(), Op.EQ); HostAndStateSearch.and("states", HostAndStateSearch.entity().getState(), Op.IN); + HostAndStateSearch.and("idsNotIn", HostAndStateSearch.entity().getId(), Op.NIN); HostAndStateSearch.done(); StartingWithNoHostSearch = createSearchBuilder(); @@ -325,6 +335,15 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem VmsNotInClusterUsingPool.join("hostSearch2", hostSearch2, hostSearch2.entity().getId(), VmsNotInClusterUsingPool.entity().getHostId(), JoinType.INNER); VmsNotInClusterUsingPool.and("vmStates", VmsNotInClusterUsingPool.entity().getState(), Op.IN); VmsNotInClusterUsingPool.done(); + + IdsPowerStateSelectSearch = createSearchBuilder(); + IdsPowerStateSelectSearch.and("id", IdsPowerStateSelectSearch.entity().getId(), Op.IN); + IdsPowerStateSelectSearch.selectFields(IdsPowerStateSelectSearch.entity().getId(), + IdsPowerStateSelectSearch.entity().getPowerHostId(), + IdsPowerStateSelectSearch.entity().getPowerState(), + IdsPowerStateSelectSearch.entity().getPowerStateUpdateCount(), + IdsPowerStateSelectSearch.entity().getPowerStateUpdateTime()); + IdsPowerStateSelectSearch.done(); } @Override @@ -460,10 +479,10 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem } @Override - public List listByTypes(Type... types) { + public int countByTypes(Type... types) { SearchCriteria sc = TypesSearch.create(); sc.setParameters("types", (Object[])types); - return listBy(sc); + return getCount(sc); } @Override @@ -522,8 +541,8 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem @Override public boolean updateState(State oldState, Event event, State newState, VirtualMachine vm, Object opaque) { if (newState == null) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("There's no way to transition from old state: " + oldState.toString() + " event: " + event.toString()); + if (logger.isDebugEnabled()) { + logger.debug("There's no way to transition from old state: " + oldState.toString() + " event: " + event.toString()); } return false; } @@ -565,7 +584,7 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem if (result == 0) { VMInstanceVO vo = findByIdIncludingRemoved(vm.getId()); - if (s_logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { if (vo != null) { StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); str.append(": DB Data={Host=").append(vo.getHostId()).append("; State=").append(vo.getState().toString()).append("; updated=").append(vo.getUpdated()) @@ -574,16 +593,16 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem .append("; time=").append(vo.getUpdateTime()); str.append("} Stale Data: {Host=").append(oldHostId).append("; State=").append(oldState).append("; updated=").append(oldUpdated).append("; time=") .append(oldUpdateDate).append("}"); - s_logger.debug(str.toString()); + logger.debug(str.toString()); } else { - s_logger.debug("Unable to update the vm id=" + vm.getId() + "; the vm either doesn't exist or already removed"); + logger.debug("Unable to update the vm {}; the vm either doesn't exist or already removed", vm); } } if (vo != null && vo.getState() == newState) { // allow for concurrent update if target state has already been matched - s_logger.debug("VM " + vo.getInstanceName() + " state has been already been updated to " + newState); + logger.debug("VM {} state has been already been updated to {}", vo, newState); return true; } } @@ -845,7 +864,7 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem return rs.getLong(1); } } catch (Exception e) { - s_logger.warn(String.format("Error counting vms by host tag for dcId= %s, hostTag= %s", dcId, hostTag), e); + logger.warn(String.format("Error counting vms by host tag for dcId= %s, hostTag= %s", dcId, hostTag), e); } return 0L; } @@ -899,6 +918,17 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem return result; } + @Override + public List findByHostInStatesExcluding(Long hostId, Collection excludingIds, State... states) { + SearchCriteria sc = HostAndStateSearch.create(); + sc.setParameters("host", hostId); + if (excludingIds != null && !excludingIds.isEmpty()) { + sc.setParameters("idsNotIn", excludingIds.toArray()); + } + sc.setParameters("states", (Object[])states); + return listBy(sc); + } + @Override public List findByHostInStates(Long hostId, State... states) { SearchCriteria sc = HostAndStateSearch.create(); @@ -914,59 +944,124 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem return listBy(sc); } - @Override - public boolean updatePowerState(final long instanceId, final long powerHostId, final VirtualMachine.PowerState powerState, Date wisdomEra) { - return Transaction.execute(new TransactionCallback<>() { - @Override - public Boolean doInTransaction(TransactionStatus status) { - boolean needToUpdate = false; - VMInstanceVO instance = findById(instanceId); - if (instance != null - && (null == instance.getPowerStateUpdateTime() - || instance.getPowerStateUpdateTime().before(wisdomEra))) { - Long savedPowerHostId = instance.getPowerHostId(); - if (instance.getPowerState() != powerState - || savedPowerHostId == null - || savedPowerHostId != powerHostId - || !isPowerStateInSyncWithInstanceState(powerState, powerHostId, instance)) { - instance.setPowerState(powerState); - instance.setPowerHostId(powerHostId); - instance.setPowerStateUpdateCount(1); - instance.setPowerStateUpdateTime(DateUtil.currentGMTTime()); - needToUpdate = true; - update(instanceId, instance); - } else { - // to reduce DB updates, consecutive same state update for more than 3 times - if (instance.getPowerStateUpdateCount() < MAX_CONSECUTIVE_SAME_STATE_UPDATE_COUNT) { - instance.setPowerStateUpdateCount(instance.getPowerStateUpdateCount() + 1); - instance.setPowerStateUpdateTime(DateUtil.currentGMTTime()); - needToUpdate = true; - update(instanceId, instance); - } - } - } - return needToUpdate; + protected List listSelectPowerStateByIds(final List ids) { + if (CollectionUtils.isEmpty(ids)) { + return new ArrayList<>(); + } + SearchCriteria sc = IdsPowerStateSelectSearch.create(); + sc.setParameters("id", ids.toArray()); + return customSearch(sc, null); + } + + protected Integer getPowerUpdateCount(final VMInstanceVO instance, final long powerHostId, + final VirtualMachine.PowerState powerState, Date wisdomEra) { + if (instance.getPowerStateUpdateTime() == null || instance.getPowerStateUpdateTime().before(wisdomEra)) { + Long savedPowerHostId = instance.getPowerHostId(); + boolean isStateMismatch = instance.getPowerState() != powerState + || savedPowerHostId == null + || !savedPowerHostId.equals(powerHostId) + || !isPowerStateInSyncWithInstanceState(powerState, powerHostId, instance); + if (isStateMismatch) { + return 1; + } else if (instance.getPowerStateUpdateCount() < MAX_CONSECUTIVE_SAME_STATE_UPDATE_COUNT) { + return instance.getPowerStateUpdateCount() + 1; } + } + return null; + } + + @Override + public boolean updatePowerState(final long instanceId, final long powerHostId, + final VirtualMachine.PowerState powerState, Date wisdomEra) { + return Transaction.execute((TransactionCallback) status -> { + VMInstanceVO instance = findById(instanceId); + if (instance == null) { + return false; + } + // Check if we need to update based on powerStateUpdateTime + if (instance.getPowerStateUpdateTime() == null || instance.getPowerStateUpdateTime().before(wisdomEra)) { + Long savedPowerHostId = instance.getPowerHostId(); + boolean isStateMismatch = instance.getPowerState() != powerState + || savedPowerHostId == null + || !savedPowerHostId.equals(powerHostId) + || !isPowerStateInSyncWithInstanceState(powerState, powerHostId, instance); + + if (isStateMismatch) { + instance.setPowerState(powerState); + instance.setPowerHostId(powerHostId); + instance.setPowerStateUpdateCount(1); + } else if (instance.getPowerStateUpdateCount() < MAX_CONSECUTIVE_SAME_STATE_UPDATE_COUNT) { + instance.setPowerStateUpdateCount(instance.getPowerStateUpdateCount() + 1); + } else { + // No need to update if power state is already in sync and count exceeded + return false; + } + instance.setPowerStateUpdateTime(DateUtil.currentGMTTime()); + update(instanceId, instance); + return true; // Return true since an update occurred + } + return false; }); } + @Override + public Map updatePowerState( + final Map instancePowerStates, long powerHostId, Date wisdomEra) { + Map notUpdated = new HashMap<>(); + List instances = listSelectPowerStateByIds(new ArrayList<>(instancePowerStates.keySet())); + Map updateCounts = new HashMap<>(); + for (VMInstanceVO instance : instances) { + VirtualMachine.PowerState powerState = instancePowerStates.get(instance.getId()); + Integer count = getPowerUpdateCount(instance, powerHostId, powerState, wisdomEra); + if (count != null) { + updateCounts.put(instance.getId(), count); + } else { + notUpdated.put(instance.getId(), powerState); + } + } + if (updateCounts.isEmpty()) { + return notUpdated; + } + StringBuilder sql = new StringBuilder("UPDATE `cloud`.`vm_instance` SET " + + "`power_host` = ?, `power_state_update_time` = now(), `power_state` = CASE "); + updateCounts.keySet().forEach(key -> { + sql.append("WHEN id = ").append(key).append(" THEN '").append(instancePowerStates.get(key)).append("' "); + }); + sql.append("END, `power_state_update_count` = CASE "); + StringBuilder idList = new StringBuilder(); + updateCounts.forEach((key, value) -> { + sql.append("WHEN `id` = ").append(key).append(" THEN ").append(value).append(" "); + idList.append(key).append(","); + }); + idList.setLength(idList.length() - 1); + sql.append("END WHERE `id` IN (").append(idList).append(")"); + TransactionLegacy txn = TransactionLegacy.currentTxn(); + try (PreparedStatement pstmt = txn.prepareAutoCloseStatement(sql.toString())) { + pstmt.setLong(1, powerHostId); + pstmt.executeUpdate(); + } catch (SQLException e) { + logger.error("Unable to execute update power states SQL from VMs {} due to: {}", + idList, e.getMessage(), e); + return instancePowerStates; + } + return notUpdated; + } + private boolean isPowerStateInSyncWithInstanceState(final VirtualMachine.PowerState powerState, final long powerHostId, final VMInstanceVO instance) { State instanceState = instance.getState(); if ((powerState == VirtualMachine.PowerState.PowerOff && instanceState == State.Running) || (powerState == VirtualMachine.PowerState.PowerOn && instanceState == State.Stopped)) { - s_logger.debug(String.format("VM id: %d on host id: %d and power host id: %d is in %s state, but power state is %s", - instance.getId(), instance.getHostId(), powerHostId, instanceState, powerState)); + HostVO instanceHost = hostDao.findById(instance.getHostId()); + HostVO powerHost = powerHostId == instance.getHostId() ? instanceHost : hostDao.findById(powerHostId); + logger.debug("VM: {} on host: {} and power host : {} is in {} state, but power state is {}", + instance, instanceHost, powerHost, instanceState, powerState); return false; } return true; } @Override - public boolean isPowerStateUpToDate(final long instanceId) { - VMInstanceVO instance = findById(instanceId); - if(instance == null) { - throw new CloudRuntimeException("checking power state update count on non existing instance " + instanceId); - } + public boolean isPowerStateUpToDate(final VMInstanceVO instance) { return instance.getPowerStateUpdateCount() < MAX_CONSECUTIVE_SAME_STATE_UPDATE_COUNT; } @@ -985,6 +1080,25 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem }); } + @Override + public void resetVmPowerStateTracking(List instanceIds) { + if (CollectionUtils.isEmpty(instanceIds)) { + return; + } + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + SearchCriteria sc = IdsPowerStateSelectSearch.create(); + sc.setParameters("id", instanceIds.toArray()); + VMInstanceVO vm = createForUpdate(); + vm.setPowerStateUpdateCount(0); + vm.setPowerStateUpdateTime(DateUtil.currentGMTTime()); + UpdateBuilder ub = getUpdateBuilder(vm); + update(ub, sc, null); + } + }); + } + @Override @DB public void resetHostPowerStateTracking(final long hostId) { Transaction.execute(new TransactionCallbackNoReturn() { @@ -1038,6 +1152,28 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem return listBy(sc); } + @Override + public List searchRemovedByRemoveDate(Date startDate, Date endDate, Long batchSize, + List skippedVmIds) { + SearchBuilder sb = createSearchBuilder(); + sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.NNULL); + sb.and("startDate", sb.entity().getRemoved(), SearchCriteria.Op.GTEQ); + sb.and("endDate", sb.entity().getRemoved(), SearchCriteria.Op.LTEQ); + sb.and("skippedVmIds", sb.entity().getId(), Op.NOTIN); + SearchCriteria sc = sb.create(); + if (startDate != null) { + sc.setParameters("startDate", startDate); + } + if (endDate != null) { + sc.setParameters("endDate", endDate); + } + if (CollectionUtils.isNotEmpty(skippedVmIds)) { + sc.setParameters("skippedVmIds", skippedVmIds.toArray()); + } + Filter filter = new Filter(VMInstanceVO.class, "id", true, 0L, batchSize); + return searchIncludingRemoved(sc, filter, null, false); + } + @Override public Pair, Integer> listByVmsNotInClusterUsingPool(long clusterId, long poolId) { SearchCriteria sc = VmsNotInClusterUsingPool.create(); @@ -1048,4 +1184,44 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem List uniqueVms = vms.stream().distinct().collect(Collectors.toList()); return new Pair<>(uniqueVms, uniqueVms.size()); } + + @Override + public List listIdServiceOfferingForUpVmsByHostId(Long hostId) { + SearchCriteria sc = IdServiceOfferingIdSelectSearch.create(); + sc.setParameters("host", hostId); + sc.setParameters("states", new Object[] {State.Starting, State.Running, State.Stopping, State.Migrating}); + return customSearch(sc, null); + } + + @Override + public List listIdServiceOfferingForVmsMigratingFromHost(Long hostId) { + SearchCriteria sc = IdServiceOfferingIdSelectSearch.create(); + sc.setParameters("lastHost", hostId); + sc.setParameters("state", State.Migrating); + return customSearch(sc, null); + } + + @Override + public Map getNameIdMapForVmInstanceNames(Collection names) { + SearchBuilder sb = createSearchBuilder(); + sb.and("name", sb.entity().getInstanceName(), Op.IN); + sb.selectFields(sb.entity().getId(), sb.entity().getInstanceName()); + SearchCriteria sc = sb.create(); + sc.setParameters("name", names.toArray()); + List vms = customSearch(sc, null); + return vms.stream() + .collect(Collectors.toMap(VMInstanceVO::getInstanceName, VMInstanceVO::getId)); + } + + @Override + public Map getNameIdMapForVmIds(Collection ids) { + SearchBuilder sb = createSearchBuilder(); + sb.and("id", sb.entity().getId(), Op.IN); + sb.selectFields(sb.entity().getId(), sb.entity().getInstanceName()); + SearchCriteria sc = sb.create(); + sc.setParameters("id", ids.toArray()); + List vms = customSearch(sc, null); + return vms.stream() + .collect(Collectors.toMap(VMInstanceVO::getInstanceName, VMInstanceVO::getId)); + } } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/VmStatsDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/VmStatsDaoImpl.java index a98302e2136..327acec0c17 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/VmStatsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/VmStatsDaoImpl.java @@ -21,7 +21,8 @@ import java.util.List; import javax.annotation.PostConstruct; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.Filter; @@ -34,7 +35,7 @@ import com.cloud.vm.VmStatsVO; @Component public class VmStatsDaoImpl extends GenericDaoBase implements VmStatsDao { - protected Logger logger = Logger.getLogger(getClass()); + protected Logger logger = LogManager.getLogger(getClass()); protected SearchBuilder vmIdSearch; protected SearchBuilder vmIdTimestampGreaterThanEqualSearch; @@ -122,14 +123,7 @@ public class VmStatsDaoImpl extends GenericDaoBase implements V logger.debug(String.format("Starting to remove all vm_stats rows older than [%s].", limitDate)); - long totalRemoved = 0; - long removed; - - do { - removed = expunge(sc, limitPerQuery); - totalRemoved += removed; - logger.trace(String.format("Removed [%s] vm_stats rows on the last update and a sum of [%s] vm_stats rows older than [%s] until now.", removed, totalRemoved, limitDate)); - } while (limitPerQuery > 0 && removed >= limitPerQuery); + long totalRemoved = batchExpunge(sc, limitPerQuery); logger.info(String.format("Removed a total of [%s] vm_stats rows older than [%s].", totalRemoved, limitDate)); } diff --git a/engine/schema/src/main/java/com/cloud/vm/snapshot/VMSnapshotVO.java b/engine/schema/src/main/java/com/cloud/vm/snapshot/VMSnapshotVO.java index c48396ad021..5b6f97b82e7 100644 --- a/engine/schema/src/main/java/com/cloud/vm/snapshot/VMSnapshotVO.java +++ b/engine/schema/src/main/java/com/cloud/vm/snapshot/VMSnapshotVO.java @@ -36,6 +36,7 @@ import javax.persistence.Transient; import org.apache.cloudstack.engine.subsystem.api.storage.VMSnapshotOptions; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "vm_snapshots") @@ -145,6 +146,13 @@ public class VMSnapshotVO implements VMSnapshot { this.serviceOfferingId = serviceOfferingId; } + @Override + public String toString() { + return String.format("VMSnapshot %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "vmId")); + } + @Override public String getDescription() { return description; diff --git a/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDao.java b/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDao.java index 31999ef15d6..bbdbfb5b520 100644 --- a/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDao.java +++ b/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDao.java @@ -38,4 +38,8 @@ public interface VMSnapshotDao extends GenericDao, StateDao< VMSnapshotVO findByName(Long vmId, String name); List listByAccountId(Long accountId); + + List searchByVms(List vmIds); + + List searchRemovedByVms(List vmIds, Long batchSize); } diff --git a/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDaoImpl.java index 1b1842dfd89..03a978f8546 100644 --- a/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDaoImpl.java @@ -17,13 +17,14 @@ package com.cloud.vm.snapshot.dao; +import java.util.ArrayList; import java.util.Date; import java.util.List; - -import org.apache.log4j.Logger; +import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Component; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @@ -36,7 +37,6 @@ import com.cloud.vm.snapshot.VMSnapshotVO; @Component public class VMSnapshotDaoImpl extends GenericDaoBase implements VMSnapshotDao { - private static final Logger s_logger = Logger.getLogger(VMSnapshotDaoImpl.class); private final SearchBuilder SnapshotSearch; private final SearchBuilder ExpungingSnapshotSearch; private final SearchBuilder SnapshotStatusSearch; @@ -143,7 +143,7 @@ public class VMSnapshotDaoImpl extends GenericDaoBase implem builder.set(vo, "updated", new Date()); int rows = update((VMSnapshotVO)vo, sc); - if (rows == 0 && s_logger.isDebugEnabled()) { + if (rows == 0 && logger.isDebugEnabled()) { VMSnapshotVO dbVol = findByIdIncludingRemoved(vo.getId()); if (dbVol != null) { StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); @@ -176,10 +176,35 @@ public class VMSnapshotDaoImpl extends GenericDaoBase implem .append("; updatedTime=") .append(oldUpdatedTime); } else { - s_logger.debug("Unable to update VM snapshot: id=" + vo.getId() + ", as there is no such snapshot exists in the database anymore"); + logger.debug("Unable to update VM snapshot: {}, as there is no such snapshot exists in the database anymore", vo); } } return rows > 0; } + @Override + public List searchByVms(List vmIds) { + if (CollectionUtils.isEmpty(vmIds)) { + return new ArrayList<>(); + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getVmId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + return search(sc, null); + } + + @Override + public List searchRemovedByVms(List vmIds, Long batchSize) { + if (CollectionUtils.isEmpty(vmIds)) { + return new ArrayList<>(); + } + SearchBuilder sb = createSearchBuilder(); + sb.and("vmIds", sb.entity().getVmId(), SearchCriteria.Op.IN); + sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.NNULL); + SearchCriteria sc = sb.create(); + sc.setParameters("vmIds", vmIds.toArray()); + Filter filter = new Filter(VMSnapshotVO.class, "id", true, 0L, batchSize); + return searchIncludingRemoved(sc, filter, null, false); + } } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/acl/RoleVO.java b/engine/schema/src/main/java/org/apache/cloudstack/acl/RoleVO.java index d4647255fc6..cff139a9263 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/acl/RoleVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/acl/RoleVO.java @@ -58,11 +58,16 @@ public class RoleVO implements Role { @Column(name = "public_role") private boolean publicRole = true; + @Column(name = "state") + @Enumerated(value = EnumType.STRING) + private State state; + @Column(name = GenericDao.REMOVED_COLUMN) private Date removed; public RoleVO() { this.uuid = UUID.randomUUID().toString(); + this.state = State.ENABLED; } public RoleVO(final String name, final RoleType roleType, final String description) { @@ -121,7 +126,8 @@ public class RoleVO implements Role { @Override public String toString() { - return ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "name", "uuid", "roleType"); + return String.format("Role %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "roleType")); } public boolean isPublicRole() { @@ -131,4 +137,12 @@ public class RoleVO implements Role { public void setPublicRole(boolean publicRole) { this.publicRole = publicRole; } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/ProjectRolePermissionsDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/ProjectRolePermissionsDaoImpl.java index d88a6f5453d..d028ca58b32 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/ProjectRolePermissionsDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/ProjectRolePermissionsDaoImpl.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.acl.ProjectRole; import org.apache.cloudstack.acl.RolePermissionEntity.Permission; import org.apache.cloudstack.acl.ProjectRolePermission; import org.apache.cloudstack.acl.ProjectRolePermissionVO; -import org.apache.log4j.Logger; import com.cloud.utils.db.Attribute; import com.cloud.utils.db.Filter; @@ -42,7 +41,6 @@ import com.cloud.utils.exception.CloudRuntimeException; public class ProjectRolePermissionsDaoImpl extends GenericDaoBase implements ProjectRolePermissionsDao{ - private static final Logger LOGGER = Logger.getLogger(ProjectRolePermissionsDaoImpl.class); private final SearchBuilder ProjectRolePermissionsSearch; private Attribute sortOrderAttribute; diff --git a/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RoleDao.java b/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RoleDao.java index 2d4151afc7d..f4fdb6a2b16 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RoleDao.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RoleDao.java @@ -28,15 +28,15 @@ import java.util.List; public interface RoleDao extends GenericDao { List findAllByName(String roleName, boolean showPrivateRole); - Pair, Integer> findAllByName(final String roleName, String keyword, Long offset, Long limit, boolean showPrivateRole); + Pair, Integer> findAllByName(final String roleName, String keyword, String state, Long offset, Long limit, boolean showPrivateRole); List findAllByRoleType(RoleType type, boolean showPrivateRole); List findByName(String roleName, boolean showPrivateRole); RoleVO findByNameAndType(String roleName, RoleType type, boolean showPrivateRole); - Pair, Integer> findAllByRoleType(RoleType type, Long offset, Long limit, boolean showPrivateRole); + Pair, Integer> findAllByRoleType(RoleType type, String state, Long offset, Long limit, boolean showPrivateRole); - Pair, Integer> listAllRoles(Long startIndex, Long limit, boolean showPrivateRole); + Pair, Integer> listAllRoles(String state, Long startIndex, Long limit, boolean showPrivateRole); List searchByIds(Long... ids); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RoleDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RoleDaoImpl.java index 2e8fdd5fcc2..48c0d828a41 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RoleDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RoleDaoImpl.java @@ -50,11 +50,13 @@ public class RoleDaoImpl extends GenericDaoBase implements RoleDao RoleByNameSearch = createSearchBuilder(); RoleByNameSearch.and("roleName", RoleByNameSearch.entity().getName(), SearchCriteria.Op.LIKE); RoleByNameSearch.and("isPublicRole", RoleByNameSearch.entity().isPublicRole(), SearchCriteria.Op.EQ); + RoleByNameSearch.and("state", RoleByNameSearch.entity().getState(), SearchCriteria.Op.EQ); RoleByNameSearch.done(); RoleByTypeSearch = createSearchBuilder(); RoleByTypeSearch.and("roleType", RoleByTypeSearch.entity().getRoleType(), SearchCriteria.Op.EQ); RoleByTypeSearch.and("isPublicRole", RoleByTypeSearch.entity().isPublicRole(), SearchCriteria.Op.EQ); + RoleByTypeSearch.and("state", RoleByTypeSearch.entity().getState(), SearchCriteria.Op.EQ); RoleByTypeSearch.done(); RoleByNameAndTypeSearch = createSearchBuilder(); @@ -65,16 +67,17 @@ public class RoleDaoImpl extends GenericDaoBase implements RoleDao RoleByIsPublicSearch = createSearchBuilder(); RoleByIsPublicSearch.and("isPublicRole", RoleByIsPublicSearch.entity().isPublicRole(), SearchCriteria.Op.EQ); + RoleByIsPublicSearch.and("state", RoleByIsPublicSearch.entity().getState(), SearchCriteria.Op.EQ); RoleByIsPublicSearch.done(); } @Override public List findAllByName(final String roleName, boolean showPrivateRole) { - return findAllByName(roleName, null, null, null, showPrivateRole).first(); + return findAllByName(roleName, null, null, null, null, showPrivateRole).first(); } @Override - public Pair, Integer> findAllByName(final String roleName, String keyword, Long offset, Long limit, boolean showPrivateRole) { + public Pair, Integer> findAllByName(final String roleName, String keyword, String state, Long offset, Long limit, boolean showPrivateRole) { SearchCriteria sc = RoleByNameSearch.create(); filterPrivateRolesIfNeeded(sc, showPrivateRole); if (StringUtils.isNotEmpty(roleName)) { @@ -83,19 +86,25 @@ public class RoleDaoImpl extends GenericDaoBase implements RoleDao if (StringUtils.isNotEmpty(keyword)) { sc.setParameters("roleName", "%" + keyword + "%"); } + if (StringUtils.isNotEmpty(state)) { + sc.setParameters("state", state); + } return searchAndCount(sc, new Filter(RoleVO.class, "id", true, offset, limit)); } @Override public List findAllByRoleType(final RoleType type, boolean showPrivateRole) { - return findAllByRoleType(type, null, null, showPrivateRole).first(); + return findAllByRoleType(type, null, null, null, showPrivateRole).first(); } - public Pair, Integer> findAllByRoleType(final RoleType type, Long offset, Long limit, boolean showPrivateRole) { + public Pair, Integer> findAllByRoleType(final RoleType type, String state, Long offset, Long limit, boolean showPrivateRole) { SearchCriteria sc = RoleByTypeSearch.create(); filterPrivateRolesIfNeeded(sc, showPrivateRole); sc.setParameters("roleType", type); + if (StringUtils.isNotEmpty(state)) { + sc.setParameters("state", state); + } return searchAndCount(sc, new Filter(RoleVO.class, "id", true, offset, limit)); } @@ -117,8 +126,11 @@ public class RoleDaoImpl extends GenericDaoBase implements RoleDao } @Override - public Pair, Integer> listAllRoles(Long startIndex, Long limit, boolean showPrivateRole) { + public Pair, Integer> listAllRoles(String state, Long startIndex, Long limit, boolean showPrivateRole) { SearchCriteria sc = RoleByIsPublicSearch.create(); + if (StringUtils.isNotEmpty(state)) { + sc.setParameters("state", state); + } filterPrivateRolesIfNeeded(sc, showPrivateRole); return searchAndCount(sc, new Filter(RoleVO.class, "id", true, startIndex, limit)); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RolePermissionsDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RolePermissionsDaoImpl.java index b63dd502ee7..7802265928e 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RolePermissionsDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/acl/dao/RolePermissionsDaoImpl.java @@ -27,7 +27,6 @@ import org.apache.cloudstack.acl.Role; import org.apache.cloudstack.acl.RolePermission; import org.apache.cloudstack.acl.RolePermissionEntity.Permission; import org.apache.cloudstack.acl.RolePermissionVO; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.utils.db.Attribute; @@ -43,7 +42,6 @@ import com.cloud.utils.exception.CloudRuntimeException; @Component public class RolePermissionsDaoImpl extends GenericDaoBase implements RolePermissionsDao { - protected static final Logger LOGGER = Logger.getLogger(RolePermissionsDaoImpl.class); private final SearchBuilder RolePermissionsSearchByRoleAndRule; private final SearchBuilder RolePermissionsSearch; @@ -90,7 +88,7 @@ public class RolePermissionsDaoImpl extends GenericDaoBase implements AffinityGroupDomainMapDao { - public static Logger logger = Logger.getLogger(NetworkDomainDaoImpl.class.getName()); private SearchBuilder ListByAffinityGroup; diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupRepositoryVO.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupRepositoryVO.java new file mode 100644 index 00000000000..e8364520ed0 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupRepositoryVO.java @@ -0,0 +1,155 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.backup; + +import com.cloud.utils.db.Encrypt; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name = "backup_repository") +public class BackupRepositoryVO implements BackupRepository { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "uuid") + private String uuid; + + @Column(name = "name") + private String name; + + @Column(name = "zone_id", nullable = false) + private long zoneId; + + @Column(name = "provider", nullable = false) + private String provider; + + @Column(name = "type", nullable = false) + private String type; + + @Column(name = "address", nullable = false) + private String address; + + @Encrypt + @Column(name = "mount_opts") + private String mountOptions; + + @Column(name = "used_bytes",nullable = true) + private Long usedBytes; + + @Column(name = "capacity_bytes", nullable = true) + private Long capacityBytes; + + @Column(name = "created") + @Temporal(value = TemporalType.TIMESTAMP) + private Date created; + + @Column(name = "removed") + @Temporal(value = TemporalType.TIMESTAMP) + private Date removed; + + public BackupRepositoryVO() { + this.uuid = UUID.randomUUID().toString(); + } + + public BackupRepositoryVO(final long zoneId, final String provider, final String name, final String type, final String address, final String mountOptions, final Long capacityBytes) { + this(); + this.zoneId = zoneId; + this.provider = provider; + this.name = name; + this.type = type; + this.address = address; + this.mountOptions = mountOptions; + this.capacityBytes = capacityBytes; + this.created = new Date(); + } + + public String getUuid() { + return uuid; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public long getZoneId() { + return zoneId; + } + + @Override + public String getProvider() { + return provider; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public void setAddress(String address) { + this.address = address; + } + + @Override + public String getAddress() { + return address; + } + + @Override + public String getMountOptions() { + return mountOptions; + } + + @Override + public Long getUsedBytes() { + return usedBytes; + } + + @Override + public Long getCapacityBytes() { + return capacityBytes; + } + + public Date getCreated() { + return created; + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupScheduleVO.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupScheduleVO.java index ba31dc59d39..fd3c0be18d2 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupScheduleVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupScheduleVO.java @@ -29,6 +29,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.DateUtil; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "backup_schedule") @@ -68,6 +69,12 @@ public class BackupScheduleVO implements BackupSchedule { this.scheduledTimestamp = scheduledTimestamp; } + @Override + public String toString() { + return String.format("BackupSchedule %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "vmId", "schedule", "scheduleType")); + } + @Override public long getId() { return id; diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupVO.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupVO.java index b6ad0e7cb8f..b4cd2f7bada 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupVO.java @@ -18,8 +18,14 @@ package org.apache.cloudstack.backup; import com.cloud.utils.db.GenericDao; +import com.google.gson.Gson; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; +import org.apache.commons.lang3.StringUtils; +import java.util.Arrays; +import java.util.Collections; import java.util.Date; +import java.util.List; import java.util.UUID; import javax.persistence.Column; @@ -82,10 +88,19 @@ public class BackupVO implements Backup { @Column(name = "zone_id") private long zoneId; + @Column(name = "backed_volumes", length = 65535) + protected String backedUpVolumes; + public BackupVO() { this.uuid = UUID.randomUUID().toString(); } + @Override + public String toString() { + return String.format("Backup %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "vmId", "backupType", "externalId")); + } + @Override public long getId() { return id; @@ -203,6 +218,17 @@ public class BackupVO implements Backup { return null; } + public List getBackedUpVolumes() { + if (StringUtils.isEmpty(this.backedUpVolumes)) { + return Collections.emptyList(); + } + return Arrays.asList(new Gson().fromJson(this.backedUpVolumes, Backup.VolumeInfo[].class)); + } + + public void setBackedUpVolumes(String backedUpVolumes) { + this.backedUpVolumes = backedUpVolumes; + } + public Date getRemoved() { return removed; } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupDao.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupDao.java index 5d2f5ac64d6..89a13245b0a 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupDao.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupDao.java @@ -32,9 +32,8 @@ public interface BackupDao extends GenericDao { List listByVmId(Long zoneId, Long vmId); List listByAccountId(Long accountId); - List listByOfferingId(Long offeringId); List syncBackups(Long zoneId, Long vmId, List externalBackups); BackupVO getBackupVO(Backup backup); - + List listByOfferingId(Long backupOfferingId); BackupResponse newBackupResponse(Backup backup); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupDaoImpl.java index 8628fe8e01b..5a9cd062037 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupDaoImpl.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.backup.dao; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import javax.annotation.PostConstruct; import javax.inject.Inject; @@ -68,6 +69,8 @@ public class BackupDaoImpl extends GenericDaoBase implements Bac backupSearch = createSearchBuilder(); backupSearch.and("vm_id", backupSearch.entity().getVmId(), SearchCriteria.Op.EQ); backupSearch.and("external_id", backupSearch.entity().getExternalId(), SearchCriteria.Op.EQ); + backupSearch.and("backup_offering_id", backupSearch.entity().getBackupOfferingId(), SearchCriteria.Op.EQ); + backupSearch.and("zone_id", backupSearch.entity().getZoneId(), SearchCriteria.Op.EQ); backupSearch.done(); } @@ -102,13 +105,6 @@ public class BackupDaoImpl extends GenericDaoBase implements Bac return new ArrayList<>(listBy(sc)); } - @Override - public List listByOfferingId(Long offeringId) { - SearchCriteria sc = backupSearch.create(); - sc.setParameters("offering_id", offeringId); - return new ArrayList<>(listBy(sc)); - } - private Backup findByExternalId(Long zoneId, String externalId) { SearchCriteria sc = backupSearch.create(); sc.setParameters("external_id", externalId); @@ -123,6 +119,13 @@ public class BackupDaoImpl extends GenericDaoBase implements Bac return backupVO; } + @Override + public List listByOfferingId(Long backupOfferingId) { + SearchCriteria sc = backupSearch.create(); + sc.setParameters("backup_offering_id", backupOfferingId); + return new ArrayList<>(listBy(sc)); + } + public void removeExistingBackups(Long zoneId, Long vmId) { SearchCriteria sc = backupSearch.create(); sc.setParameters("vm_id", vmId); @@ -145,9 +148,9 @@ public class BackupDaoImpl extends GenericDaoBase implements Bac AccountVO account = accountDao.findByIdIncludingRemoved(vm.getAccountId()); DomainVO domain = domainDao.findByIdIncludingRemoved(vm.getDomainId()); DataCenterVO zone = dataCenterDao.findByIdIncludingRemoved(vm.getDataCenterId()); - Long offeringId = vm.getBackupOfferingId(); + Long offeringId = backup.getBackupOfferingId(); if (offeringId == null) { - offeringId = backup.getBackupOfferingId(); + offeringId = vm.getBackupOfferingId(); } BackupOffering offering = backupOfferingDao.findByIdIncludingRemoved(offeringId); @@ -161,7 +164,14 @@ public class BackupDaoImpl extends GenericDaoBase implements Bac response.setSize(backup.getSize()); response.setProtectedSize(backup.getProtectedSize()); response.setStatus(backup.getStatus()); - response.setVolumes(new Gson().toJson(vm.getBackupVolumeList().toArray(), Backup.VolumeInfo[].class)); + // ACS 4.20: For backups taken prior this release the backup.backed_volumes column would be empty hence use vm_instance.backup_volumes + String backedUpVolumes; + if (Objects.isNull(backup.getBackedUpVolumes())) { + backedUpVolumes = new Gson().toJson(vm.getBackupVolumeList().toArray(), Backup.VolumeInfo[].class); + } else { + backedUpVolumes = new Gson().toJson(backup.getBackedUpVolumes().toArray(), Backup.VolumeInfo[].class); + } + response.setVolumes(backedUpVolumes); response.setBackupOfferingId(offering.getUuid()); response.setBackupOffering(offering.getName()); response.setAccountId(account.getUuid()); diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupRepositoryDao.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupRepositoryDao.java new file mode 100644 index 00000000000..0034bfb30ab --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupRepositoryDao.java @@ -0,0 +1,31 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.backup.dao; + +import java.util.List; + +import org.apache.cloudstack.backup.BackupRepository; +import org.apache.cloudstack.backup.BackupRepositoryVO; + +import com.cloud.utils.db.GenericDao; + +public interface BackupRepositoryDao extends GenericDao { + List listByZoneAndProvider(Long zoneId, String provider); + + BackupRepository findByBackupOfferingId(Long backupOfferingId); +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupRepositoryDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupRepositoryDaoImpl.java new file mode 100644 index 00000000000..460b6d8aba4 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupRepositoryDaoImpl.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.backup.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.inject.Inject; + +import org.apache.cloudstack.backup.BackupOfferingVO; +import org.apache.cloudstack.backup.BackupRepository; +import org.apache.cloudstack.backup.BackupRepositoryVO; + +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +public class BackupRepositoryDaoImpl extends GenericDaoBase implements BackupRepositoryDao { + @Inject + BackupOfferingDao backupOfferingDao; + + private SearchBuilder backupRepoSearch; + + public BackupRepositoryDaoImpl() { + } + + @PostConstruct + protected void init() { + backupRepoSearch = createSearchBuilder(); + backupRepoSearch.and("zone_id", backupRepoSearch.entity().getZoneId(), SearchCriteria.Op.EQ); + backupRepoSearch.and("provider", backupRepoSearch.entity().getProvider(), SearchCriteria.Op.EQ); + backupRepoSearch.done(); + } + + @Override + public List listByZoneAndProvider(Long zoneId, String provider) { + SearchCriteria sc = backupRepoSearch.create(); + sc.setParameters("zone_id", zoneId); + sc.setParameters("provider", provider); + return new ArrayList<>(listBy(sc)); + } + + @Override + public BackupRepository findByBackupOfferingId(Long backupOfferingId) { + BackupOfferingVO offering = backupOfferingDao.findByIdIncludingRemoved(backupOfferingId); + if (offering == null) { + return null; + } + return findByUuid(offering.getExternalId()); + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupScheduleDao.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupScheduleDao.java index 516b0112c98..ee1783a9c89 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupScheduleDao.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupScheduleDao.java @@ -20,6 +20,7 @@ package org.apache.cloudstack.backup.dao; import java.util.Date; import java.util.List; +import com.cloud.utils.DateUtil; import org.apache.cloudstack.api.response.BackupScheduleResponse; import org.apache.cloudstack.backup.BackupSchedule; import org.apache.cloudstack.backup.BackupScheduleVO; @@ -29,6 +30,10 @@ import com.cloud.utils.db.GenericDao; public interface BackupScheduleDao extends GenericDao { BackupScheduleVO findByVM(Long vmId); + List listByVM(Long vmId); + + BackupScheduleVO findByVMAndIntervalType(Long vmId, DateUtil.IntervalType intervalType); + List getSchedulesToExecute(Date currentTimestamp); BackupScheduleResponse newBackupScheduleResponse(BackupSchedule schedule); diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupScheduleDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupScheduleDaoImpl.java index 7a58679e7e5..e00ccc5abd7 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupScheduleDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupScheduleDaoImpl.java @@ -23,6 +23,7 @@ import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; +import com.cloud.utils.DateUtil; import org.apache.cloudstack.api.response.BackupScheduleResponse; import org.apache.cloudstack.backup.BackupSchedule; import org.apache.cloudstack.backup.BackupScheduleVO; @@ -49,6 +50,7 @@ public class BackupScheduleDaoImpl extends GenericDaoBase listByVM(Long vmId) { + SearchCriteria sc = backupScheduleSearch.create(); + sc.setParameters("vm_id", vmId); + return listBy(sc, null); + } + + @Override + public BackupScheduleVO findByVMAndIntervalType(Long vmId, DateUtil.IntervalType intervalType) { + SearchCriteria sc = backupScheduleSearch.create(); + sc.setParameters("vm_id", vmId); + sc.setParameters("interval_type", intervalType.ordinal()); + return findOneBy(sc); + } + @Override public List getSchedulesToExecute(Date currentTimestamp) { SearchCriteria sc = executableSchedulesSearch.create(); diff --git a/engine/schema/src/main/java/org/apache/cloudstack/cluster/ClusterDrsPlanMigrationVO.java b/engine/schema/src/main/java/org/apache/cloudstack/cluster/ClusterDrsPlanMigrationVO.java index eab2e555d69..6afc2e7707a 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/cluster/ClusterDrsPlanMigrationVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/cluster/ClusterDrsPlanMigrationVO.java @@ -20,6 +20,7 @@ package org.apache.cloudstack.cluster; import org.apache.cloudstack.jobs.JobInfo; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import javax.persistence.Column; import javax.persistence.Entity; @@ -66,6 +67,13 @@ public class ClusterDrsPlanMigrationVO implements ClusterDrsPlanMigration { } + @Override + public String toString() { + return String.format("ClusterDrsPlanMigration %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "planId", "vmId", "jobId")); + } + public long getId() { return id; } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/cluster/ClusterDrsPlanVO.java b/engine/schema/src/main/java/org/apache/cloudstack/cluster/ClusterDrsPlanVO.java index 0ce25ae90fe..68f7fe4b44e 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/cluster/ClusterDrsPlanVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/cluster/ClusterDrsPlanVO.java @@ -20,6 +20,7 @@ package org.apache.cloudstack.cluster; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import javax.persistence.Column; import javax.persistence.Entity; @@ -68,6 +69,13 @@ public class ClusterDrsPlanVO implements ClusterDrsPlan { uuid = UUID.randomUUID().toString(); } + @Override + public String toString() { + return String.format("ClusterDrsPlan %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "clusterId")); + } + public long getId() { return id; } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/datacenter/DataCenterIpv4GuestSubnetVO.java b/engine/schema/src/main/java/org/apache/cloudstack/datacenter/DataCenterIpv4GuestSubnetVO.java new file mode 100644 index 00000000000..828e7b39e9a --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/datacenter/DataCenterIpv4GuestSubnetVO.java @@ -0,0 +1,123 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.datacenter; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name = "dc_ip4_guest_subnets") +public class DataCenterIpv4GuestSubnetVO implements DataCenterIpv4GuestSubnet { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "uuid") + String uuid; + + @Column(name = "data_center_id") + private long dataCenterId; + + @Column(name = "subnet") + private String subnet; + + @Column(name = "domain_id") + Long domainId; + + @Column(name = "account_id") + Long accountId; + + @Column(name = GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name= GenericDao.REMOVED_COLUMN) + private Date removed; + + public DataCenterIpv4GuestSubnetVO(long dcId, String subnet) { + this(); + this.dataCenterId = dcId; + this.subnet = subnet; + this.created = new Date(); + } + + protected DataCenterIpv4GuestSubnetVO() { + this.uuid = UUID.randomUUID().toString(); + } + + @Override + public long getId() { + return id; + } + + @Override + public String getUuid() { + return uuid; + } + + @Override + public Long getDataCenterId() { + return dataCenterId; + } + + public void setDataCenterId(long dcId) { + this.dataCenterId = dcId; + } + + public String getSubnet() { + return subnet; + } + + public void setSubnet(String subnet) { + this.subnet = subnet; + } + + @Override + public Long getDomainId() { + return domainId; + } + + public void setDomainId(Long domainId) { + this.domainId = domainId; + } + + @Override + public Long getAccountId() { + return accountId; + } + + public void setAccountId(Long accountId) { + this.accountId = accountId; + } + + @Override + public Date getCreated() { + return created; + } + + +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/datacenter/dao/DataCenterIpv4GuestSubnetDao.java b/engine/schema/src/main/java/org/apache/cloudstack/datacenter/dao/DataCenterIpv4GuestSubnetDao.java new file mode 100644 index 00000000000..e231b267fda --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/datacenter/dao/DataCenterIpv4GuestSubnetDao.java @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.datacenter.dao; + +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnetVO; + +import java.util.List; + +public interface DataCenterIpv4GuestSubnetDao extends GenericDao { + + List listByDataCenterId(long dcId); + List listByDataCenterIdAndAccountId(long dcId, long accountId); + List listByDataCenterIdAndDomainId(long dcId, long domainId); + List listNonDedicatedByDataCenterId(long dcId); + List listByAccountId(long accountId); + List listByDomainId(long domainId); +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/datacenter/dao/DataCenterIpv4GuestSubnetDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/datacenter/dao/DataCenterIpv4GuestSubnetDaoImpl.java new file mode 100644 index 00000000000..49e8a6ef662 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/datacenter/dao/DataCenterIpv4GuestSubnetDaoImpl.java @@ -0,0 +1,83 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.datacenter.dao; + +import java.util.List; + +import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnetVO; +import org.springframework.stereotype.Component; + +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.QueryBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Component +@DB +public class DataCenterIpv4GuestSubnetDaoImpl extends GenericDaoBase implements DataCenterIpv4GuestSubnetDao { + + public DataCenterIpv4GuestSubnetDaoImpl() { + } + + @Override + public List listByDataCenterId(long dcId) { + QueryBuilder sc = QueryBuilder.create(DataCenterIpv4GuestSubnetVO.class); + sc.and(sc.entity().getDataCenterId(), SearchCriteria.Op.EQ, dcId); + return sc.list(); + } + + @Override + public List listByDataCenterIdAndAccountId(long dcId, long accountId) { + QueryBuilder sc = QueryBuilder.create(DataCenterIpv4GuestSubnetVO.class); + sc.and(sc.entity().getDataCenterId(), SearchCriteria.Op.EQ, dcId); + sc.and(sc.entity().getAccountId(), SearchCriteria.Op.EQ, accountId); + return sc.list(); + } + + @Override + public List listByDataCenterIdAndDomainId(long dcId, long domainId) { + QueryBuilder sc = QueryBuilder.create(DataCenterIpv4GuestSubnetVO.class); + sc.and(sc.entity().getDataCenterId(), SearchCriteria.Op.EQ, dcId); + sc.and(sc.entity().getDomainId(), SearchCriteria.Op.EQ, domainId); + sc.and(sc.entity().getAccountId(), SearchCriteria.Op.NULL); + return sc.list(); + } + + @Override + public List listNonDedicatedByDataCenterId(long dcId) { + QueryBuilder sc = QueryBuilder.create(DataCenterIpv4GuestSubnetVO.class); + sc.and(sc.entity().getDataCenterId(), SearchCriteria.Op.EQ, dcId); + sc.and(sc.entity().getDomainId(), SearchCriteria.Op.NULL); + sc.and(sc.entity().getAccountId(), SearchCriteria.Op.NULL); + return sc.list(); + } + + @Override + public List listByAccountId(long accountId) { + QueryBuilder sc = QueryBuilder.create(DataCenterIpv4GuestSubnetVO.class); + sc.and(sc.entity().getAccountId(), SearchCriteria.Op.EQ, accountId); + return sc.list(); + } + + @Override + public List listByDomainId(long domainId) { + QueryBuilder sc = QueryBuilder.create(DataCenterIpv4GuestSubnetVO.class); + sc.and(sc.entity().getDomainId(), SearchCriteria.Op.EQ, domainId); + return sc.list(); + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/direct/download/DirectDownloadCertificateVO.java b/engine/schema/src/main/java/org/apache/cloudstack/direct/download/DirectDownloadCertificateVO.java index 1e43e164ba4..3c35f59659f 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/direct/download/DirectDownloadCertificateVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/direct/download/DirectDownloadCertificateVO.java @@ -17,8 +17,11 @@ package org.apache.cloudstack.direct.download; import com.cloud.hypervisor.Hypervisor; +import org.apache.cloudstack.util.HypervisorTypeConverter; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; @@ -45,6 +48,7 @@ public class DirectDownloadCertificateVO implements DirectDownloadCertificate { private String certificate; @Column(name = "hypervisor_type") + @Convert(converter = HypervisorTypeConverter.class) private Hypervisor.HypervisorType hypervisorType; @Column(name = "zone_id") @@ -54,6 +58,13 @@ public class DirectDownloadCertificateVO implements DirectDownloadCertificate { this.uuid = UUID.randomUUID().toString(); } + @Override + public String toString() { + return String.format("DirectDownloadCertificate %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "alias")); + } + public void setId(Long id) { this.id = id; } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java b/engine/schema/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java index 4b96dd1641a..917f8bb800a 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/engine/cloud/entity/api/db/VMEntityVO.java @@ -24,6 +24,7 @@ import java.util.Map; import java.util.UUID; import javax.persistence.Column; +import javax.persistence.Convert; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.Entity; @@ -48,6 +49,8 @@ import com.cloud.utils.fsm.FiniteStateObject; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; import com.google.gson.Gson; +import org.apache.cloudstack.util.HypervisorTypeConverter; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "vm_instance") @@ -146,7 +149,7 @@ public class VMEntityVO implements VirtualMachine, FiniteStateObject implements VMEntityDao { - public static final Logger s_logger = Logger.getLogger(VMEntityDaoImpl.class); @Inject protected VMReservationDao _vmReservationDao; diff --git a/engine/schema/src/main/java/org/apache/cloudstack/ha/dao/HAConfigDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/ha/dao/HAConfigDaoImpl.java index 4d74e2e6656..1a27bb1de67 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/ha/dao/HAConfigDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/ha/dao/HAConfigDaoImpl.java @@ -31,7 +31,6 @@ import com.cloud.utils.db.UpdateBuilder; import org.apache.cloudstack.ha.HAConfig; import org.apache.cloudstack.ha.HAConfigVO; import org.apache.cloudstack.ha.HAResource; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import java.sql.PreparedStatement; @@ -42,7 +41,6 @@ import java.util.List; @DB @Component public class HAConfigDaoImpl extends GenericDaoBase implements HAConfigDao { - private static final Logger LOG = Logger.getLogger(HAConfigDaoImpl.class); private static final String EXPIRE_OWNERSHIP = "UPDATE ha_config set mgmt_server_id=NULL where mgmt_server_id=?"; @@ -77,8 +75,8 @@ public class HAConfigDaoImpl extends GenericDaoBase implements public boolean updateState(HAConfig.HAState currentState, HAConfig.Event event, HAConfig.HAState nextState, HAConfig vo, Object data) { HAConfigVO haConfig = (HAConfigVO) vo; if (haConfig == null) { - if (LOG.isTraceEnabled()) { - LOG.trace("Invalid ha config view object provided"); + if (logger.isTraceEnabled()) { + logger.trace("Invalid ha config view object provided"); } return false; } @@ -104,8 +102,8 @@ public class HAConfigDaoImpl extends GenericDaoBase implements ub.set(haConfig, MsIdAttr, newManagementServerId); int result = update(ub, sc, null); - if (LOG.isTraceEnabled() && result <= 0) { - LOG.trace(String.format("Failed to update HA state from:%s to:%s due to event:%s for the ha_config id:%d", currentState, nextState, event, haConfig.getId())); + if (logger.isTraceEnabled() && result <= 0) { + logger.trace(String.format("Failed to update HA state from:%s to:%s due to event:%s for the ha_config id:%d", currentState, nextState, event, haConfig.getId())); } return result > 0; } @@ -141,7 +139,7 @@ public class HAConfigDaoImpl extends GenericDaoBase implements pstmt.executeUpdate(); } catch (SQLException e) { txn.rollback(); - LOG.warn("Failed to expire HA ownership of management server id: " + serverId); + logger.warn("Failed to expire HA ownership of management server id: " + serverId); } } }); diff --git a/engine/schema/src/main/java/org/apache/cloudstack/lb/ApplicationLoadBalancerRuleVO.java b/engine/schema/src/main/java/org/apache/cloudstack/lb/ApplicationLoadBalancerRuleVO.java index d8ee8631b0b..4fec96067a3 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/lb/ApplicationLoadBalancerRuleVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/lb/ApplicationLoadBalancerRuleVO.java @@ -30,6 +30,7 @@ import org.apache.cloudstack.network.lb.ApplicationLoadBalancerRule; import com.cloud.network.rules.FirewallRuleVO; import com.cloud.utils.net.Ip; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; /** * This VO represent Internal Load Balancer rule. @@ -90,6 +91,13 @@ public class ApplicationLoadBalancerRuleVO extends FirewallRuleVO implements App this.scheme = scheme; } + @Override + public String toString() { + return String.format("ApplicationLoadBalancerRule %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "purpose", "state")); + } + @Override public Long getSourceIpNetworkId() { return sourceIpNetworkId; diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/BgpPeerDetailsVO.java b/engine/schema/src/main/java/org/apache/cloudstack/network/BgpPeerDetailsVO.java new file mode 100644 index 00000000000..9e337887011 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/BgpPeerDetailsVO.java @@ -0,0 +1,103 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.network; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.ResourceDetail; + +@Entity +@Table(name = "bgp_peer_details") +public class BgpPeerDetailsVO implements ResourceDetail { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "bgp_peer_id") + private long resourceId; + + @Enumerated(value = EnumType.STRING) + @Column(name = "name") + private BgpPeer.Detail name; + + @Column(name = "value", length = 1024) + private String value; + + @Column(name = "display") + private boolean display; + + public BgpPeerDetailsVO() { + } + + public BgpPeerDetailsVO(long resourceId, BgpPeer.Detail detailName, String value, boolean display) { + this.resourceId = resourceId; + this.name = detailName; + this.value = value; + this.display = display; + } + + @Override + public long getId() { + return id; + } + + @Override + public long getResourceId() { + return resourceId; + } + + public void setResourceId(long resourceId) { + this.resourceId = resourceId; + } + + public String getName() { + return name.name(); + } + + public BgpPeer.Detail getDetailName() { + return name; + } + + public String getValue() { + return value; + } + + @Override + public boolean isDisplay() { + return display; + } + + public void setId(long id) { + this.id = id; + } + + public void setName(BgpPeer.Detail name) { + this.name = name; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/BgpPeerNetworkMapVO.java b/engine/schema/src/main/java/org/apache/cloudstack/network/BgpPeerNetworkMapVO.java new file mode 100644 index 00000000000..b520ecd5cd1 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/BgpPeerNetworkMapVO.java @@ -0,0 +1,104 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.network; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; + +import java.util.Date; + +@Entity +@Table(name = "bgp_peer_network_map") +public class BgpPeerNetworkMapVO implements InternalIdentity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "bgp_peer_id") + private long bgpPeerId; + + @Column(name = "network_id") + private Long networkId; + + @Column(name = "vpc_id") + private Long vpcId; + + @Column(name = "state") + private BgpPeer.State state; + + @Column(name = GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name= GenericDao.REMOVED_COLUMN) + private Date removed; + + /** + * There should never be a public constructor for this class. Since it's + * only here to define the table for the DAO class. + */ + protected BgpPeerNetworkMapVO() { + } + + public BgpPeerNetworkMapVO(long bgpPeerId, Long networkId, Long vpcId, BgpPeer.State state) { + this.bgpPeerId = bgpPeerId; + this.networkId = networkId; + this.vpcId = vpcId; + this.state = state; + } + + @Override + public long getId() { + return id; + } + + public long getBgpPeerId() { + return bgpPeerId; + } + + public Long getNetworkId() { + return networkId; + } + + public Long getVpcId() { + return vpcId; + } + + public BgpPeer.State getState() { + return state; + } + + public void setState(BgpPeer.State state) { + this.state = state; + } + + public Date getCreated() { + return created; + } + + public Date getRemoved() { + return removed; + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/BgpPeerVO.java b/engine/schema/src/main/java/org/apache/cloudstack/network/BgpPeerVO.java new file mode 100644 index 00000000000..c60a3ec3868 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/BgpPeerVO.java @@ -0,0 +1,173 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.network; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; + +@Entity +@Table(name = "bgp_peers") +public class BgpPeerVO implements BgpPeer { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + long id; + + @Column(name = "uuid") + private String uuid; + + @Column(name = "data_center_id") + private long dataCenterId; + + @Column(name = "ip4_address") + private String ip4Address; + + @Column(name = "ip6_address") + private String ip6Address; + + @Column(name = "as_number") + private Long asNumber; + + @Column(name = "password") + private String password; + + @Column(name = "domain_id") + Long domainId; + + @Column(name = "account_id") + Long accountId; + + @Column(name = GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name= GenericDao.REMOVED_COLUMN) + private Date removed; + + protected BgpPeerVO() { + uuid = UUID.randomUUID().toString(); + } + + public BgpPeerVO(long dcId, String ip4Address, String ip6Address, Long asNumber, String password) { + this(); + this.dataCenterId = dcId; + this.ip4Address = ip4Address; + this.ip6Address = ip6Address; + this.asNumber = asNumber; + this.password = password; + } + + @Override + public String toString() { + return String.format("BgpPeer %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "asNumber", "ip4Address", "ip6Address")); + } + + @Override + public long getId() { + return id; + } + + @Override + public String getUuid() { + return uuid; + } + + @Override + public long getDataCenterId() { + return dataCenterId; + } + + public void setDataCenterId(long dataCenterId) { + this.dataCenterId = dataCenterId; + } + + @Override + public String getIp4Address() { + return ip4Address; + } + + public void setIp4Address(String ip4Address) { + this.ip4Address = ip4Address; + } + + @Override + public String getIp6Address() { + return ip6Address; + } + + public void setIp6Address(String ip6Address) { + this.ip6Address = ip6Address; + } + + @Override + public Long getAsNumber() { + return asNumber; + } + + public void setAsNumber(Long asNumber) { + this.asNumber = asNumber; + } + + @Override + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public Long getDomainId() { + return domainId; + } + + public void setDomainId(Long domainId) { + this.domainId = domainId; + } + + @Override + public Long getAccountId() { + return accountId; + } + + public void setAccountId(Long accountId) { + this.accountId = accountId; + } + + @Override + public Date getCreated() { + return created; + } + + public Date getRemoved() { + return removed; + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/Ipv4GuestSubnetNetworkMapVO.java b/engine/schema/src/main/java/org/apache/cloudstack/network/Ipv4GuestSubnetNetworkMapVO.java new file mode 100644 index 00000000000..cc726ba3d35 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/Ipv4GuestSubnetNetworkMapVO.java @@ -0,0 +1,143 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.network; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name = "ip4_guest_subnet_network_map") +public class Ipv4GuestSubnetNetworkMapVO implements Ipv4GuestSubnetNetworkMap { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + long id; + + @Column(name = "uuid") + private String uuid; + + @Column(name = "parent_id") + private Long parentId; + + @Column(name = "subnet") + private String subnet; + + @Column(name = "vpc_id") + private Long vpcId; + + @Column(name = "network_id") + private Long networkId; + + @Column(name = "state") + private State state; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "allocated") + Date allocated; + + @Column(name = GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name= GenericDao.REMOVED_COLUMN) + private Date removed; + + protected Ipv4GuestSubnetNetworkMapVO() { + uuid = UUID.randomUUID().toString(); + } + + protected Ipv4GuestSubnetNetworkMapVO(Long parentId, String subnet, Long networkId, Ipv4GuestSubnetNetworkMap.State state) { + this.parentId = parentId; + this.subnet = subnet; + this.networkId = networkId; + this.state = state; + uuid = UUID.randomUUID().toString(); + } + + @Override + public long getId() { + return id; + } + + @Override + public String getUuid() { + return uuid; + } + + @Override + public Long getParentId() { + return parentId; + } + + @Override + public String getSubnet() { + return subnet; + } + + @Override + public Long getVpcId() { + return vpcId; + } + + public void setVpcId(Long vpcId) { + this.vpcId = vpcId; + } + + @Override + public Long getNetworkId() { + return networkId; + } + + public void setNetworkId(Long networkId) { + this.networkId = networkId; + } + + @Override + public State getState() { + return state; + } + + public void setState(Ipv4GuestSubnetNetworkMap.State state) { + this.state = state; + } + + public void setAllocated(Date allocated) { + this.allocated = allocated; + } + + @Override + public Date getAllocated() { + return allocated; + } + + @Override + public Date getCreated() { + return created; + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDao.java b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDao.java new file mode 100644 index 00000000000..8ca4c2d86da --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDao.java @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.network.dao; + +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.BgpPeerVO; + +import java.util.List; +import java.util.Map; + +public interface BgpPeerDao extends GenericDao { + List listNonRevokeByNetworkId(long networkId); + + List listNonRevokeByVpcId(long vpcId); + + BgpPeerVO findByZoneAndAsNumberAndAddress(long zoneId, Long asNumber, String ip4Address, String ip6Address); + + BgpPeerVO persist(BgpPeerVO bgpPeerVO, Map details); + + List listAvailableBgpPeerIdsForAccount(long zoneId, long domainId, long accountId, boolean useSystemBgpPeers); + + int removeByAccountId(long accountId); + int removeByDomainId(long domainId); +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDaoImpl.java new file mode 100644 index 00000000000..0f95f7c3cd5 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDaoImpl.java @@ -0,0 +1,193 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.network.dao; + +import com.cloud.utils.db.DB; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.JoinBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +import com.cloud.utils.db.TransactionLegacy; +import com.cloud.utils.exception.CloudRuntimeException; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.BgpPeerDetailsVO; +import org.apache.cloudstack.network.BgpPeerNetworkMapVO; +import org.apache.cloudstack.network.BgpPeerVO; +import org.apache.commons.collections.CollectionUtils; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.inject.Inject; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Component +@DB +public class BgpPeerDaoImpl extends GenericDaoBase implements BgpPeerDao { + protected SearchBuilder NetworkIdSearch; + protected SearchBuilder VpcIdSearch; + protected SearchBuilder AllFieldsSearch; + + private static final String LIST_ALL_BGP_PEERS_IDS_FOR_ACCOUNT = "SELECT id FROM `cloud`.`bgp_peers` WHERE removed IS NULL AND data_center_id = ? " + + "AND ((domain_id IS NULL AND account_id IS NULL) " + + "OR (domain_id = ? AND account_id IS NULL) " + + "OR (domain_id = ? AND account_id = ?))"; + + private static final String LIST_DEDICATED_BGP_PEERS_IDS_FOR_ACCOUNT = "SELECT id FROM `cloud`.`bgp_peers` WHERE removed IS NULL AND data_center_id = ? " + + "AND ((domain_id = ? AND account_id IS NULL) " + + "OR (domain_id = ? AND account_id = ?))"; + + @Inject + BgpPeerNetworkMapDao bgpPeerNetworkMapDao; + @Inject + BgpPeerDetailsDao bgpPeerDetailsDao; + + @PostConstruct + public void init() { + final SearchBuilder networkSearchBuilder = bgpPeerNetworkMapDao.createSearchBuilder(); + networkSearchBuilder.and("networkId", networkSearchBuilder.entity().getNetworkId(), SearchCriteria.Op.EQ); + networkSearchBuilder.and("state", networkSearchBuilder.entity().getState(), SearchCriteria.Op.IN); + networkSearchBuilder.and("removed", networkSearchBuilder.entity().getRemoved(), SearchCriteria.Op.NULL); + NetworkIdSearch = createSearchBuilder(); + NetworkIdSearch.join("network", networkSearchBuilder, networkSearchBuilder.entity().getBgpPeerId(), + NetworkIdSearch.entity().getId(), JoinBuilder.JoinType.INNER); + NetworkIdSearch.done(); + + final SearchBuilder vpcSearchBuilder = bgpPeerNetworkMapDao.createSearchBuilder(); + vpcSearchBuilder.and("vpcId", vpcSearchBuilder.entity().getVpcId(), SearchCriteria.Op.EQ); + vpcSearchBuilder.and("state", vpcSearchBuilder.entity().getState(), SearchCriteria.Op.IN); + vpcSearchBuilder.and("removed", vpcSearchBuilder.entity().getRemoved(), SearchCriteria.Op.NULL); + VpcIdSearch = createSearchBuilder(); + VpcIdSearch.join("vpc", vpcSearchBuilder, vpcSearchBuilder.entity().getBgpPeerId(), + VpcIdSearch.entity().getId(), JoinBuilder.JoinType.INNER); + VpcIdSearch.done(); + + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("zoneId", AllFieldsSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("domainId", AllFieldsSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("asNumber", AllFieldsSearch.entity().getAsNumber(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("ip4Address", AllFieldsSearch.entity().getIp4Address(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("ip6Address", AllFieldsSearch.entity().getIp6Address(), SearchCriteria.Op.EQ); + AllFieldsSearch.done(); + } + + @Override + public List listNonRevokeByNetworkId(long networkId) { + SearchCriteria sc = NetworkIdSearch.create(); + sc.setJoinParameters("network", "networkId", networkId); + sc.setJoinParameters("network", "state", BgpPeer.State.Active, BgpPeer.State.Add); + return listBy(sc); + } + + @Override + public List listNonRevokeByVpcId(long vpcId) { + SearchCriteria sc = VpcIdSearch.create(); + sc.setJoinParameters("vpc", "vpcId", vpcId); + sc.setJoinParameters("vpc", "state", BgpPeer.State.Active, BgpPeer.State.Add); + return listBy(sc); + } + + @Override + public BgpPeerVO findByZoneAndAsNumberAndAddress(long zoneId, Long asNumber, String ip4Address, String ip6Address) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters( "zoneId", zoneId); + sc.setParameters( "asNumber", asNumber); + if (ip4Address != null) { + sc.setParameters( "ip4Address", ip4Address); + } + if (ip6Address != null) { + sc.setParameters( "ip6Address", ip6Address); + } + return findOneBy(sc); + } + + @Override + public BgpPeerVO persist(BgpPeerVO bgpPeerVO, Map details) { + TransactionLegacy txn = TransactionLegacy.currentTxn(); + txn.start(); + BgpPeerVO vo = super.persist(bgpPeerVO); + + // persist the details + if (details != null && !details.isEmpty()) { + for (BgpPeer.Detail detail : details.keySet()) { + bgpPeerDetailsDao.persist(new BgpPeerDetailsVO(bgpPeerVO.getId(), detail, details.get(detail), true)); + } + } + + txn.commit(); + return vo; + } + + @Override + public List listAvailableBgpPeerIdsForAccount(long zoneId, long domainId, long accountId, boolean useSystemBgpPeers) { + if (useSystemBgpPeers) { + return listBgpPeerIdsForAccount(zoneId, domainId, accountId, false); + } else { + List dedicatedBgpPeerIds = listBgpPeerIdsForAccount(zoneId, domainId, accountId, true); + if (CollectionUtils.isNotEmpty(dedicatedBgpPeerIds)) { + return dedicatedBgpPeerIds; + } + return listBgpPeerIdsForAccount(zoneId, domainId, accountId, false); + } + } + + private List listBgpPeerIdsForAccount(long zoneId, long domainId, long accountId, boolean isDedicated) { + TransactionLegacy txn = TransactionLegacy.currentTxn(); + PreparedStatement pstmt = null; + List result = new ArrayList(); + + StringBuilder sql = isDedicated ? new StringBuilder(LIST_DEDICATED_BGP_PEERS_IDS_FOR_ACCOUNT): new StringBuilder(LIST_ALL_BGP_PEERS_IDS_FOR_ACCOUNT); + + try { + pstmt = txn.prepareAutoCloseStatement(sql.toString()); + pstmt.setLong(1, zoneId); + pstmt.setLong(2, domainId); + pstmt.setLong(3, domainId); + pstmt.setLong(4, accountId); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) { + result.add(rs.getLong(1)); + } + return result; + } catch (SQLException e) { + throw new CloudRuntimeException("DB Exception on: " + sql, e); + } catch (Throwable e) { + throw new CloudRuntimeException("Caught: " + sql, e); + } + } + + @Override + public int removeByAccountId(long accountId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); + return remove(sc); + } + + @Override + public int removeByDomainId(long domainId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); + return remove(sc); + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDetailsDao.java b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDetailsDao.java new file mode 100644 index 00000000000..377bc45ebfe --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDetailsDao.java @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.network.dao; + +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.BgpPeerDetailsVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDao; + +import java.util.List; +import java.util.Map; + +public interface BgpPeerDetailsDao extends ResourceDetailsDao { + Map getBgpPeerDetails(long bgpPeerId); + String getDetail(long offeringId, BgpPeer.Detail detailName); + List findDomainIds(final long resourceId); + List findZoneIds(final long resourceId); + + int removeByBgpPeerId(long bgpPeerId); +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDetailsDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDetailsDaoImpl.java new file mode 100644 index 00000000000..a974cf5e276 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerDetailsDaoImpl.java @@ -0,0 +1,123 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.network.dao; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.cloudstack.api.ApiConstants; + +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Func; +import com.cloud.utils.db.SearchCriteria.Op; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.BgpPeerDetailsVO; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; +import org.apache.commons.lang3.EnumUtils; + +public class BgpPeerDetailsDaoImpl extends ResourceDetailsDaoBase implements BgpPeerDetailsDao { + protected final SearchBuilder DetailSearch; + private final GenericSearchBuilder ValueSearch; + + public BgpPeerDetailsDaoImpl() { + + DetailSearch = createSearchBuilder(); + DetailSearch.and("resourceId", DetailSearch.entity().getResourceId(), SearchCriteria.Op.EQ); + DetailSearch.and("name", DetailSearch.entity().getName(), SearchCriteria.Op.EQ); + DetailSearch.and("value", DetailSearch.entity().getValue(), SearchCriteria.Op.EQ); + DetailSearch.and("display", DetailSearch.entity().isDisplay(), SearchCriteria.Op.EQ); + DetailSearch.done(); + + ValueSearch = createSearchBuilder(String.class); + ValueSearch.select(null, Func.DISTINCT, ValueSearch.entity().getValue()); + ValueSearch.and("resourceId", ValueSearch.entity().getResourceId(), SearchCriteria.Op.EQ); + ValueSearch.and("name", ValueSearch.entity().getName(), Op.EQ); + ValueSearch.and("display", ValueSearch.entity().isDisplay(), SearchCriteria.Op.EQ); + ValueSearch.done(); + } + + @Override + public Map getBgpPeerDetails(long bgpPeerId) { + SearchCriteria sc = DetailSearch.create(); + sc.setParameters("resourceId", bgpPeerId); + sc.setParameters("display", true); + + List results = search(sc, null); + if (results.size() == 0) { + return null; + } + Map details = new HashMap<>(results.size()); + for (BgpPeerDetailsVO result : results) { + details.put(result.getDetailName(), result.getValue()); + } + + return details; + } + + @Override + public String getDetail(long bgpPeerId, BgpPeer.Detail detailName) { + SearchCriteria sc = ValueSearch.create(); + sc.setParameters("name", detailName); + sc.setParameters("resourceId", bgpPeerId); + List results = customSearch(sc, null); + if (results.isEmpty()) { + return null; + } else { + return results.get(0); + } + } + + @Override + public void addDetail(long resourceId, String key, String value, boolean display) { + persist(new BgpPeerDetailsVO(resourceId, EnumUtils.getEnumIgnoreCase(BgpPeer.Detail.class, key), value, display)); + } + + @Override + public List findDomainIds(long resourceId) { + final List domainIds = new ArrayList<>(); + for (final BgpPeerDetailsVO detail: findDetails(resourceId, ApiConstants.DOMAIN_ID)) { + final Long domainId = Long.valueOf(detail.getValue()); + if (domainId > 0) { + domainIds.add(domainId); + } + } + return domainIds; + } + + @Override + public List findZoneIds(long resourceId) { + final List zoneIds = new ArrayList<>(); + for (final BgpPeerDetailsVO detail: findDetails(resourceId, ApiConstants.ZONE_ID)) { + final Long zoneId = Long.valueOf(detail.getValue()); + if (zoneId > 0) { + zoneIds.add(zoneId); + } + } + return zoneIds; + } + + @Override + public int removeByBgpPeerId(long bgpPeerId) { + SearchCriteria sc = DetailSearch.create(); + sc.setParameters("resourceId", bgpPeerId); + return remove(sc); + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerNetworkMapDao.java b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerNetworkMapDao.java new file mode 100644 index 00000000000..8d8ec8c998a --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerNetworkMapDao.java @@ -0,0 +1,48 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.network.dao; + +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.network.BgpPeerNetworkMapVO; + +import java.util.List; + + +public interface BgpPeerNetworkMapDao extends GenericDao { + + void persistForNetwork(long networkId, List bgpPeerIds); + + List listByBgpPeerId(long bgpPeerId); + + List listByNetworkId(long networkId); + + List listUsedNetworksByOtherDomains(long bgpPeerId, Long domainId); + + List listUsedNetworksByOtherAccounts(long bgpPeerId, Long accountId); + + int removeByNetworkId(long networkId); + + void persistForVpc(long vpcId, List bgpPeerIds); + + List listByVpcId(long vpcId); + + List listUsedVpcsByOtherDomains(long bgpPeerId, Long domainId); + + List listUsedVpcsByOtherAccounts(long bgpPeerId, Long accountId); + + int removeByVpcId(long vpcId); +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerNetworkMapDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerNetworkMapDaoImpl.java new file mode 100644 index 00000000000..a5e5f47684a --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/BgpPeerNetworkMapDaoImpl.java @@ -0,0 +1,185 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.network.dao; + +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.inject.Inject; + +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.network.vpc.VpcVO; +import com.cloud.network.vpc.dao.VpcDao; +import com.cloud.utils.db.JoinBuilder; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.BgpPeerNetworkMapVO; +import org.springframework.stereotype.Component; + +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.TransactionLegacy; + +@Component +public class BgpPeerNetworkMapDaoImpl extends GenericDaoBase implements BgpPeerNetworkMapDao { + + protected SearchBuilder BgpPeerNetworkVpcSearch; + protected SearchBuilder NetworkDomainAccountNeqSearch; + protected SearchBuilder VpcDomainAccountNeqSearch; + + @Inject + NetworkDao networkDao; + @Inject + VpcDao vpcDao; + + public BgpPeerNetworkMapDaoImpl() { + } + + @PostConstruct + public void init() { + BgpPeerNetworkVpcSearch = createSearchBuilder(); + BgpPeerNetworkVpcSearch.and("bgpPeerId", BgpPeerNetworkVpcSearch.entity().getBgpPeerId(), SearchCriteria.Op.EQ); + BgpPeerNetworkVpcSearch.and("networkId", BgpPeerNetworkVpcSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); + BgpPeerNetworkVpcSearch.and("vpcId", BgpPeerNetworkVpcSearch.entity().getVpcId(), SearchCriteria.Op.EQ); + BgpPeerNetworkVpcSearch.done(); + + final SearchBuilder networkSearchBuilder = networkDao.createSearchBuilder(); + networkSearchBuilder.and("domainId", networkSearchBuilder.entity().getDomainId(), SearchCriteria.Op.NEQ); + networkSearchBuilder.and("accountId", networkSearchBuilder.entity().getAccountId(), SearchCriteria.Op.NEQ); + NetworkDomainAccountNeqSearch = createSearchBuilder(); + NetworkDomainAccountNeqSearch.and("bgpPeerId", NetworkDomainAccountNeqSearch.entity().getBgpPeerId(), SearchCriteria.Op.EQ); + NetworkDomainAccountNeqSearch.join("network", networkSearchBuilder, networkSearchBuilder.entity().getId(), + NetworkDomainAccountNeqSearch.entity().getNetworkId(), JoinBuilder.JoinType.INNER); + NetworkDomainAccountNeqSearch.done(); + + final SearchBuilder vpcSearchBuilder = vpcDao.createSearchBuilder(); + vpcSearchBuilder.and("domainId", vpcSearchBuilder.entity().getDomainId(), SearchCriteria.Op.NEQ); + vpcSearchBuilder.and("accountId", vpcSearchBuilder.entity().getAccountId(), SearchCriteria.Op.NEQ); + VpcDomainAccountNeqSearch = createSearchBuilder(); + VpcDomainAccountNeqSearch.and("bgpPeerId", VpcDomainAccountNeqSearch.entity().getBgpPeerId(), SearchCriteria.Op.EQ); + VpcDomainAccountNeqSearch.join("vpc", vpcSearchBuilder, vpcSearchBuilder.entity().getId(), + VpcDomainAccountNeqSearch.entity().getVpcId(), JoinBuilder.JoinType.INNER); + VpcDomainAccountNeqSearch.done(); + } + + @Override + public void persistForNetwork(long networkId, List bgpPeerIds) { + TransactionLegacy txn = TransactionLegacy.currentTxn(); + + txn.start(); + SearchCriteria sc = BgpPeerNetworkVpcSearch.create(); + sc.setParameters("networkId", networkId); + expunge(sc); + + for (Long bgpPeerId : bgpPeerIds) { + BgpPeerNetworkMapVO vo = new BgpPeerNetworkMapVO(bgpPeerId, networkId, null, BgpPeer.State.Active); + persist(vo); + } + + txn.commit(); + } + + @Override + public List listByBgpPeerId(long bgpPeerId) { + SearchCriteria sc = BgpPeerNetworkVpcSearch.create(); + sc.setParameters("bgpPeerId", bgpPeerId); + + return search(sc, null); + } + + @Override + public List listByNetworkId(long networkId) { + SearchCriteria sc = BgpPeerNetworkVpcSearch.create(); + sc.setParameters("networkId", networkId); + + return search(sc, null); + } + + @Override + public List listUsedNetworksByOtherDomains(long bgpPeerId, Long domainId) { + SearchCriteria sc = NetworkDomainAccountNeqSearch.create(); + sc.setParameters("bgpPeerId", bgpPeerId); + sc.setJoinParameters("network", "domainId", domainId); + return listBy(sc); + } + + @Override + public List listUsedNetworksByOtherAccounts(long bgpPeerId, Long accountId) { + SearchCriteria sc = NetworkDomainAccountNeqSearch.create(); + sc.setParameters("bgpPeerId", bgpPeerId); + sc.setJoinParameters("network", "accountId", accountId); + return listBy(sc); + } + + @Override + public int removeByNetworkId(long networkId) { + SearchCriteria sc = BgpPeerNetworkVpcSearch.create(); + sc.setParameters("networkId", networkId); + + return remove(sc); + } + + @Override + public void persistForVpc(long vpcId, List bgpPeerIds) { + TransactionLegacy txn = TransactionLegacy.currentTxn(); + + txn.start(); + SearchCriteria sc = BgpPeerNetworkVpcSearch.create(); + sc.setParameters("vpcId", vpcId); + expunge(sc); + + for (Long bgpPeerId : bgpPeerIds) { + BgpPeerNetworkMapVO vo = new BgpPeerNetworkMapVO(bgpPeerId, null, vpcId, BgpPeer.State.Active); + persist(vo); + } + + txn.commit(); + } + + @Override + public List listByVpcId(long vpcId) { + SearchCriteria sc = BgpPeerNetworkVpcSearch.create(); + sc.setParameters("vpcId", vpcId); + + return search(sc, null); + } + + @Override + public List listUsedVpcsByOtherDomains(long bgpPeerId, Long domainId) { + SearchCriteria sc = VpcDomainAccountNeqSearch.create(); + sc.setParameters("bgpPeerId", bgpPeerId); + sc.setJoinParameters("vpc", "domainId", domainId); + return listBy(sc); + } + + @Override + public List listUsedVpcsByOtherAccounts(long bgpPeerId, Long accountId) { + SearchCriteria sc = VpcDomainAccountNeqSearch.create(); + sc.setParameters("bgpPeerId", bgpPeerId); + sc.setJoinParameters("vpc", "accountId", accountId); + return listBy(sc); + } + + @Override + public int removeByVpcId(long vpcId) { + SearchCriteria sc = BgpPeerNetworkVpcSearch.create(); + sc.setParameters("vpcId", vpcId); + + return remove(sc); + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/dao/Ipv4GuestSubnetNetworkMapDao.java b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/Ipv4GuestSubnetNetworkMapDao.java new file mode 100644 index 00000000000..c3f860009db --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/Ipv4GuestSubnetNetworkMapDao.java @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.network.dao; + +import java.util.List; + +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.network.Ipv4GuestSubnetNetworkMap; +import org.apache.cloudstack.network.Ipv4GuestSubnetNetworkMapVO; + +public interface Ipv4GuestSubnetNetworkMapDao extends GenericDao { + List listByParent(long parentId); + List listUsedByParent(long parentId); + List listUsedByOtherDomains(long parentId, Long domainId); + List listUsedByOtherAccounts(long parentId, Long accountId); + Ipv4GuestSubnetNetworkMapVO findFirstAvailable(long parentId, long cidrSize); + Ipv4GuestSubnetNetworkMapVO findByNetworkId(long networkId); + Ipv4GuestSubnetNetworkMapVO findByVpcId(long vpcId); + Ipv4GuestSubnetNetworkMapVO findBySubnet(String subnet); + List findSubnetsInStates(Ipv4GuestSubnetNetworkMap.State... states); + void deleteByParentId(long parentId); + List listAllNoParent(); +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/dao/Ipv4GuestSubnetNetworkMapDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/Ipv4GuestSubnetNetworkMapDaoImpl.java new file mode 100644 index 00000000000..95e53448907 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/Ipv4GuestSubnetNetworkMapDaoImpl.java @@ -0,0 +1,170 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.network.dao; + +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.inject.Inject; + +import org.apache.cloudstack.network.Ipv4GuestSubnetNetworkMap; +import org.apache.cloudstack.network.Ipv4GuestSubnetNetworkMapVO; +import org.apache.commons.collections.CollectionUtils; +import org.springframework.stereotype.Component; + +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.JoinBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Component +@DB +public class Ipv4GuestSubnetNetworkMapDaoImpl extends GenericDaoBase implements Ipv4GuestSubnetNetworkMapDao { + + protected SearchBuilder ParentStateSearch; + protected SearchBuilder ParentIdSearch; + protected SearchBuilder NoParentSearch; + protected SearchBuilder NetworkIdSearch; + protected SearchBuilder SubnetSearch; + protected SearchBuilder StatesSearch; + protected SearchBuilder DomainAccountNeqSearch; + + @Inject + NetworkDao networkDao; + + @PostConstruct + public void init() { + ParentStateSearch = createSearchBuilder(); + ParentStateSearch.and("parentId", ParentStateSearch.entity().getParentId(), SearchCriteria.Op.EQ); + ParentStateSearch.and("state", ParentStateSearch.entity().getState(), SearchCriteria.Op.IN); + ParentStateSearch.and("subnet", ParentStateSearch.entity().getSubnet(), SearchCriteria.Op.LIKE); + ParentStateSearch.done(); + ParentIdSearch = createSearchBuilder(); + ParentIdSearch.and("parentId", ParentIdSearch.entity().getParentId(), SearchCriteria.Op.EQ); + ParentIdSearch.done(); + NoParentSearch = createSearchBuilder(); + NoParentSearch.and("parentId", NoParentSearch.entity().getParentId(), SearchCriteria.Op.NULL); + NoParentSearch.done(); + NetworkIdSearch = createSearchBuilder(); + NetworkIdSearch.and("networkId", NetworkIdSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); + NetworkIdSearch.and("vpcId", NetworkIdSearch.entity().getVpcId(), SearchCriteria.Op.EQ); + NetworkIdSearch.done(); + SubnetSearch = createSearchBuilder(); + SubnetSearch.and("subnet", SubnetSearch.entity().getSubnet(), SearchCriteria.Op.EQ); + SubnetSearch.done(); + StatesSearch = createSearchBuilder(); + StatesSearch.and("state", StatesSearch.entity().getState(), SearchCriteria.Op.IN); + StatesSearch.done(); + + final SearchBuilder networkSearchBuilder = networkDao.createSearchBuilder(); + networkSearchBuilder.and("domainId", networkSearchBuilder.entity().getDomainId(), SearchCriteria.Op.NEQ); + networkSearchBuilder.and("accountId", networkSearchBuilder.entity().getAccountId(), SearchCriteria.Op.NEQ); + DomainAccountNeqSearch = createSearchBuilder(); + DomainAccountNeqSearch.and("parentId", DomainAccountNeqSearch.entity().getParentId(), SearchCriteria.Op.EQ); + DomainAccountNeqSearch.join("network", networkSearchBuilder, networkSearchBuilder.entity().getId(), + DomainAccountNeqSearch.entity().getNetworkId(), JoinBuilder.JoinType.INNER); + DomainAccountNeqSearch.done(); + } + + @Override + public List listByParent(long parentId) { + SearchCriteria sc = ParentIdSearch.create(); + sc.setParameters("parentId", parentId); + return listBy(sc, null); + } + + @Override + public List listUsedByParent(long parentId) { + SearchCriteria sc = ParentStateSearch.create(); + sc.setParameters("parentId", parentId); + sc.setParameters("state", (Object[]) new Ipv4GuestSubnetNetworkMap.State[]{Ipv4GuestSubnetNetworkMap.State.Allocated, Ipv4GuestSubnetNetworkMap.State.Allocating}); + return listBy(sc, null); + } + + @Override + public List listUsedByOtherDomains(long parentId, Long domainId) { + SearchCriteria sc = DomainAccountNeqSearch.create(); + sc.setParameters("parentId", parentId); + sc.setJoinParameters("network", "domainId", domainId); + return listBy(sc); + } + + @Override + public List listUsedByOtherAccounts(long parentId, Long accountId) { + SearchCriteria sc = DomainAccountNeqSearch.create(); + sc.setParameters("parentId", parentId); + sc.setJoinParameters("network", "accountId", accountId); + return listBy(sc); + } + + @Override + public Ipv4GuestSubnetNetworkMapVO findFirstAvailable(long parentId, long cidrSize) { + SearchCriteria sc = ParentStateSearch.create(); + sc.setParameters("parentId", parentId); + sc.setParameters("subnet", "%/" + cidrSize); + sc.setParameters("state", (Object[]) new Ipv4GuestSubnetNetworkMap.State[]{Ipv4GuestSubnetNetworkMap.State.Free}); + Filter searchFilter = new Filter(Ipv4GuestSubnetNetworkMapVO.class, "id", true, null, 1L); + List list = listBy(sc, searchFilter); + return CollectionUtils.isNotEmpty(list) ? list.get(0) : null; + } + + @Override + public Ipv4GuestSubnetNetworkMapVO findByNetworkId(long networkId) { + SearchCriteria sc = NetworkIdSearch.create(); + sc.setParameters("networkId", networkId); + return findOneBy(sc); + } + + @Override + public Ipv4GuestSubnetNetworkMapVO findByVpcId(long vpcId) { + SearchCriteria sc = NetworkIdSearch.create(); + sc.setParameters("vpcId", vpcId); + return findOneBy(sc); + } + + @Override + public Ipv4GuestSubnetNetworkMapVO findBySubnet(String subnet) { + SearchCriteria sc = SubnetSearch.create(); + sc.setParameters("subnet", subnet); + return findOneBy(sc); + } + + @Override + public List findSubnetsInStates(Ipv4GuestSubnetNetworkMap.State... states) { + SearchCriteria sc = StatesSearch.create(); + sc.setParameters("state", (Object[])states); + return listBy(sc); + } + + @Override + public void deleteByParentId(long parentId) { + SearchCriteria sc = ParentIdSearch.create(); + sc.setParameters("parentId", parentId); + remove(sc); + } + + @Override + public List listAllNoParent() { + SearchCriteria sc = NoParentSearch.create(); + return listBy(sc, null); + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/network/dao/NetworkPermissionDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/NetworkPermissionDaoImpl.java index 950daa11083..74ae02d67a2 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/network/dao/NetworkPermissionDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/network/dao/NetworkPermissionDaoImpl.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.network.dao; import java.util.ArrayList; import java.util.List; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.apache.cloudstack.network.NetworkPermissionVO; @@ -31,7 +30,6 @@ import com.cloud.utils.db.SearchCriteria; @Component public class NetworkPermissionDaoImpl extends GenericDaoBase implements NetworkPermissionDao { - private static final Logger s_logger = Logger.getLogger(NetworkPermissionDaoImpl.class); private SearchBuilder NetworkAndAccountSearch; private SearchBuilder NetworkIdSearch; @@ -82,7 +80,7 @@ public class NetworkPermissionDaoImpl extends GenericDaoBase 0) { - s_logger.debug(String.format("Removed [%s] network permission(s) for the account with Id [%s]", networkPermissionRemoved, accountId)); + logger.debug(String.format("Removed [%s] network permission(s) for the account with Id [%s]", networkPermissionRemoved, accountId)); } } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/outofbandmanagement/dao/OutOfBandManagementDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/outofbandmanagement/dao/OutOfBandManagementDaoImpl.java index af164326da7..375bb43e40e 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/outofbandmanagement/dao/OutOfBandManagementDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/outofbandmanagement/dao/OutOfBandManagementDaoImpl.java @@ -31,7 +31,6 @@ import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.db.UpdateBuilder; import org.apache.cloudstack.outofbandmanagement.OutOfBandManagement; import org.apache.cloudstack.outofbandmanagement.OutOfBandManagementVO; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import java.sql.PreparedStatement; @@ -41,7 +40,6 @@ import java.util.List; @DB @Component public class OutOfBandManagementDaoImpl extends GenericDaoBase implements OutOfBandManagementDao { - private static final Logger LOG = Logger.getLogger(OutOfBandManagementDaoImpl.class); private SearchBuilder HostSearch; private SearchBuilder ManagementServerSearch; @@ -109,7 +107,7 @@ public class OutOfBandManagementDaoImpl extends GenericDaoBase 0; } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/region/dao/RegionDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/region/dao/RegionDaoImpl.java index e2ad5d9ed23..1e53c925e08 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/region/dao/RegionDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/region/dao/RegionDaoImpl.java @@ -17,7 +17,6 @@ package org.apache.cloudstack.region.dao; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.apache.cloudstack.region.RegionVO; @@ -28,7 +27,6 @@ import com.cloud.utils.db.SearchCriteria; @Component public class RegionDaoImpl extends GenericDaoBase implements RegionDao { - private static final Logger s_logger = Logger.getLogger(RegionDaoImpl.class); protected SearchBuilder NameSearch; protected SearchBuilder AllFieldsSearch; diff --git a/engine/schema/src/main/java/org/apache/cloudstack/region/gslb/GlobalLoadBalancerRuleVO.java b/engine/schema/src/main/java/org/apache/cloudstack/region/gslb/GlobalLoadBalancerRuleVO.java index 1865b9a6783..4ce7033156f 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/region/gslb/GlobalLoadBalancerRuleVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/region/gslb/GlobalLoadBalancerRuleVO.java @@ -29,6 +29,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.region.ha.GlobalLoadBalancerRule; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "global_load_balancing_rules") @@ -92,6 +93,15 @@ public class GlobalLoadBalancerRuleVO implements GlobalLoadBalancerRule { this.state = state; } + + @Override + public String toString() { + return String.format("GlobalLoadBalancerRule %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); + } + + @Override public String getName() { return name; diff --git a/engine/schema/src/main/java/org/apache/cloudstack/reservation/ReservationVO.java b/engine/schema/src/main/java/org/apache/cloudstack/reservation/ReservationVO.java index e5636f0bfc9..df0ede6821a 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/reservation/ReservationVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/reservation/ReservationVO.java @@ -18,10 +18,6 @@ // package org.apache.cloudstack.reservation; -import com.cloud.configuration.Resource; -import org.apache.cloudstack.user.ResourceReservation; -import com.cloud.utils.exception.CloudRuntimeException; - import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -29,6 +25,15 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.user.ResourceReservation; + +import com.cloud.configuration.Resource; +import com.cloud.utils.exception.CloudRuntimeException; +import org.apache.cloudstack.utils.identity.ManagementServerNode; + +import java.util.Date; + @Entity @Table(name = "resource_reservation") public class ReservationVO implements ResourceReservation { @@ -47,20 +52,38 @@ public class ReservationVO implements ResourceReservation { @Column(name = "resource_type", nullable = false) Resource.ResourceType resourceType; + @Column(name = "tag") + String tag; + + @Column(name = "resource_id") + Long resourceId; + @Column(name = "amount") long amount; - protected ReservationVO() - {} + @Column(name = "mgmt_server_id") + Long managementServerId; - public ReservationVO(Long accountId, Long domainId, Resource.ResourceType resourceType, Long delta) { - if (delta == null || delta <= 0) { - throw new CloudRuntimeException("resource reservations can not be made for no resources"); + @Column(name = GenericDao.CREATED_COLUMN) + private Date created; + + protected ReservationVO() { + } + + public ReservationVO(Long accountId, Long domainId, Resource.ResourceType resourceType, String tag, Long delta) { + if (delta == null) { + throw new CloudRuntimeException("resource reservations can not be made for null resources"); } this.accountId = accountId; this.domainId = domainId; this.resourceType = resourceType; + this.tag = tag; this.amount = delta; + this.managementServerId = ManagementServerNode.getManagementServerId(); + } + + public ReservationVO(Long accountId, Long domainId, Resource.ResourceType resourceType, Long delta) { + this(accountId, domainId, resourceType, null, delta); } @Override @@ -83,8 +106,35 @@ public class ReservationVO implements ResourceReservation { return resourceType; } + @Override + public String getTag() { + return tag; + } + @Override public Long getReservedAmount() { return amount; } + + @Override + public Long getResourceId() { + return resourceId; + } + + public void setResourceId(long resourceId) { + this.resourceId = resourceId; + } + + @Override + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Long getManagementServerId() { + return managementServerId; + } } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/reservation/dao/ReservationDao.java b/engine/schema/src/main/java/org/apache/cloudstack/reservation/dao/ReservationDao.java index eead91c7b8e..d6d494f61f9 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/reservation/dao/ReservationDao.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/reservation/dao/ReservationDao.java @@ -18,11 +18,22 @@ // package org.apache.cloudstack.reservation.dao; -import com.cloud.configuration.Resource; import org.apache.cloudstack.reservation.ReservationVO; + +import com.cloud.configuration.Resource; import com.cloud.utils.db.GenericDao; +import java.util.Date; +import java.util.List; + public interface ReservationDao extends GenericDao { - long getAccountReservation(Long account, Resource.ResourceType resourceType); - long getDomainReservation(Long domain, Resource.ResourceType resourceType); + long getAccountReservation(Long account, Resource.ResourceType resourceType, String tag); + long getDomainReservation(Long domain, Resource.ResourceType resourceType, String tag); + void setResourceId(Resource.ResourceType type, Long resourceId); + List getReservationsForAccount(long accountId, Resource.ResourceType type, String tag); + void removeByIds(List reservationIds); + + int removeByMsId(long managementServerId); + + int removeStaleReservations(Long accountId, Resource.ResourceType resourceType, String tag, Date createdBefore); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/reservation/dao/ReservationDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/reservation/dao/ReservationDaoImpl.java index 6703de0b13c..3b17f4e4294 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/reservation/dao/ReservationDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/reservation/dao/ReservationDaoImpl.java @@ -18,39 +18,103 @@ // package org.apache.cloudstack.reservation.dao; +import java.util.Date; +import java.util.List; + +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.reservation.ReservationVO; + import com.cloud.configuration.Resource; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import org.apache.cloudstack.reservation.ReservationVO; - -import java.util.List; +import org.apache.cloudstack.user.ResourceReservation; +import org.apache.commons.collections.CollectionUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class ReservationDaoImpl extends GenericDaoBase implements ReservationDao { + protected transient Logger logger = LogManager.getLogger(getClass()); private static final String RESOURCE_TYPE = "resourceType"; + private static final String RESOURCE_TAG = "resourceTag"; + private static final String RESOURCE_ID = "resourceId"; private static final String ACCOUNT_ID = "accountId"; private static final String DOMAIN_ID = "domainId"; + private static final String IDS = "ids"; + private static final String MS_ID = "managementServerId"; + private static final String CREATED = "created"; + private final SearchBuilder listResourceByAccountAndTypeSearch; private final SearchBuilder listAccountAndTypeSearch; + private final SearchBuilder listAccountAndTypeAndNoTagSearch; private final SearchBuilder listDomainAndTypeSearch; + private final SearchBuilder listDomainAndTypeAndNoTagSearch; + private final SearchBuilder listResourceByAccountAndTypeAndNoTagSearch; + private final SearchBuilder listIdsSearch; + private final SearchBuilder listMsIdSearch; public ReservationDaoImpl() { + + listResourceByAccountAndTypeSearch = createSearchBuilder(); + listResourceByAccountAndTypeSearch.and(ACCOUNT_ID, listResourceByAccountAndTypeSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + listResourceByAccountAndTypeSearch.and(RESOURCE_TYPE, listResourceByAccountAndTypeSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + listResourceByAccountAndTypeSearch.and(RESOURCE_ID, listResourceByAccountAndTypeSearch.entity().getResourceId(), SearchCriteria.Op.NNULL); + listResourceByAccountAndTypeSearch.and(RESOURCE_TAG, listResourceByAccountAndTypeSearch.entity().getTag(), SearchCriteria.Op.EQ); + listResourceByAccountAndTypeSearch.done(); + + listResourceByAccountAndTypeAndNoTagSearch = createSearchBuilder(); + listResourceByAccountAndTypeAndNoTagSearch.and(ACCOUNT_ID, listResourceByAccountAndTypeAndNoTagSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + listResourceByAccountAndTypeAndNoTagSearch.and(RESOURCE_TYPE, listResourceByAccountAndTypeAndNoTagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + listResourceByAccountAndTypeAndNoTagSearch.and(RESOURCE_ID, listResourceByAccountAndTypeAndNoTagSearch.entity().getResourceId(), SearchCriteria.Op.NNULL); + listResourceByAccountAndTypeAndNoTagSearch.and(RESOURCE_TAG, listResourceByAccountAndTypeAndNoTagSearch.entity().getTag(), SearchCriteria.Op.NULL); + listResourceByAccountAndTypeAndNoTagSearch.done(); + listAccountAndTypeSearch = createSearchBuilder(); listAccountAndTypeSearch.and(ACCOUNT_ID, listAccountAndTypeSearch.entity().getAccountId(), SearchCriteria.Op.EQ); listAccountAndTypeSearch.and(RESOURCE_TYPE, listAccountAndTypeSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + listAccountAndTypeSearch.and(RESOURCE_TAG, listAccountAndTypeSearch.entity().getTag(), SearchCriteria.Op.EQ); + listAccountAndTypeSearch.and(CREATED, listAccountAndTypeSearch.entity().getCreated(), SearchCriteria.Op.LT); listAccountAndTypeSearch.done(); + listAccountAndTypeAndNoTagSearch = createSearchBuilder(); + listAccountAndTypeAndNoTagSearch.and(ACCOUNT_ID, listAccountAndTypeAndNoTagSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + listAccountAndTypeAndNoTagSearch.and(RESOURCE_TYPE, listAccountAndTypeAndNoTagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + listAccountAndTypeAndNoTagSearch.and(RESOURCE_TAG, listAccountAndTypeAndNoTagSearch.entity().getTag(), SearchCriteria.Op.NULL); + listAccountAndTypeAndNoTagSearch.and(CREATED, listAccountAndTypeAndNoTagSearch.entity().getCreated(), SearchCriteria.Op.LT); + listAccountAndTypeAndNoTagSearch.done(); + listDomainAndTypeSearch = createSearchBuilder(); listDomainAndTypeSearch.and(DOMAIN_ID, listDomainAndTypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ); listDomainAndTypeSearch.and(RESOURCE_TYPE, listDomainAndTypeSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + listDomainAndTypeSearch.and(RESOURCE_TAG, listDomainAndTypeSearch.entity().getTag(), SearchCriteria.Op.EQ); listDomainAndTypeSearch.done(); + + listDomainAndTypeAndNoTagSearch = createSearchBuilder(); + listDomainAndTypeAndNoTagSearch.and(DOMAIN_ID, listDomainAndTypeAndNoTagSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + listDomainAndTypeAndNoTagSearch.and(RESOURCE_TYPE, listDomainAndTypeAndNoTagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); + listDomainAndTypeAndNoTagSearch.and(RESOURCE_TAG, listDomainAndTypeAndNoTagSearch.entity().getTag(), SearchCriteria.Op.NULL); + listDomainAndTypeAndNoTagSearch.done(); + + listIdsSearch = createSearchBuilder(); + listIdsSearch.and(IDS, listIdsSearch.entity().getId(), SearchCriteria.Op.IN); + listIdsSearch.done(); + + listMsIdSearch = createSearchBuilder(); + listMsIdSearch.and(MS_ID, listMsIdSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ); + listMsIdSearch.done(); } @Override - public long getAccountReservation(Long accountId, Resource.ResourceType resourceType) { + public long getAccountReservation(Long accountId, Resource.ResourceType resourceType, String tag) { long total = 0; - SearchCriteria sc = listAccountAndTypeSearch.create(); + SearchCriteria sc; + if (tag == null) { + sc = listAccountAndTypeAndNoTagSearch.create(); + } else { + sc = listAccountAndTypeSearch.create(); + sc.setParameters(RESOURCE_TAG, tag); + } sc.setParameters(ACCOUNT_ID, accountId); sc.setParameters(RESOURCE_TYPE, resourceType); List reservations = listBy(sc); @@ -61,9 +125,15 @@ public class ReservationDaoImpl extends GenericDaoBase impl } @Override - public long getDomainReservation(Long domainId, Resource.ResourceType resourceType) { + public long getDomainReservation(Long domainId, Resource.ResourceType resourceType, String tag) { long total = 0; - SearchCriteria sc = listDomainAndTypeSearch.create(); + SearchCriteria sc; + if (tag == null) { + sc = listDomainAndTypeAndNoTagSearch.create(); + } else { + sc = listDomainAndTypeSearch.create(); + sc.setParameters(RESOURCE_TAG, tag); + } sc.setParameters(DOMAIN_ID, domainId); sc.setParameters(RESOURCE_TYPE, resourceType); List reservations = listBy(sc); @@ -72,4 +142,70 @@ public class ReservationDaoImpl extends GenericDaoBase impl } return total; } + + @Override + public void setResourceId(Resource.ResourceType type, Long resourceId) { + Object obj = CallContext.current().getContextParameter(String.format("%s-%s", ResourceReservation.class.getSimpleName(), type.getName())); + if (obj instanceof List) { + try { + List reservationIds = (List)obj; + for (Long reservationId : reservationIds) { + ReservationVO reservation = findById(reservationId); + if (reservation != null) { + reservation.setResourceId(resourceId); + persist(reservation); + } + } + } catch (Exception e) { + logger.warn("Failed to persist reservation for resource type " + type.getName() + " for resource id " + resourceId, e); + } + } + } + + @Override + public List getReservationsForAccount(long accountId, Resource.ResourceType type, String tag) { + SearchCriteria sc; + if (tag == null) { + sc = listResourceByAccountAndTypeAndNoTagSearch.create(); + } else { + sc = listResourceByAccountAndTypeSearch.create(); + sc.setParameters(RESOURCE_TAG, tag); + } + sc.setParameters(ACCOUNT_ID, accountId); + sc.setParameters(RESOURCE_TYPE, type); + return listBy(sc); + } + + @Override + public void removeByIds(List reservationIds) { + if (CollectionUtils.isNotEmpty(reservationIds)) { + SearchCriteria sc = listIdsSearch.create(); + sc.setParameters(IDS, reservationIds.toArray()); + remove(sc); + } + } + + @Override + public int removeByMsId(long managementServerId) { + SearchCriteria sc = listMsIdSearch.create(); + sc.setParameters(MS_ID, managementServerId); + return remove(sc); + } + + @Override + public int removeStaleReservations(Long accountId, Resource.ResourceType resourceType, String tag, + Date createdBefore) { + SearchCriteria sc; + if (tag == null) { + sc = listAccountAndTypeAndNoTagSearch.create(); + } else { + sc = listAccountAndTypeSearch.create(); + sc.setParameters(RESOURCE_TAG, tag); + } + sc.setParameters(ACCOUNT_ID, accountId); + sc.setParameters(RESOURCE_TYPE, resourceType); + sc.setParameters(CREATED, createdBefore); + return remove(sc); + } + } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/FirewallRuleDetailVO.java b/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/FirewallRuleDetailVO.java index 636d889fafe..1149d0b13e7 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/FirewallRuleDetailVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/FirewallRuleDetailVO.java @@ -79,4 +79,8 @@ public class FirewallRuleDetailVO implements ResourceDetail { public boolean isDisplay() { return display; } + + public void setValue(String value) { + this.value = value; + } } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/ResourceDetailsDao.java b/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/ResourceDetailsDao.java index 6daf8f02231..6b6fe200c10 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/ResourceDetailsDao.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/ResourceDetailsDao.java @@ -53,7 +53,7 @@ public interface ResourceDetailsDao extends GenericDao * Removes all details for the resource specified * @param resourceId */ - public void removeDetails(long resourceId); + void removeDetails(long resourceId); /** @@ -76,7 +76,7 @@ public interface ResourceDetailsDao extends GenericDao * @param resourceId * @return list of details each implementing ResourceDetail interface */ - public List listDetails(long resourceId); + List listDetails(long resourceId); /** * List details for resourceId having display field = forDisplay value passed in @@ -84,19 +84,23 @@ public interface ResourceDetailsDao extends GenericDao * @param forDisplay * @return */ - public List listDetails(long resourceId, boolean forDisplay); + List listDetails(long resourceId, boolean forDisplay); - public Map listDetailsKeyPairs(long resourceId); + Map listDetailsKeyPairs(long resourceId); - public Map listDetailsKeyPairs(long resourceId, boolean forDisplay); + Map listDetailsKeyPairs(long resourceId, List keys); + + Map listDetailsKeyPairs(long resourceId, boolean forDisplay); Map listDetailsVisibility(long resourceId); - public void saveDetails(List details); + void saveDetails(List details); - public void addDetail(long resourceId, String key, String value, boolean display); + void addDetail(long resourceId, String key, String value, boolean display); - public List findResourceIdsByNameAndValueIn(String name, Object[] values); + List findResourceIdsByNameAndValueIn(String name, Object[] values); + + long batchExpungeForResources(List ids, Long batchSize); String getActualValue(ResourceDetail resourceDetail); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/ResourceDetailsDaoBase.java b/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/ResourceDetailsDaoBase.java index 556c832e991..29d3f88fd90 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/ResourceDetailsDaoBase.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/ResourceDetailsDaoBase.java @@ -19,16 +19,19 @@ package org.apache.cloudstack.resourcedetail; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.collections.CollectionUtils; import com.cloud.utils.crypt.DBEncryptionUtil; -import org.apache.cloudstack.api.ResourceDetail; - import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.TransactionLegacy; + +import org.apache.cloudstack.api.ResourceDetail; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.config.impl.ConfigurationVO; @@ -83,8 +86,7 @@ public abstract class ResourceDetailsDaoBase extends G sc.setParameters("value", value); } - List results = search(sc, null); - return results; + return search(sc, null); } public Map listDetailsKeyPairs(long resourceId) { @@ -92,13 +94,27 @@ public abstract class ResourceDetailsDaoBase extends G sc.setParameters("resourceId", resourceId); List results = search(sc, null); - Map details = new HashMap(results.size()); + Map details = new HashMap<>(results.size()); for (R result : results) { details.put(result.getName(), result.getValue()); } return details; } + @Override + public Map listDetailsKeyPairs(long resourceId, List keys) { + SearchBuilder sb = createSearchBuilder(); + sb.and("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.IN); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("resourceId", resourceId); + sc.setParameters("name", keys.toArray()); + + List results = search(sc, null); + return results.stream().collect(Collectors.toMap(R::getName, R::getValue)); + } + public Map listDetailsVisibility(long resourceId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("resourceId", resourceId); @@ -115,8 +131,7 @@ public abstract class ResourceDetailsDaoBase extends G SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("resourceId", resourceId); - List results = search(sc, null); - return results; + return search(sc, null); } public void removeDetails(long resourceId) { @@ -178,7 +193,7 @@ public abstract class ResourceDetailsDaoBase extends G sc.setParameters("display", forDisplay); List results = search(sc, null); - Map details = new HashMap(results.size()); + Map details = new HashMap<>(results.size()); for (R result : results) { details.put(result.getName(), result.getValue()); } @@ -190,8 +205,7 @@ public abstract class ResourceDetailsDaoBase extends G sc.setParameters("resourceId", resourceId); sc.setParameters("display", forDisplay); - List results = search(sc, null); - return results; + return search(sc, null); } @Override @@ -211,6 +225,19 @@ public abstract class ResourceDetailsDaoBase extends G return customSearch(sc, null); } + @Override + public long batchExpungeForResources(final List ids, final Long batchSize) { + if (CollectionUtils.isEmpty(ids)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("ids", sb.entity().getResourceId(), Op.IN); + sb.done(); + SearchCriteria sc = sb.create(); + sc.setParameters("ids", ids.toArray()); + return batchExpunge(sc, batchSize); + } + @Override public String getActualValue(ResourceDetail resourceDetail) { ConfigurationVO configurationVO = configDao.findByName(resourceDetail.getName()); diff --git a/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/UserDetailVO.java b/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/UserDetailVO.java index 1b430e806e2..d0cfcc3d439 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/UserDetailVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/resourcedetail/UserDetailVO.java @@ -46,6 +46,8 @@ public class UserDetailVO implements ResourceDetail { private boolean display = true; public static final String Setup2FADetail = "2FASetupStatus"; + public static final String PasswordResetToken = "PasswordResetToken"; + public static final String PasswordResetTokenExpiryDate = "PasswordResetTokenExpiryDate"; public UserDetailVO() { } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/secstorage/HeuristicVO.java b/engine/schema/src/main/java/org/apache/cloudstack/secstorage/HeuristicVO.java index b0da0c5e747..f647d0c8365 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/secstorage/HeuristicVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/secstorage/HeuristicVO.java @@ -120,6 +120,8 @@ public class HeuristicVO implements Heuristic { @Override public String toString() { - return ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "name", "heuristicRule", "type"); + return String.format("Heuristic %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "heuristicRule", "type")); } } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDao.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDao.java index 7aab5bbf7b3..eda4bcfdaa1 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDao.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDao.java @@ -44,7 +44,7 @@ public interface ImageStoreDao extends GenericDao { List listStoresByZoneId(long zoneId); - List listAllStoresInZone(Long zoneId, String provider, DataStoreRole role); + List listAllStoresInZoneExceptId(Long zoneId, String provider, DataStoreRole role, long storeId); List findByProtocol(String protocol); diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDaoImpl.java index 84b88c215ca..4cb40b5eaf6 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDaoImpl.java @@ -41,7 +41,7 @@ public class ImageStoreDaoImpl extends GenericDaoBase implem private SearchBuilder nameSearch; private SearchBuilder providerSearch; private SearchBuilder regionSearch; - private SearchBuilder storeSearch; + private SearchBuilder storesExceptIdSearch; private SearchBuilder protocolSearch; private SearchBuilder zoneProtocolSearch; @@ -88,11 +88,12 @@ public class ImageStoreDaoImpl extends GenericDaoBase implem regionSearch.and("role", regionSearch.entity().getRole(), SearchCriteria.Op.EQ); regionSearch.done(); - storeSearch = createSearchBuilder(); - storeSearch.and("providerName", storeSearch.entity().getProviderName(), SearchCriteria.Op.EQ); - storeSearch.and("role", storeSearch.entity().getRole(), SearchCriteria.Op.EQ); - storeSearch.and("dataCenterId", storeSearch.entity().getDcId(), SearchCriteria.Op.EQ); - storeSearch.done(); + storesExceptIdSearch = createSearchBuilder(); + storesExceptIdSearch.and("providerName", storesExceptIdSearch.entity().getProviderName(), SearchCriteria.Op.EQ); + storesExceptIdSearch.and("role", storesExceptIdSearch.entity().getRole(), SearchCriteria.Op.EQ); + storesExceptIdSearch.and("dataCenterId", storesExceptIdSearch.entity().getDcId(), SearchCriteria.Op.EQ); + storesExceptIdSearch.and("id", storesExceptIdSearch.entity().getId(), SearchCriteria.Op.NEQ); + storesExceptIdSearch.done(); return true; } @@ -113,11 +114,12 @@ public class ImageStoreDaoImpl extends GenericDaoBase implem } @Override - public List listAllStoresInZone(Long zoneId, String provider, DataStoreRole role) { - SearchCriteria sc = storeSearch.create(); + public List listAllStoresInZoneExceptId(Long zoneId, String provider, DataStoreRole role, long id) { + SearchCriteria sc = storesExceptIdSearch.create(); sc.setParameters("providerName", provider); sc.setParameters("role", role); sc.setParameters("dataCenterId", zoneId); + sc.setParameters("id", id); return listBy(sc); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailsDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailsDaoImpl.java index 1b0644820c5..97e41949a57 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailsDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreDetailsDaoImpl.java @@ -20,6 +20,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.framework.config.ConfigKey.Scope; +import org.apache.cloudstack.framework.config.ScopedConfigStorage; +import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; import org.springframework.stereotype.Component; import com.cloud.utils.crypt.DBEncryptionUtil; @@ -29,12 +34,6 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.TransactionLegacy; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.framework.config.ConfigKey; -import org.apache.cloudstack.framework.config.ConfigKey.Scope; -import org.apache.cloudstack.framework.config.ScopedConfigStorage; -import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase; - @Component public class ImageStoreDetailsDaoImpl extends ResourceDetailsDaoBase implements ImageStoreDetailsDao, ScopedConfigStorage { protected final SearchBuilder storeSearch; @@ -67,7 +66,7 @@ public class ImageStoreDetailsDaoImpl extends ResourceDetailsDaoBase details = listBy(sc); - Map detailsMap = new HashMap(); + Map detailsMap = new HashMap<>(); for (ImageStoreDetailVO detail : details) { String name = detail.getName(); String value = detail.getValue(); @@ -104,11 +103,17 @@ public class ImageStoreDetailsDaoImpl extends ResourceDetailsDaoBase key) { ImageStoreDetailVO vo = findDetail(id, key.key()); return vo == null ? null : getActualValue(vo); - } + } @Override public void addDetail(long resourceId, String key, String value, boolean display) { diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreVO.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreVO.java index 3ca9259c099..c13f5aac6d6 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ImageStoreVO.java @@ -33,6 +33,7 @@ import com.cloud.storage.ImageStore; import com.cloud.storage.ScopeType; import com.cloud.utils.UriUtils; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; @Entity @Table(name = "image_store") @@ -215,4 +216,11 @@ public class ImageStoreVO implements ImageStore { public void setUsedBytes(Long usedBytes) { this.usedBytes = usedBytes; } + + @Override + public String toString() { + return String.format("ImageStore %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name")); + } } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ObjectStoreVO.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ObjectStoreVO.java index 885cbfd98ab..18cc06a6573 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ObjectStoreVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/ObjectStoreVO.java @@ -20,6 +20,7 @@ package org.apache.cloudstack.storage.datastore.db; import org.apache.cloudstack.storage.object.ObjectStore; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import javax.persistence.Column; import javax.persistence.Entity; @@ -140,4 +141,11 @@ public class ObjectStoreVO implements ObjectStore { public void setDetails(Map details) { this.details = details; } + + @Override + public String toString() { + return String.format("ObjectStore %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "name", "providerName")); + } } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java index 2fce0628554..102df6848f8 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java @@ -143,7 +143,7 @@ public interface PrimaryDataStoreDao extends GenericDao { Integer countAll(); - List findPoolsByStorageType(String storageType); + List findPoolsByStorageType(Storage.StoragePoolType storageType); StoragePoolVO findPoolByZoneAndPath(long zoneId, String datastorePath); @@ -154,4 +154,6 @@ public interface PrimaryDataStoreDao extends GenericDao { String keyword, Filter searchFilter); List listByIds(List ids); + + List listByDataCenterIds(List dataCenterIds); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java index 9b03bfe29a7..0d901c82306 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java @@ -28,20 +28,20 @@ import java.util.stream.Collectors; import javax.inject.Inject; import javax.naming.ConfigurationException; -import com.cloud.storage.Storage; -import com.cloud.utils.Pair; -import com.cloud.utils.db.Filter; import org.apache.commons.collections.CollectionUtils; import com.cloud.host.Status; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.ScopeType; +import com.cloud.storage.Storage; import com.cloud.storage.StoragePoolHostVO; import com.cloud.storage.StoragePoolStatus; import com.cloud.storage.StoragePoolTagVO; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.StoragePoolTagsDao; +import com.cloud.utils.Pair; import com.cloud.utils.db.DB; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.JoinBuilder; @@ -63,6 +63,7 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase private final GenericSearchBuilder StatusCountSearch; private final SearchBuilder ClustersSearch; private final SearchBuilder IdsSearch; + private final SearchBuilder DcsSearch; @Inject private StoragePoolDetailsDao _detailsDao; @@ -155,6 +156,9 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase IdsSearch.and("ids", IdsSearch.entity().getId(), SearchCriteria.Op.IN); IdsSearch.done(); + DcsSearch = createSearchBuilder(); + DcsSearch.and("dataCenterId", DcsSearch.entity().getDataCenterId(), SearchCriteria.Op.IN); + DcsSearch.done(); } @Override @@ -676,7 +680,7 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase } @Override - public List findPoolsByStorageType(String storageType) { + public List findPoolsByStorageType(Storage.StoragePoolType storageType) { SearchCriteria sc = AllFieldSearch.create(); sc.setParameters("poolType", storageType); return listBy(sc); @@ -733,6 +737,16 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase return listBy(sc); } + @Override + public List listByDataCenterIds(List dataCenterIds) { + if (CollectionUtils.isEmpty(dataCenterIds)) { + return Collections.emptyList(); + } + SearchCriteria sc = DcsSearch.create(); + sc.setParameters("dataCenterId", dataCenterIds.toArray()); + return listBy(sc); + } + private SearchCriteria createStoragePoolSearchCriteria(Long storagePoolId, String storagePoolName, Long zoneId, String path, Long podId, Long clusterId, String address, ScopeType scopeType, StoragePoolStatus status, String keyword) { diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java index 344ff8b2a69..4cd29b465ee 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java @@ -106,4 +106,6 @@ StateDao snapshotIds, Long batchSize); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDaoImpl.java index 98cb6ca5b42..5bf67eb3881 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDaoImpl.java @@ -32,7 +32,6 @@ import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreState import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.hypervisor.Hypervisor; @@ -50,7 +49,6 @@ import com.cloud.utils.db.UpdateBuilder; @Component public class SnapshotDataStoreDaoImpl extends GenericDaoBase implements SnapshotDataStoreDao { - private static final Logger s_logger = Logger.getLogger(SnapshotDataStoreDaoImpl.class); private static final String STORE_ID = "store_id"; private static final String STORE_ROLE = "store_role"; private static final String STATE = "state"; @@ -188,7 +186,7 @@ public class SnapshotDataStoreDaoImpl extends GenericDaoBase snapshots = listBy(sc); if (snapshots == null) { - s_logger.debug(String.format("There are no snapshots on cache store to duplicate to region store [%s].", storeId)); + logger.debug(String.format("There are no snapshots on cache store to duplicate to region store [%s].", storeId)); return; } - s_logger.info(String.format("Duplicating [%s] snapshot cache store records to region store [%s].", snapshots.size(), storeId)); + logger.info(String.format("Duplicating [%s] snapshot cache store records to region store [%s].", snapshots.size(), storeId)); for (SnapshotDataStoreVO snap : snapshots) { SnapshotDataStoreVO snapStore = findByStoreSnapshot(DataStoreRole.Image, storeId, snap.getSnapshotId()); if (snapStore != null) { - s_logger.debug(String.format("There is already an entry for snapshot [%s] on region store [%s].", snap.getSnapshotId(), storeId)); + logger.debug(String.format("There is already an entry for snapshot [%s] on region store [%s].", snap.getSnapshotId(), storeId)); continue; } - s_logger.info(String.format("Persisting an entry for snapshot [%s] on region store [%s].", snap.getSnapshotId(), storeId)); + logger.info(String.format("Persisting an entry for snapshot [%s] on region store [%s].", snap.getSnapshotId(), storeId)); SnapshotDataStoreVO ss = new SnapshotDataStoreVO(); ss.setSnapshotId(snap.getSnapshotId()); ss.setDataStoreId(storeId); @@ -434,9 +432,9 @@ public class SnapshotDataStoreDaoImpl extends GenericDaoBase snaps = listBy(sc); if (snaps != null) { - s_logger.info(String.format("Updating role to cache store for [%s] entries in snapshot_store_ref.", snaps.size())); + logger.info(String.format("Updating role to cache store for [%s] entries in snapshot_store_ref.", snaps.size())); for (SnapshotDataStoreVO snap : snaps) { - s_logger.debug(String.format("Updating role to cache store for entry [%s].", snap)); + logger.debug(String.format("Updating role to cache store for entry [%s].", snap)); snap.setRole(DataStoreRole.ImageCache); update(snap.getId(), snap); } @@ -561,4 +559,16 @@ public class SnapshotDataStoreDaoImpl extends GenericDaoBase snapshotIds, final Long batchSize) { + if (CollectionUtils.isEmpty(snapshotIds)) { + return 0; + } + SearchBuilder sb = createSearchBuilder(); + sb.and("snapshotIds", sb.entity().getSnapshotId(), SearchCriteria.Op.IN); + SearchCriteria sc = sb.create(); + sc.setParameters("snapshotIds", snapshotIds.toArray()); + return batchExpunge(sc, batchSize); + } } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreVO.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreVO.java index 6f6ed4e08f2..7a466c1f505 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreVO.java @@ -29,7 +29,8 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; @@ -47,7 +48,7 @@ import com.cloud.utils.fsm.StateObject; @Entity @Table(name = "snapshot_store_ref") public class SnapshotDataStoreVO implements StateObject, DataObjectInStore { - private static final Logger s_logger = Logger.getLogger(SnapshotDataStoreVO.class); + protected transient Logger logger = LogManager.getLogger(getClass()); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -85,6 +86,13 @@ public class SnapshotDataStoreVO implements StateObject, DataObjectInStore { - private static final Logger s_logger = Logger.getLogger(TemplateDataStoreVO.class); + protected transient Logger logger = LogManager.getLogger(getClass()); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -382,7 +383,7 @@ public class TemplateDataStoreVO implements StateObject, List listByVolume(long volumeId, long storeId); List listByStoreIdAndInstallPaths(Long storeId, List paths); + + int expungeByVolumeList(List volumeIds, Long batchSize); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java index bb21abbe44b..d57dec8fbfd 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java @@ -29,7 +29,8 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; @@ -46,7 +47,7 @@ import com.cloud.utils.fsm.StateObject; @Entity @Table(name = "volume_store_ref") public class VolumeDataStoreVO implements StateObject, DataObjectInStore { - private static final Logger s_logger = Logger.getLogger(VolumeDataStoreVO.class); + protected transient Logger logger = LogManager.getLogger(getClass()); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -362,7 +363,7 @@ public class VolumeDataStoreVO implements StateObject getEntityType() { + return SharedFS.class; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + @Override + public String getUuid() { + return uuid; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public void setDescription(String description) { + this.description = description; + } + + @Override + public long getDomainId() { + return domainId; + } + + @Override + public long getAccountId() { + return accountId; + } + + @Override + public Long getDataCenterId() { + return dataCenterId; + } + + @Override + public State getState() { + return state; + } + + @Override + public String getFsProviderName() { + return fsProviderName; + } + + @Override + public Protocol getProtocol() { + return protocol; + } + + @Override + public Long getVolumeId() { + return volumeId; + } + + @Override + public void setVolumeId(Long volumeId) { + this.volumeId = volumeId; + } + + @Override + public Long getVmId() { + return vmId; + } + + @Override + public void setVmId(Long vmId) { + this.vmId = vmId; + } + + @Override + public FileSystemType getFsType() { + return fsType; + } + + @Override + public Long getServiceOfferingId() { + return serviceOfferingId; + } + + @Override + public void setServiceOfferingId(Long serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; + } + + @Override + public Date getUpdated() { + return updated; + } + + @Override + public long getUpdatedCount() { + return updatedCount; + } + + @Override + public void incrUpdatedCount() { + updatedCount++; + } + +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/sharedfs/dao/SharedFSDao.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/sharedfs/dao/SharedFSDao.java new file mode 100644 index 00000000000..4735202a762 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/sharedfs/dao/SharedFSDao.java @@ -0,0 +1,32 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.storage.sharedfs.dao; + +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSVO; + +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.fsm.StateDao; + +import java.util.Date; +import java.util.List; + +public interface SharedFSDao extends GenericDao, StateDao { + List listSharedFSToBeDestroyed(Date date); + + SharedFSVO findSharedFSByNameAccountDomain(String name, Long accountId, Long domainId); +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/sharedfs/dao/SharedFSDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/sharedfs/dao/SharedFSDaoImpl.java new file mode 100644 index 00000000000..da622071671 --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/sharedfs/dao/SharedFSDaoImpl.java @@ -0,0 +1,117 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.storage.sharedfs.dao; + +import com.cloud.network.dao.NetworkDao; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.UpdateBuilder; + +import org.apache.cloudstack.engine.cloud.entity.api.db.dao.VMNetworkMapDao; +import org.apache.cloudstack.storage.sharedfs.SharedFS; +import org.apache.cloudstack.storage.sharedfs.SharedFSVO; + +import javax.inject.Inject; +import java.util.Date; +import java.util.List; + +public class SharedFSDaoImpl extends GenericDaoBase implements SharedFSDao { + + @Inject + VMNetworkMapDao vmNetworkMapDao; + + @Inject + NetworkDao networkDao; + + protected final SearchBuilder StateUpdateCountSearch; + + protected final SearchBuilder DestroyedByTimeSearch; + + protected final SearchBuilder NameAccountDomainSearch; + + public SharedFSDaoImpl() { + StateUpdateCountSearch = createSearchBuilder(); + StateUpdateCountSearch.and("id", StateUpdateCountSearch.entity().getId(), SearchCriteria.Op.EQ); + StateUpdateCountSearch.and("state", StateUpdateCountSearch.entity().getState(), SearchCriteria.Op.EQ); + StateUpdateCountSearch.and("updatedCount", StateUpdateCountSearch.entity().getUpdatedCount(), SearchCriteria.Op.EQ); + StateUpdateCountSearch.done(); + + DestroyedByTimeSearch = createSearchBuilder(); + DestroyedByTimeSearch.and("state", DestroyedByTimeSearch.entity().getState(), SearchCriteria.Op.IN); + DestroyedByTimeSearch.and("accountId", DestroyedByTimeSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + DestroyedByTimeSearch.done(); + + NameAccountDomainSearch = createSearchBuilder(); + NameAccountDomainSearch.and("name", NameAccountDomainSearch.entity().getName(), SearchCriteria.Op.EQ); + NameAccountDomainSearch.and("accountId", NameAccountDomainSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + NameAccountDomainSearch.and("domainId", NameAccountDomainSearch.entity().getDomainId(), SearchCriteria.Op.EQ); + NameAccountDomainSearch.done(); + } + + @Override + public boolean updateState(SharedFS.State currentState, SharedFS.Event event, SharedFS.State nextState, SharedFS vo, Object data) { + + Long oldUpdated = vo.getUpdatedCount(); + Date oldUpdatedTime = vo.getUpdated(); + + SearchCriteria sc = StateUpdateCountSearch.create(); + sc.setParameters("id", vo.getId()); + sc.setParameters("state", currentState); + sc.setParameters("updatedCount", vo.getUpdatedCount()); + + vo.incrUpdatedCount(); + + UpdateBuilder builder = getUpdateBuilder(vo); + builder.set(vo, "state", nextState); + builder.set(vo, "updated", new Date()); + + int rows = update((SharedFSVO) vo, sc); + if (rows == 0 && logger.isDebugEnabled()) { + SharedFSVO dbSharedFS = findByIdIncludingRemoved(vo.getId()); + if (dbSharedFS != null) { + StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); + str.append(": DB Data={id=").append(dbSharedFS.getId()).append("; state=").append(dbSharedFS.getState()).append("; updatecount=").append(dbSharedFS.getUpdatedCount()).append(";updatedTime=") + .append(dbSharedFS.getUpdated()); + str.append(": New Data={id=").append(vo.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(vo.getUpdatedCount()) + .append("; updatedTime=").append(vo.getUpdated()); + str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated) + .append("; updatedTime=").append(oldUpdatedTime); + } else { + logger.debug("Unable to update sharedfs: id=" + vo.getId() + ", as it is not present in the database anymore"); + } + } + return rows > 0; + } + + @Override + public List listSharedFSToBeDestroyed(Date date) { + SearchCriteria sc = DestroyedByTimeSearch.create(); + sc.setParameters("state", SharedFS.State.Destroyed, SharedFS.State.Expunging, SharedFS.State.Error); + sc.setParameters("updateTime", date); + return listBy(sc); + } + + @Override + public SharedFSVO findSharedFSByNameAccountDomain(String name, Long accountId, Long domainId) { + SearchCriteria sc = NameAccountDomainSearch.create(); + sc.setParameters("name", name); + sc.setParameters("accountId", accountId); + sc.setParameters("domainId", domainId); + return findOneBy(sc); + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/util/CPUArchConverter.java b/engine/schema/src/main/java/org/apache/cloudstack/util/CPUArchConverter.java new file mode 100644 index 00000000000..8e56cce739d --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/util/CPUArchConverter.java @@ -0,0 +1,36 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package org.apache.cloudstack.util; + +import com.cloud.cpu.CPU; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +@Converter(autoApply = true) +public class CPUArchConverter implements AttributeConverter { + + @Override + public String convertToDatabaseColumn(CPU.CPUArch cpuArch) { + return cpuArch == null ? CPU.CPUArch.amd64.getType() : cpuArch.getType(); + } + + @Override + public CPU.CPUArch convertToEntityAttribute(String attribute) { + return CPU.CPUArch.fromType(attribute); + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/util/HypervisorTypeConverter.java b/engine/schema/src/main/java/org/apache/cloudstack/util/HypervisorTypeConverter.java new file mode 100644 index 00000000000..57c12a9b7fa --- /dev/null +++ b/engine/schema/src/main/java/org/apache/cloudstack/util/HypervisorTypeConverter.java @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// 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. +package org.apache.cloudstack.util; + +import com.cloud.hypervisor.Hypervisor; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +/** + * Converts {@link com.cloud.hypervisor.Hypervisor.HypervisorType} to and from {@link String} using {@link com.cloud.hypervisor.Hypervisor.HypervisorType#name()}. + */ +@Converter +public class HypervisorTypeConverter implements AttributeConverter { + @Override + public String convertToDatabaseColumn(Hypervisor.HypervisorType attribute) { + return attribute != null ? attribute.name() : null; + } + + @Override + public Hypervisor.HypervisorType convertToEntityAttribute(String dbData) { + return dbData != null ? Hypervisor.HypervisorType.valueOf(dbData) : null; + } +} diff --git a/engine/schema/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduleVO.java b/engine/schema/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduleVO.java index 176f88c5f6b..e0065db1e77 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduleVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduleVO.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.vm.schedule; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; import javax.persistence.Column; import javax.persistence.Entity; @@ -95,6 +96,11 @@ public class VMScheduleVO implements VMSchedule { this.enabled = enabled; } + @Override + public String toString() { + return String.format("VMSchedule %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "id", "uuid", "action", "description")); + } + @Override public String getUuid() { return uuid; diff --git a/engine/schema/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduledJobVO.java b/engine/schema/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduledJobVO.java index 0c2dd94cce5..775e9cfe40c 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduledJobVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduledJobVO.java @@ -18,6 +18,8 @@ */ package org.apache.cloudstack.vm.schedule; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; @@ -71,6 +73,14 @@ public class VMScheduledJobVO implements VMScheduledJob { this.scheduledTime = scheduledTime; } + + @Override + public String toString() { + return String.format("VMScheduledJob %s", + ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "id", "uuid", "action", "vmScheduleId", "vmId", "asyncJobId")); + } + @Override public String getUuid() { return uuid; diff --git a/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-common-daos-between-management-and-usage-context.xml b/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-common-daos-between-management-and-usage-context.xml index 2b6361c8126..d6d72f9228e 100644 --- a/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-common-daos-between-management-and-usage-context.xml +++ b/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-common-daos-between-management-and-usage-context.xml @@ -70,5 +70,6 @@ + diff --git a/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml b/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml index ba25f1a91ae..4f22234d7bf 100644 --- a/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml +++ b/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml @@ -117,6 +117,7 @@ + @@ -136,6 +137,7 @@ + @@ -157,7 +159,6 @@ - @@ -187,7 +188,6 @@ - @@ -270,6 +270,7 @@ + @@ -290,4 +291,13 @@ + + + + + + + + + diff --git a/engine/schema/src/main/resources/META-INF/db/data-217to218.sql b/engine/schema/src/main/resources/META-INF/db/data-217to218.sql index 5c1253143f4..1a03e9b7998 100755 --- a/engine/schema/src/main/resources/META-INF/db/data-217to218.sql +++ b/engine/schema/src/main/resources/META-INF/db/data-217to218.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/procedures/cloud.idempotent_add_foreign_key.sql b/engine/schema/src/main/resources/META-INF/db/procedures/cloud.idempotent_add_foreign_key.sql new file mode 100644 index 00000000000..754c02acb93 --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/procedures/cloud.idempotent_add_foreign_key.sql @@ -0,0 +1,28 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. + +DROP PROCEDURE IF EXISTS `cloud`.`IDEMPOTENT_ADD_FOREIGN_KEY`; + +CREATE PROCEDURE `cloud`.`IDEMPOTENT_ADD_FOREIGN_KEY` ( + IN in_table_name VARCHAR(200) + , IN in_key_name VARCHAR(200) + , IN in_foreign_key VARCHAR(200) + , IN in_references VARCHAR(1000) +) +BEGIN + + DECLARE CONTINUE HANDLER FOR 1061 BEGIN END; SET @ddl = CONCAT_WS(' ', 'ALTER TABLE ', in_table_name, ' ADD CONSTRAINT ', in_key_name, ' FOREIGN KEY ', in_foreign_key, ' REFERENCES ', in_references, ' ON DELETE CASCADE'); PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt; END; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-20to21.sql b/engine/schema/src/main/resources/META-INF/db/schema-20to21.sql index 7013046ca43..000d0f077cc 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-20to21.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-20to21.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -141,14 +141,14 @@ ALTER TABLE `cloud`.`host` ADD COLUMN `cluster_id` bigint unsigned; -- -- enforced in postporcess-20to21.sql -ALTER TABLE `cloud`.`host_pod_ref` ADD COLUMN `gateway` varchar(255); -- need to migrage data with user input +ALTER TABLE `cloud`.`host_pod_ref` ADD COLUMN `gateway` varchar(255); -- need to migrage data with user input -ALTER TABLE `cloud`.`service_offering` ADD COLUMN `recreatable` tinyint(1) unsigned NOT NULL DEFAULT 0; +ALTER TABLE `cloud`.`service_offering` ADD COLUMN `recreatable` tinyint(1) unsigned NOT NULL DEFAULT 0; ALTER TABLE `cloud`.`service_offering` ADD COLUMN `tags` varchar(255); -ALTER TABLE `cloud`.`user_vm` MODIFY COLUMN `domain_router_id` bigint unsigned; -- change from NOT NULL to NULL +ALTER TABLE `cloud`.`user_vm` MODIFY COLUMN `domain_router_id` bigint unsigned; -- change from NOT NULL to NULL -ALTER TABLE `cloud`.`event` ADD COLUMN `state` varchar(32) NOT NULL DEFAULT 'Completed'; +ALTER TABLE `cloud`.`event` ADD COLUMN `state` varchar(32) NOT NULL DEFAULT 'Completed'; ALTER TABLE `cloud`.`event` ADD COLUMN `start_id` bigint unsigned NOT NULL DEFAULT 0; ALTER TABLE `cloud`.`disk_offering` ADD COLUMN `tags` varchar(4096); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-217to218.sql b/engine/schema/src/main/resources/META-INF/db/schema-217to218.sql index f2b6b291f78..006a3f1cd7b 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-217to218.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-217to218.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-21to22-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-21to22-cleanup.sql index c8757833fab..8a3ca39d5e7 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-21to22-cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-21to22-cleanup.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-21to22-premium.sql b/engine/schema/src/main/resources/META-INF/db/schema-21to22-premium.sql index 45202840565..a34b65dc8ab 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-21to22-premium.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-21to22-premium.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -50,7 +50,7 @@ CREATE TABLE `cloud_usage`.`usage_event` ( `resource_name` varchar(255), `offering_id` bigint unsigned, `template_id` bigint unsigned, - `size` bigint unsigned, + `size` bigint unsigned, `processed` tinyint NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-21to22.sql b/engine/schema/src/main/resources/META-INF/db/schema-21to22.sql index eb473cfc7f6..8da29caae53 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-21to22.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-21to22.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -22,7 +22,7 @@ ALTER TABLE `cloud`.`cluster` ADD COLUMN `guid` varchar(255) UNIQUE DEFAULT NULL ALTER TABLE `cloud`.`cluster` ADD COLUMN `cluster_type` varchar(64) DEFAULT 'CloudManaged'; ALTER TABLE `cloud`.`vm_template` ADD COLUMN `hypervisor_type` varchar(32) COMMENT 'hypervisor that the template is belonged to'; ALTER TABLE `cloud`.`vm_template` ADD COLUMN `extractable` int(1) unsigned NOT NULL default 0 COMMENT 'Is this template extractable'; -ALTER TABLE `cloud`.`template_spool_ref` ADD CONSTRAINT `fk_template_spool_ref__template_id` FOREIGN KEY (`template_id`) REFERENCES `vm_template`(`id`); +ALTER TABLE `cloud`.`template_spool_ref` ADD CONSTRAINT `fk_template_spool_ref__template_id` FOREIGN KEY (`template_id`) REFERENCES `vm_template`(`id`); ALTER TABLE `cloud`.`guest_os` modify `name` varchar(255) ; @@ -104,7 +104,7 @@ CREATE TABLE `cloud`.`networks` ( `broadcast_domain_type` varchar(32) NOT NULL COMMENT 'type of broadcast domain used', `broadcast_uri` varchar(255) COMMENT 'broadcast domain specifier', `gateway` varchar(15) COMMENT 'gateway for this network configuration', - `cidr` varchar(18) COMMENT 'network cidr', + `cidr` varchar(18) COMMENT 'network cidr', `mode` varchar(32) COMMENT 'How to retrieve ip address in this network', `network_offering_id` bigint unsigned NOT NULL COMMENT 'network offering id that this configuration is created from', `data_center_id` bigint unsigned NOT NULL COMMENT 'data center id that this configuration is used in', @@ -167,7 +167,7 @@ CREATE TABLE `cloud`.`nics` ( `ip_type` varchar(32) COMMENT 'type of ip', `broadcast_uri` varchar(255) COMMENT 'broadcast uri', `network_id` bigint unsigned NOT NULL COMMENT 'network configuration id', - `mode` varchar(32) COMMENT 'mode of getting ip address', + `mode` varchar(32) COMMENT 'mode of getting ip address', `state` varchar(32) NOT NULL COMMENT 'state of the creation', `strategy` varchar(32) NOT NULL COMMENT 'reservation strategy', `reserver_name` varchar(255) COMMENT 'Name of the component that reserved the ip address', @@ -176,7 +176,7 @@ CREATE TABLE `cloud`.`nics` ( `update_time` timestamp NOT NULL COMMENT 'time the state was changed', `isolation_uri` varchar(255) COMMENT 'id for isolation', `ip6_address` char(40) COMMENT 'ip6 address', - `default_nic` tinyint NOT NULL COMMENT "None", + `default_nic` tinyint NOT NULL COMMENT "None", `created` datetime NOT NULL COMMENT 'date created', `removed` datetime COMMENT 'date removed if not null', PRIMARY KEY (`id`), @@ -253,7 +253,7 @@ CREATE TABLE `cloud`.`op_host` ( `id` bigint unsigned NOT NULL UNIQUE COMMENT 'host id', `sequence` bigint unsigned DEFAULT 1 NOT NULL COMMENT 'sequence for the host communication', PRIMARY KEY (`id`), - CONSTRAINT `fk_op_host__id` FOREIGN KEY (`id`) REFERENCES `host`(`id`) ON DELETE CASCADE + CONSTRAINT `fk_op_host__id` FOREIGN KEY (`id`) REFERENCES `host`(`id`) ON DELETE CASCADE ) ENGINE = InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `cloud`.`guest_os_hypervisor` ( @@ -261,7 +261,7 @@ CREATE TABLE `cloud`.`guest_os_hypervisor` ( `hypervisor_type` varchar(32) NOT NULL, `guest_os_name` varchar(255) NOT NULL, `guest_os_id` bigint unsigned NOT NULL, - PRIMARY KEY (`id`) + PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; INSERT INTO op_host(id, sequence) select id, sequence from host; @@ -269,7 +269,7 @@ INSERT INTO op_host(id, sequence) select id, sequence from host; -- Alter Tables to add Columns; ALTER TABLE `cloud`.`cluster` ADD COLUMN `hypervisor_type` varchar(32); -UPDATE `cloud`.`cluster` SET hypervisor_type=(SELECT DISTINCT host.hypervisor_type from host where host.cluster_id = cluster.id GROUP BY host.hypervisor_type); +UPDATE `cloud`.`cluster` SET hypervisor_type=(SELECT DISTINCT host.hypervisor_type from host where host.cluster_id = cluster.id GROUP BY host.hypervisor_type); ALTER TABLE `cloud`.`volumes` ADD COLUMN `attached` datetime; UPDATE `cloud`.`volumes` SET attached=now() WHERE removed IS NULL AND instance_id IS NOT NULL; @@ -286,7 +286,7 @@ ALTER TABLE `cloud`.`vlan` ADD COLUMN `network_id` bigint unsigned NOT NULL; ALTER TABLE `cloud`.`data_center` ADD COLUMN `domain` varchar(100); ALTER TABLE `cloud`.`data_center` ADD COLUMN `domain_id` bigint unsigned; -ALTER TABLE `cloud`.`data_center` ADD COLUMN `networktype` varchar(255) NOT NULL DEFAULT 'Basic'; +ALTER TABLE `cloud`.`data_center` ADD COLUMN `networktype` varchar(255) NOT NULL DEFAULT 'Basic'; ALTER TABLE `cloud`.`data_center` ADD COLUMN `dns_provider` char(64) DEFAULT 'VirtualRouter'; ALTER TABLE `cloud`.`data_center` ADD COLUMN `gateway_provider` char(64) DEFAULT 'VirtualRouter'; ALTER TABLE `cloud`.`data_center` ADD COLUMN `firewall_provider` char(64) DEFAULT 'VirtualRouter'; @@ -306,7 +306,7 @@ UPDATE `cloud`.`op_dc_link_local_ip_address_alloc` SET reservation_id=concat(cas ALTER TABLE `cloud`.`host_pod_ref` ADD COLUMN `enabled` tinyint NOT NULL DEFAULT 1; ALTER TABLE `cloud`.`op_dc_vnet_alloc` ADD COLUMN `reservation_id` char(40) NULL; -UPDATE op_dc_vnet_alloc set reservation_id=concat(cast(data_center_id as CHAR), concat("-", vnet)) WHERE taken is NOT NULL; +UPDATE op_dc_vnet_alloc set reservation_id=concat(cast(data_center_id as CHAR), concat("-", vnet)) WHERE taken is NOT NULL; ALTER TABLE `cloud`.`vm_instance` ADD COLUMN `service_offering_id` bigint unsigned NOT NULL; ALTER TABLE `cloud`.`vm_instance` ADD COLUMN `reservation_id` char(40); @@ -326,7 +326,7 @@ ALTER TABLE `cloud`.`user_vm` ADD COLUMN `display_name` varchar(255); UPDATE user_vm inner join vm_instance on user_vm.id=vm_instance.id set user_vm.iso_id=vm_instance.iso_id, user_vm.display_name=vm_instance.display_name where vm_instance.type='User'; ALTER TABLE `cloud`.`template_host_ref` ADD COLUMN `physical_size` bigint unsigned DEFAULT 0; -UPDATE template_host_ref INNER JOIN template_spool_ref ON template_host_ref.template_id=template_spool_ref.template_id SET template_host_ref.physical_size=template_spool_ref.template_size; +UPDATE template_host_ref INNER JOIN template_spool_ref ON template_host_ref.template_id=template_spool_ref.template_id SET template_host_ref.physical_size=template_spool_ref.template_size; CREATE TABLE `cloud`.`user_vm_details` ( @@ -412,7 +412,7 @@ CREATE TABLE `cloud`.`vpn_users` ( CONSTRAINT `fk_vpn_users__owner_id` FOREIGN KEY (`owner_id`) REFERENCES `account`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_vpn_users__domain_id` FOREIGN KEY (`domain_id`) REFERENCES `domain`(`id`) ON DELETE CASCADE, INDEX `i_vpn_users_username`(`username`), - UNIQUE `i_vpn_users__account_id__username`(`owner_id`, `username`) + UNIQUE `i_vpn_users__account_id__username`(`owner_id`, `username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `cloud`.`storage_pool` ADD COLUMN `status` varchar(32); @@ -490,7 +490,7 @@ CREATE TABLE `cloud`.`usage_event` ( `resource_name` varchar(255), `offering_id` bigint unsigned, `template_id` bigint unsigned, - `size` bigint unsigned, + `size` bigint unsigned, `processed` tinyint NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-2210to2211.sql b/engine/schema/src/main/resources/META-INF/db/schema-2210to2211.sql index 01bec020d63..f352f5ef44d 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-2210to2211.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-2210to2211.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-2211to2212-premium.sql b/engine/schema/src/main/resources/META-INF/db/schema-2211to2212-premium.sql index 0cb187e2b9d..eae13acc78c 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-2211to2212-premium.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-2211to2212-premium.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-2211to2212.sql b/engine/schema/src/main/resources/META-INF/db/schema-2211to2212.sql index 94c3d75a29f..00d0fcaac76 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-2211to2212.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-2211to2212.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-2212to2213.sql b/engine/schema/src/main/resources/META-INF/db/schema-2212to2213.sql index 2e86599f792..c69809e8205 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-2212to2213.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-2212to2213.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-2213to2214.sql b/engine/schema/src/main/resources/META-INF/db/schema-2213to2214.sql index 6c0cc4b6c70..41e3944dc18 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-2213to2214.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-2213to2214.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -29,7 +29,7 @@ CREATE TABLE `cloud`.`mshost_peer` ( `peer_runid` bigint NOT NULL, `peer_state` varchar(10) NOT NULL DEFAULT 'Down', `last_update` DATETIME NULL COMMENT 'Last record update time', - + PRIMARY KEY (`id`), CONSTRAINT `fk_mshost_peer__owner_mshost` FOREIGN KEY (`owner_mshost`) REFERENCES `mshost`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_mshost_peer__peer_mshost` FOREIGN KEY (`peer_mshost`) REFERENCES `mshost`(`id`), diff --git a/engine/schema/src/main/resources/META-INF/db/schema-2214to30-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-2214to30-cleanup.sql index c90707c75b7..844280d29b6 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-2214to30-cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-2214to30-cleanup.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -22,7 +22,7 @@ ALTER TABLE `cloud_usage`.`usage_network` DROP COLUMN `current_bytes_sent`; ALTER TABLE `cloud`.`template_host_ref` DROP COLUMN `pool_id`; DELETE from `cloud`.`op_host_capacity` where capacity_type in (2,4,6); -ALTER TABLE `cloud`.`vm_instance` DROP COLUMN `private_netmask`; +ALTER TABLE `cloud`.`vm_instance` DROP COLUMN `private_netmask`; ALTER TABLE `cloud`.`security_group_rule` drop foreign key `fk_security_ingress_rule___security_group_id`; ALTER TABLE `cloud`.`security_group_rule` drop foreign key `fk_security_ingress_rule___allowed_network_id`; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-2214to30.sql b/engine/schema/src/main/resources/META-INF/db/schema-2214to30.sql index 22fda616649..8be481e4736 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-2214to30.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-2214to30.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -54,7 +54,7 @@ CREATE TABLE `cloud`.`projects` ( PRIMARY KEY (`id`), CONSTRAINT `fk_projects__project_account_id` FOREIGN KEY(`project_account_id`) REFERENCES `account`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_projects__domain_id` FOREIGN KEY(`domain_id`) REFERENCES `domain`(`id`) ON DELETE CASCADE, - INDEX `i_projects__removed`(`removed`) + INDEX `i_projects__removed`(`removed`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; @@ -177,97 +177,97 @@ ALTER TABLE `cloud`.`alert` ADD `cluster_id` bigint unsigned; ALTER TABLE `cloud`.`user_statistics` ADD COLUMN `agg_bytes_received` bigint unsigned NOT NULL default '0'; ALTER TABLE `cloud`.`user_statistics` ADD COLUMN `agg_bytes_sent` bigint unsigned NOT NULL default '0'; -ALTER TABLE `cloud`.`vm_instance` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`vm_instance` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`vm_instance` ADD CONSTRAINT `uc_vm_instance_uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`async_job` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`async_job` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`async_job` ADD CONSTRAINT `uc_async__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`domain` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`domain` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`domain` ADD CONSTRAINT `uc_domain__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`account` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`account` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`account` ADD CONSTRAINT `uc_account__uuid` UNIQUE (`uuid`); ALTER TABLE `cloud_usage`.`account` ADD COLUMN `uuid` varchar(40); -ALTER TABLE `cloud`.`user` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`user` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`user` ADD CONSTRAINT `uc_user__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`projects` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`projects` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`projects` ADD CONSTRAINT `uc_projects__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`data_center` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`data_center` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`data_center` ADD CONSTRAINT `uc_data_center__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`host` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`host` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`host` ADD CONSTRAINT `uc_host__uuid` UNIQUE (`uuid`); ALTER TABLE `cloud`.`host` ADD COLUMN `update_count` bigint unsigned NOT NULL DEFAULT 0 COMMENT 'atomic increase count making status update operation atomical'; -ALTER TABLE `cloud`.`vm_template` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`vm_template` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`vm_template` ADD CONSTRAINT `uc_vm_template__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`disk_offering` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`disk_offering` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`disk_offering` ADD CONSTRAINT `uc_disk_offering__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`networks` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`networks` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`networks` ADD CONSTRAINT `uc_networks__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`security_group` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`security_group` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`security_group` ADD CONSTRAINT `uc_security_group__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`instance_group` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`instance_group` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`instance_group` ADD CONSTRAINT `uc_instance_group__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`host_pod_ref` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`host_pod_ref` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`host_pod_ref` ADD CONSTRAINT `uc_host_pod_ref__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`snapshots` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`snapshots` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`snapshots` ADD CONSTRAINT `uc_snapshots__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`snapshot_policy` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`snapshot_policy` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`snapshot_policy` ADD CONSTRAINT `uc_snapshot_policy__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`snapshot_schedule` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`snapshot_schedule` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`snapshot_schedule` ADD CONSTRAINT `uc_snapshot_schedule__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`volumes` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`volumes` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`volumes` ADD CONSTRAINT `uc_volumes__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`vlan` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`vlan` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`vlan` ADD CONSTRAINT `uc_vlan__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`user_ip_address` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`user_ip_address` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`user_ip_address` ADD CONSTRAINT `uc_user_ip_address__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`firewall_rules` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`firewall_rules` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`firewall_rules` ADD CONSTRAINT `uc_firewall_rules__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`cluster` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`cluster` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`cluster` ADD CONSTRAINT `uc_cluster__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`network_offerings` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`network_offerings` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`network_offerings` ADD CONSTRAINT `uc_network_offerings__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`hypervisor_capabilities` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`hypervisor_capabilities` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`hypervisor_capabilities` ADD CONSTRAINT `uc_hypervisor_capabilities__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`vpn_users` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`vpn_users` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`vpn_users` ADD CONSTRAINT `uc_vpn_users__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`event` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`event` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`event` ADD CONSTRAINT `uc_event__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`alert` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`alert` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`alert` ADD CONSTRAINT `uc_alert__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`guest_os` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`guest_os` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`guest_os` ADD CONSTRAINT `uc_guest_os__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`guest_os_category` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`guest_os_category` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`guest_os_category` ADD CONSTRAINT `uc_guest_os_category__uuid` UNIQUE (`uuid`); -ALTER TABLE `cloud`.`nics` ADD COLUMN `uuid` varchar(40); +ALTER TABLE `cloud`.`nics` ADD COLUMN `uuid` varchar(40); ALTER TABLE `cloud`.`nics` ADD CONSTRAINT `uc_nics__uuid` UNIQUE (`uuid`); ALTER TABLE `cloud`.`op_host_capacity` ADD COLUMN `created` datetime; @@ -304,7 +304,7 @@ ALTER TABLE `cloud_usage`.`usage_ip_address` ADD COLUMN `is_system` smallint(1) INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Premium', 'DEFAULT', 'management-server', 'usage.sanity.check.interval', null, 'Interval (in days) to check sanity of usage data'); DELETE FROM `cloud`.`configuration` WHERE name='host.capacity.checker.wait'; -DELETE FROM `cloud`.`configuration` WHERE name='host.capacity.checker.interval'; +DELETE FROM `cloud`.`configuration` WHERE name='host.capacity.checker.interval'; INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'disable.extraction' , 'false', 'Flag for disabling extraction of template, isos and volumes'); INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'NetworkManager', 'router.check.interval' , '30', 'Interval (in seconds) to report redundant router status.'); @@ -362,9 +362,9 @@ CREATE TABLE `cloud`.`physical_network` ( `name` varchar(255) NOT NULL, `data_center_id` bigint unsigned NOT NULL COMMENT 'data center id that this physical network belongs to', `vnet` varchar(255), - `speed` varchar(32), + `speed` varchar(32), `domain_id` bigint unsigned COMMENT 'foreign key to domain id', - `broadcast_domain_range` varchar(32) NOT NULL DEFAULT 'POD' COMMENT 'range of broadcast domain : POD/ZONE', + `broadcast_domain_range` varchar(32) NOT NULL DEFAULT 'POD' COMMENT 'range of broadcast domain : POD/ZONE', `state` varchar(32) NOT NULL DEFAULT 'Disabled' COMMENT 'what state is this configuration in', `created` datetime COMMENT 'date created', `removed` datetime COMMENT 'date removed if not null', @@ -372,7 +372,7 @@ CREATE TABLE `cloud`.`physical_network` ( CONSTRAINT `fk_physical_network__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_physical_network__domain_id` FOREIGN KEY(`domain_id`) REFERENCES `domain`(`id`), CONSTRAINT `uc_physical_networks__uuid` UNIQUE (`uuid`), - INDEX `i_physical_network__removed`(`removed`) + INDEX `i_physical_network__removed`(`removed`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `cloud`.`physical_network_tags` ( @@ -690,7 +690,7 @@ CREATE TABLE `cloud_usage`.`usage_security_group` ( `vm_instance_id` bigint unsigned NOT NULL, `security_group_id` bigint unsigned NOT NULL, `created` DATETIME NOT NULL, - `deleted` DATETIME NULL + `deleted` DATETIME NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `cloud_usage`.`usage_security_group` ADD INDEX `i_usage_security_group__account_id`(`account_id`); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-221to222-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-221to222-cleanup.sql index d999b939103..5ed5f834f68 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-221to222-cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-221to222-cleanup.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-221to222-premium.sql b/engine/schema/src/main/resources/META-INF/db/schema-221to222-premium.sql index 5477fd8a348..01603a40658 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-221to222-premium.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-221to222-premium.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-221to222.sql b/engine/schema/src/main/resources/META-INF/db/schema-221to222.sql index 0c663b1ca03..d07b71fb6cb 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-221to222.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-221to222.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -23,7 +23,7 @@ update network_offerings set firewall_service=1, lb_service=1,vpn_service=1,gate alter table domain add column `state` char(32) NOT NULL default 'Active' COMMENT 'state of the domain'; alter table nics add column `vm_type` char(32); update nics set vm_type=(select type from vm_instance where vm_instance.id=nics.instance_id); -INSERT INTO configuration (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Network','DEFAULT','none','network.guest.cidr.limit','22','size limit for guest cidr; cant be less than this value'); +INSERT INTO configuration (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Network','DEFAULT','none','network.guest.cidr.limit','22','size limit for guest cidr; cant be less than this value'); alter table user_statistics add column `network_id` bigint unsigned; update op_networks set nics_count=(nics_count-1) where id in (select d.network_id from domain_router d, vm_instance i where i.state='Running' and i.id=d.id); update network_offerings set traffic_type='Guest' where system_only=0; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-222to224-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-222to224-cleanup.sql index 1bcd5d4c5f0..31f6eefb5fa 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-222to224-cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-222to224-cleanup.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-222to224-premium.sql b/engine/schema/src/main/resources/META-INF/db/schema-222to224-premium.sql index 9a5f62794c4..33d954d3a88 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-222to224-premium.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-222to224-premium.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-222to224.sql b/engine/schema/src/main/resources/META-INF/db/schema-222to224.sql index 8be64169b44..abbaf447bba 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-222to224.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-222to224.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -99,7 +99,7 @@ ALTER TABLE `cloud`.`op_host_capacity` MODIFY `used_capacity` bigint signed NOT ALTER TABLE `cloud`.`op_host_capacity` MODIFY `reserved_capacity` bigint signed NOT NULL; ALTER TABLE `cloud`.`op_host_capacity` MODIFY `total_capacity` bigint signed NOT NULL; -INSERT IGNORE INTO `cloud`.`configuration` VALUES +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced','DEFAULT','management-server','control.cidr','169.254.0.0/16','Changes the cidr for the control network traffic. Defaults to using link local. Must be unique within pods'), ('Advanced','DEFAULT','management-server','control.gateway','169.254.0.1','gateway for the control network traffic'), ('Advanced','DEFAULT','AgentManager','cmd.wait','7200','Time (in seconds) to wait for some heavy time-consuming commands'), @@ -110,7 +110,7 @@ INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Console Proxy','DEFAULT','AgentManager','consoleproxy.url.domain','realhostip.com','Console proxy url domain'), ('Advanced','DEFAULT','management-server','extract.url.cleanup.interval','120','The interval (in seconds) to wait before cleaning up the extract URL\'s '), ('Network','DEFAULT','AgentManager','guest.ip.network','10.1.1.1','The network address of the guest virtual network. Virtual machines will be assigned an IP in this subnet.'), -('Network','DEFAULT','AgentManager','guest.netmask','255.255.255.0','The netmask of the guest virtual network.'), +('Network','DEFAULT','AgentManager','guest.netmask','255.255.255.0','The netmask of the guest virtual network.'), ('Network','DEFAULT','management-server','guest.vlan.bits','12','The number of bits to reserve for the VLAN identifier in the guest subnet.'), ('Advanced','DEFAULT','management-server','host.capacity.checker.interval','3600','Time (in seconds) to wait before recalculating host\'s capacity'), ('Advanced','DEFAULT','management-server','host.capacity.checker.wait','3600','Time (in seconds) to wait before starting host capacity background checker'), @@ -175,7 +175,7 @@ ALTER TABLE `cloud`.`snapshot_schedule` ADD UNIQUE KEY `volume_id` (`volume_id` ALTER TABLE `cloud`.`storage_pool` MODIFY COLUMN `uuid` varchar(255) UNIQUE; ALTER TABLE `cloud`.`user_statistics` DROP KEY `account_id`; -ALTER TABLE `cloud`.`user_statistics` ADD UNIQUE KEY `account_id` (`account_id`,`data_center_id`, `public_ip_address`, `device_id`,`device_type`); +ALTER TABLE `cloud`.`user_statistics` ADD UNIQUE KEY `account_id` (`account_id`,`data_center_id`, `public_ip_address`, `device_id`,`device_type`); ALTER TABLE `cloud`.`usage_event` ADD INDEX `i_usage_event__created`(`created`); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-224to225-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-224to225-cleanup.sql index b018d7f280e..5f24290a1fd 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-224to225-cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-224to225-cleanup.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-224to225.sql b/engine/schema/src/main/resources/META-INF/db/schema-224to225.sql index 65334af306f..735c30a943c 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-224to225.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-224to225.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-225to226.sql b/engine/schema/src/main/resources/META-INF/db/schema-225to226.sql index ec1baae2e69..3527921af84 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-225to226.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-225to226.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-227to228-premium.sql b/engine/schema/src/main/resources/META-INF/db/schema-227to228-premium.sql index 40fcbfa6838..2e21f0c249e 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-227to228-premium.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-227to228-premium.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-227to228.sql b/engine/schema/src/main/resources/META-INF/db/schema-227to228.sql index 343c7663fd2..ac3c014894d 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-227to228.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-227to228.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -136,9 +136,9 @@ ALTER TABLE `cloud`.`vm_instance` ADD COLUMN `vm_type` varchar(32) NOT NULL; UPDATE vm_instance set vm_type=type; ALTER TABLE `cloud`.`networks` ADD COLUMN `is_domain_specific` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if network is domain specific, 0 false otherwise'; -INSERT INTO configuration (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Advanced', 'DEFAULT', 'NetworkManager', 'allow.subdomain.network.access', 'true', 'Allow subdomains to use networks dedicated to their parent domain(s)'); +INSERT INTO configuration (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Advanced', 'DEFAULT', 'NetworkManager', 'allow.subdomain.network.access', 'true', 'Allow subdomains to use networks dedicated to their parent domain(s)'); -INSERT INTO configuration (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Advanced', 'DEFAULT', 'management-server', 'encode.api.response', 'false', 'Do UTF-8 encoding for the api response, false by default'); +INSERT INTO configuration (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Advanced', 'DEFAULT', 'management-server', 'encode.api.response', 'false', 'Do UTF-8 encoding for the api response, false by default'); DELETE FROM load_balancer_vm_map WHERE instance_id IN (SELECT id FROM vm_instance WHERE removed IS NOT NULL); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-228to229.sql b/engine/schema/src/main/resources/META-INF/db/schema-228to229.sql index 9d5baa4c403..2496dd4c472 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-228to229.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-228to229.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-229to2210.sql b/engine/schema/src/main/resources/META-INF/db/schema-229to2210.sql index 9c5c46242af..1d2980f6564 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-229to2210.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-229to2210.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-22beta1to22beta2.sql b/engine/schema/src/main/resources/META-INF/db/schema-22beta1to22beta2.sql index 1b7c6a64eb0..dd03e61e17e 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-22beta1to22beta2.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-22beta1to22beta2.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-22beta3to22beta4.sql b/engine/schema/src/main/resources/META-INF/db/schema-22beta3to22beta4.sql index c73d16537ac..a93d6d5d7e5 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-22beta3to22beta4.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-22beta3to22beta4.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -83,7 +83,7 @@ CREATE TABLE `cloud`.`user_vm_details` ( `value` varchar(1024) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; - + CREATE TABLE `cloud`.`cluster_details` ( `id` bigint unsigned NOT NULL auto_increment, `cluster_id` bigint unsigned NOT NULL COMMENT 'cluster id', @@ -99,9 +99,9 @@ ALTER TABLE `cloud`.`service_offering` ADD COLUMN `host_tag` varchar(255); ALTER TABLE `cloud`.`op_it_work` change created created_at bigint unsigned NOT NULL COMMENT 'when was this work detail created'; ALTER TABLE `cloud`.`op_it_work` change state step char(32) NOT NULL COMMENT 'state'; ALTER TABLE `cloud`.`op_it_work` change cancel_taken updated_at bigint unsigned NOT NULL COMMENT 'time it was taken over'; -ALTER TABLE `cloud`.`op_it_work` ADD COLUMN `instance_id` bigint unsigned NOT NULL COMMENT 'vm instance'; -ALTER TABLE `cloud`.`op_it_work` ADD COLUMN `resource_id` bigint unsigned COMMENT 'resource id being worked on'; -ALTER TABLE `cloud`.`op_it_work` ADD COLUMN `resource_type` char(32) COMMENT 'type of resource being worked on'; +ALTER TABLE `cloud`.`op_it_work` ADD COLUMN `instance_id` bigint unsigned NOT NULL COMMENT 'vm instance'; +ALTER TABLE `cloud`.`op_it_work` ADD COLUMN `resource_id` bigint unsigned COMMENT 'resource id being worked on'; +ALTER TABLE `cloud`.`op_it_work` ADD COLUMN `resource_type` char(32) COMMENT 'type of resource being worked on'; ALTER TABLE `cloud`.`hypervsior_properties` ADD COLUMN `is_default` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if network is default'; ALTER TABLE `cloud`.`network_offerings` drop column TYPE; ALTER TABLE `cloud`.`domain_router` ADD COLUMN `host_tag` varchar(255) COMMENT 'host tag specified by the service_offering'; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-301to302-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-301to302-cleanup.sql index 7922d98ea99..d32644f471c 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-301to302-cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-301to302-cleanup.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-301to302.sql b/engine/schema/src/main/resources/META-INF/db/schema-301to302.sql index 4532757d052..99a555dedca 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-301to302.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-301to302.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -41,7 +41,7 @@ INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Hidden', 'DEFAULT', 'managem INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'network.disable.rpfilter', 'true', 'disable rp_filter on Domain Router VM public interfaces.'); INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'network.securitygroups.work.cleanup.interval', '120', 'Time interval (seconds) in which finished work is cleaned up from the work table'); INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'network.securitygroups.work.lock.timeout', '300', 'Lock wait timeout (seconds) while updating the security group work queues'); -INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'network.securitygroups.work.per.agent.queue.size', '100', +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'network.securitygroups.work.per.agent.queue.size', '100', 'The number of outstanding security group work items that can be queued to a host. If exceeded, work items will get dropped to conserve memory. Security Group Sync will take care of ensuring that the host gets updated eventually'); INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'network.securitygroups.workers.pool.size', '50', 'Number of worker threads processing the security group update work queue'); INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Hidden', 'DEFAULT', 'management-server', 'ovm.guest.network.device', null, 'Specify the private bridge on host for private network'); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-302to303.sql b/engine/schema/src/main/resources/META-INF/db/schema-302to303.sql index b475a8e9958..07faf98cf74 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-302to303.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-302to303.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -55,7 +55,7 @@ CREATE TABLE `cloud`.`volume_host_ref` ( `local_path` varchar(255), `install_path` varchar(255), `url` varchar(255), - `format` varchar(32) NOT NULL COMMENT 'format for the volume', + `format` varchar(32) NOT NULL COMMENT 'format for the volume', `destroyed` tinyint(1) COMMENT 'indicates whether the volume_host entry was destroyed by the user or not', PRIMARY KEY (`id`), CONSTRAINT `fk_volume_host_ref__host_id` FOREIGN KEY `fk_volume_host_ref__host_id` (`host_id`) REFERENCES `host` (`id`) ON DELETE CASCADE, diff --git a/engine/schema/src/main/resources/META-INF/db/schema-302to40-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-302to40-cleanup.sql index 4d89a078b2d..540c7716189 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-302to40-cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-302to40-cleanup.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-302to40.sql b/engine/schema/src/main/resources/META-INF/db/schema-302to40.sql index ca99f0106d2..47e4c3fd6d5 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-302to40.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-302to40.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -59,7 +59,7 @@ CREATE TABLE `cloud`.`volume_host_ref` ( `local_path` varchar(255), `install_path` varchar(255), `url` varchar(255), - `format` varchar(32) NOT NULL COMMENT 'format for the volume', + `format` varchar(32) NOT NULL COMMENT 'format for the volume', `destroyed` tinyint(1) COMMENT 'indicates whether the volume_host entry was destroyed by the user or not', PRIMARY KEY (`id`), CONSTRAINT `fk_volume_host_ref__host_id` FOREIGN KEY `fk_volume_host_ref__host_id` (`host_id`) REFERENCES `host` (`id`) ON DELETE CASCADE, @@ -236,9 +236,9 @@ from information_schema.key_column_usage A JOIN information_schema.key_column_usage B ON B.table_name = 'physical_network_service_providers' AND B.COLUMN_NAME = 'provider_name' AND A.COLUMN_NAME ='physical_network_id' AND B.CONSTRAINT_NAME=A.CONSTRAINT_NAME where A.table_name = 'physical_network_service_providers' LIMIT 1); -PREPARE stmt1 FROM @constraintname; -EXECUTE stmt1; -DEALLOCATE PREPARE stmt1; +PREPARE stmt1 FROM @constraintname; +EXECUTE stmt1; +DEALLOCATE PREPARE stmt1; AlTER TABLE `cloud`.`physical_network_service_providers` ADD CONSTRAINT `fk_pnetwork_service_providers__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE; UPDATE `cloud`.`configuration` SET description='In second, timeout for creating volume from snapshot' WHERE name='create.volume.from.snapshot.wait'; @@ -299,7 +299,7 @@ CREATE TABLE `cloud`.`vpc` ( PRIMARY KEY (`id`), INDEX `i_vpc__removed`(`removed`), CONSTRAINT `fk_vpc__zone_id` FOREIGN KEY `fk_vpc__zone_id` (`zone_id`) REFERENCES `data_center` (`id`) ON DELETE CASCADE, - CONSTRAINT `fk_vpc__vpc_offering_id` FOREIGN KEY (`vpc_offering_id`) REFERENCES `vpc_offerings`(`id`), + CONSTRAINT `fk_vpc__vpc_offering_id` FOREIGN KEY (`vpc_offering_id`) REFERENCES `vpc_offerings`(`id`), CONSTRAINT `fk_vpc__account_id` FOREIGN KEY `fk_vpc__account_id` (`account_id`) REFERENCES `account`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_vpc__domain_id` FOREIGN KEY `fk_vpc__domain_id` (`domain_id`) REFERENCES `domain`(`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; @@ -360,7 +360,7 @@ CREATE TABLE `cloud`.`static_routes` ( `id` bigint unsigned NOT NULL auto_increment COMMENT 'id', `uuid` varchar(40), `vpc_gateway_id` bigint unsigned COMMENT 'id of the corresponding ip address', - `cidr` varchar(18) COMMENT 'cidr for the static route', + `cidr` varchar(18) COMMENT 'cidr for the static route', `state` char(32) NOT NULL COMMENT 'current state of this rule', `vpc_id` bigint unsigned COMMENT 'vpc the firewall rule is associated with', `account_id` bigint unsigned NOT NULL COMMENT 'owner id', @@ -468,7 +468,7 @@ UPDATE `cloud`.`configuration` SET description='Comma separated list of cidrs in INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'site2site.vpn.vpngateway.connection.limit', '4', 'The maximum number of VPN connection per VPN gateway'); INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'site2site.vpn.customergateway.subnets.limit', '10', 'The maximum number of subnets per customer gateway'); -INSERT IGNORE INTO `cloud`.`guest_os_category` VALUES ('11','None',NULL); +INSERT IGNORE INTO `cloud`.`guest_os_category` VALUES ('11','None',NULL); ALTER TABLE `cloud`.`user` ADD COLUMN `incorrect_login_attempts` integer unsigned NOT NULL DEFAULT '0'; INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'incorrect.login.attempts.allowed', '5', 'Incorrect login attempts allowed before the user is disabled'); UPDATE `cloud`.`configuration` set description ='Uuid of the service offering used by console proxy; if NULL - system offering will be used' where name ='consoleproxy.service.offering'; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-304to305-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-304to305-cleanup.sql index 3b5c8f5a356..1184c98e182 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-304to305-cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-304to305-cleanup.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-304to305.sql b/engine/schema/src/main/resources/META-INF/db/schema-304to305.sql index dfeff3f683b..cb2efb3edd0 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-304to305.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-304to305.sql @@ -5,9 +5,9 @@ -- to you 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 @@ -80,7 +80,7 @@ CREATE TABLE `cloud`.`vpc` ( PRIMARY KEY (`id`), INDEX `i_vpc__removed`(`removed`), CONSTRAINT `fk_vpc__zone_id` FOREIGN KEY `fk_vpc__zone_id` (`zone_id`) REFERENCES `data_center` (`id`) ON DELETE CASCADE, - CONSTRAINT `fk_vpc__vpc_offering_id` FOREIGN KEY (`vpc_offering_id`) REFERENCES `vpc_offerings`(`id`), + CONSTRAINT `fk_vpc__vpc_offering_id` FOREIGN KEY (`vpc_offering_id`) REFERENCES `vpc_offerings`(`id`), CONSTRAINT `fk_vpc__account_id` FOREIGN KEY `fk_vpc__account_id` (`account_id`) REFERENCES `account`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_vpc__domain_id` FOREIGN KEY `fk_vpc__domain_id` (`domain_id`) REFERENCES `domain`(`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; @@ -141,7 +141,7 @@ CREATE TABLE `cloud`.`static_routes` ( `id` bigint unsigned NOT NULL auto_increment COMMENT 'id', `uuid` varchar(40), `vpc_gateway_id` bigint unsigned COMMENT 'id of the corresponding ip address', - `cidr` varchar(18) COMMENT 'cidr for the static route', + `cidr` varchar(18) COMMENT 'cidr for the static route', `state` char(32) NOT NULL COMMENT 'current state of this rule', `vpc_id` bigint unsigned COMMENT 'vpc the firewall rule is associated with', `account_id` bigint unsigned NOT NULL COMMENT 'owner id', diff --git a/engine/schema/src/main/resources/META-INF/db/schema-305to306-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-305to306-cleanup.sql index f15ad4fbc5c..850d48b6526 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-305to306-cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-305to306-cleanup.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-305to306.sql b/engine/schema/src/main/resources/META-INF/db/schema-305to306.sql index b1294a21054..e9a620bb4cc 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-305to306.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-305to306.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-306to307.sql b/engine/schema/src/main/resources/META-INF/db/schema-306to307.sql index a43833efa43..0ddee9ec5db 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-306to307.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-306to307.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-307to410.sql b/engine/schema/src/main/resources/META-INF/db/schema-307to410.sql index 944d910fec4..55d78b59437 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-307to410.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-307to410.sql @@ -22,7 +22,7 @@ SET foreign_key_checks = 0; --- DB upgrade steps from 302-40 +-- DB upgrade steps from 302-40 CREATE TABLE `cloud`.`external_nicira_nvp_devices` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', `uuid` varchar(255) UNIQUE, @@ -59,9 +59,9 @@ from information_schema.key_column_usage A JOIN information_schema.key_column_usage B ON B.table_name = 'physical_network_service_providers' AND B.COLUMN_NAME = 'provider_name' AND A.COLUMN_NAME ='physical_network_id' AND B.CONSTRAINT_NAME=A.CONSTRAINT_NAME where A.table_name = 'physical_network_service_providers' LIMIT 1); -PREPARE stmt1 FROM @constraintname; -EXECUTE stmt1; -DEALLOCATE PREPARE stmt1; +PREPARE stmt1 FROM @constraintname; +EXECUTE stmt1; +DEALLOCATE PREPARE stmt1; AlTER TABLE physical_network_service_providers ADD CONSTRAINT `fk_pnetwork_service_providers__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE; UPDATE `cloud`.`configuration` SET description='Do URL encoding for the api response, false by default' WHERE name='encode.api.response'; @@ -351,8 +351,8 @@ ALTER TABLE `cloud`.`vlan` ADD COLUMN `ip6_range` varchar(255); ALTER TABLE `cloud`.`data_center` ADD COLUMN `ip6_dns1` varchar(255); ALTER TABLE `cloud`.`data_center` ADD COLUMN `ip6_dns2` varchar(255); -UPDATE `cloud`.`networks` INNER JOIN `cloud`.`vlan` ON networks.id = vlan.network_id -SET networks.gateway = vlan.vlan_gateway, networks.ip6_gateway = vlan.ip6_gateway, networks.ip6_cidr = vlan.ip6_cidr +UPDATE `cloud`.`networks` INNER JOIN `cloud`.`vlan` ON networks.id = vlan.network_id +SET networks.gateway = vlan.vlan_gateway, networks.ip6_gateway = vlan.ip6_gateway, networks.ip6_cidr = vlan.ip6_cidr WHERE networks.data_center_id = vlan.data_center_id AND networks.physical_network_id = vlan.physical_network_id; -- DB views for list api diff --git a/engine/schema/src/main/resources/META-INF/db/schema-30to301.sql b/engine/schema/src/main/resources/META-INF/db/schema-30to301.sql index 0cc51e7d08f..81339bf2a53 100755 --- a/engine/schema/src/main/resources/META-INF/db/schema-30to301.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-30to301.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-40to410.sql b/engine/schema/src/main/resources/META-INF/db/schema-40to410.sql index 1b3a29b27a4..845b31ca04a 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-40to410.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-40to410.sql @@ -457,15 +457,15 @@ ALTER TABLE `cloud`.`vlan` ADD COLUMN `ip6_range` varchar(255); ALTER TABLE `cloud`.`data_center` ADD COLUMN `ip6_dns1` varchar(255); ALTER TABLE `cloud`.`data_center` ADD COLUMN `ip6_dns2` varchar(255); -UPDATE `cloud`.`networks` INNER JOIN `cloud`.`vlan` ON networks.id = vlan.network_id -SET networks.gateway = vlan.vlan_gateway, networks.ip6_gateway = vlan.ip6_gateway, networks.ip6_cidr = vlan.ip6_cidr +UPDATE `cloud`.`networks` INNER JOIN `cloud`.`vlan` ON networks.id = vlan.network_id +SET networks.gateway = vlan.vlan_gateway, networks.ip6_gateway = vlan.ip6_gateway, networks.ip6_cidr = vlan.ip6_cidr WHERE networks.data_center_id = vlan.data_center_id AND networks.physical_network_id = vlan.physical_network_id; -- DB views for list api DROP VIEW IF EXISTS `cloud`.`user_vm_view`; CREATE VIEW `cloud`.`user_vm_view` AS - select + select vm_instance.id id, vm_instance.name name, user_vm.display_name display_name, @@ -504,7 +504,7 @@ CREATE VIEW `cloud`.`user_vm_view` AS vm_instance.vm_type vm_type, data_center.id data_center_id, data_center.uuid data_center_uuid, - data_center.name data_center_name, + data_center.name data_center_name, data_center.is_security_group_enabled security_group_enabled, host.id host_id, host.uuid host_uuid, @@ -634,7 +634,7 @@ CREATE VIEW `cloud`.`user_vm_view` AS DROP VIEW IF EXISTS `cloud`.`domain_router_view`; CREATE VIEW `cloud`.`domain_router_view` AS - select + select vm_instance.id id, vm_instance.name name, account.id account_id, @@ -740,7 +740,7 @@ CREATE VIEW `cloud`.`domain_router_view` AS DROP VIEW IF EXISTS `cloud`.`security_group_view`; CREATE VIEW `cloud`.`security_group_view` AS - select + select security_group.id id, security_group.name name, security_group.description description, @@ -799,7 +799,7 @@ CREATE VIEW `cloud`.`security_group_view` AS DROP VIEW IF EXISTS `cloud`.`resource_tag_view`; CREATE VIEW `cloud`.`resource_tag_view` AS - select + select resource_tags.id, resource_tags.uuid, resource_tags.key, @@ -831,7 +831,7 @@ CREATE VIEW `cloud`.`resource_tag_view` AS DROP VIEW IF EXISTS `cloud`.`event_view`; CREATE VIEW `cloud`.`event_view` AS - select + select event.id, event.uuid, event.type, @@ -870,7 +870,7 @@ CREATE VIEW `cloud`.`event_view` AS DROP VIEW IF EXISTS `cloud`.`instance_group_view`; CREATE VIEW `cloud`.`instance_group_view` AS - select + select instance_group.id, instance_group.uuid, instance_group.name, @@ -898,7 +898,7 @@ CREATE VIEW `cloud`.`instance_group_view` AS DROP VIEW IF EXISTS `cloud`.`user_view`; CREATE VIEW `cloud`.`user_view` AS - select + select user.id, user.uuid, user.username, @@ -941,7 +941,7 @@ CREATE VIEW `cloud`.`user_view` AS DROP VIEW IF EXISTS `cloud`.`project_view`; CREATE VIEW `cloud`.`project_view` AS - select + select projects.id, projects.uuid, projects.name, @@ -982,7 +982,7 @@ CREATE VIEW `cloud`.`project_view` AS DROP VIEW IF EXISTS `cloud`.`project_account_view`; CREATE VIEW `cloud`.`project_account_view` AS - select + select project_account.id, account.id account_id, account.uuid account_uuid, @@ -1007,7 +1007,7 @@ CREATE VIEW `cloud`.`project_account_view` AS DROP VIEW IF EXISTS `cloud`.`project_invitation_view`; CREATE VIEW `cloud`.`project_invitation_view` AS - select + select project_invitations.id, project_invitations.uuid, project_invitations.email, @@ -1035,7 +1035,7 @@ CREATE VIEW `cloud`.`project_invitation_view` AS DROP VIEW IF EXISTS `cloud`.`host_view`; CREATE VIEW `cloud`.`host_view` AS - select + select host.id, host.uuid, host.name, @@ -1105,7 +1105,7 @@ CREATE VIEW `cloud`.`host_view` AS DROP VIEW IF EXISTS `cloud`.`volume_view`; CREATE VIEW `cloud`.`volume_view` AS - select + select volumes.id, volumes.uuid, volumes.name, @@ -1206,7 +1206,7 @@ CREATE VIEW `cloud`.`volume_view` AS DROP VIEW IF EXISTS `cloud`.`account_netstats_view`; CREATE VIEW `cloud`.`account_netstats_view` AS - SELECT + SELECT account_id, sum(net_bytes_received) + sum(current_bytes_received) as bytesReceived, sum(net_bytes_sent) + sum(current_bytes_sent) as bytesSent @@ -1217,7 +1217,7 @@ CREATE VIEW `cloud`.`account_netstats_view` AS DROP VIEW IF EXISTS `cloud`.`account_vmstats_view`; CREATE VIEW `cloud`.`account_vmstats_view` AS - SELECT + SELECT account_id, state, count(*) as vmcount from `cloud`.`vm_instance` @@ -1225,7 +1225,7 @@ CREATE VIEW `cloud`.`account_vmstats_view` AS DROP VIEW IF EXISTS `cloud`.`free_ip_view`; CREATE VIEW `cloud`.`free_ip_view` AS - select + select count(user_ip_address.id) free_ip from `cloud`.`user_ip_address` @@ -1237,7 +1237,7 @@ CREATE VIEW `cloud`.`free_ip_view` AS DROP VIEW IF EXISTS `cloud`.`account_view`; CREATE VIEW `cloud`.`account_view` AS - select + select account.id, account.uuid, account.account_name, @@ -1348,7 +1348,7 @@ CREATE VIEW `cloud`.`account_view` AS DROP VIEW IF EXISTS `cloud`.`async_job_view`; CREATE VIEW `cloud`.`async_job_view` AS - select + select account.id account_id, account.uuid account_uuid, account.account_name account_name, @@ -1457,7 +1457,7 @@ CREATE VIEW `cloud`.`async_job_view` AS DROP VIEW IF EXISTS `cloud`.`storage_pool_view`; CREATE VIEW `cloud`.`storage_pool_view` AS - select + select storage_pool.id, storage_pool.uuid, storage_pool.name, @@ -1475,7 +1475,7 @@ CREATE VIEW `cloud`.`storage_pool_view` AS cluster.cluster_type, data_center.id data_center_id, data_center.uuid data_center_uuid, - data_center.name data_center_name, + data_center.name data_center_name, host_pod_ref.id pod_id, host_pod_ref.uuid pod_uuid, host_pod_ref.name pod_name, @@ -1507,7 +1507,7 @@ CREATE VIEW `cloud`.`storage_pool_view` AS DROP VIEW IF EXISTS `cloud`.`disk_offering_view`; CREATE VIEW `cloud`.`disk_offering_view` AS - select + select disk_offering.id, disk_offering.uuid, disk_offering.name, @@ -1532,7 +1532,7 @@ CREATE VIEW `cloud`.`disk_offering_view` AS DROP VIEW IF EXISTS `cloud`.`service_offering_view`; CREATE VIEW `cloud`.`service_offering_view` AS - select + select service_offering.id, disk_offering.uuid, disk_offering.name, @@ -1563,10 +1563,10 @@ CREATE VIEW `cloud`.`service_offering_view` AS `cloud`.`disk_offering` ON service_offering.id = disk_offering.id left join `cloud`.`domain` ON disk_offering.domain_id = domain.id; - + DROP VIEW IF EXISTS `cloud`.`data_center_view`; CREATE VIEW `cloud`.`data_center_view` AS - select + select data_center.id, data_center.uuid, data_center.name, @@ -1593,8 +1593,8 @@ CREATE VIEW `cloud`.`data_center_view` AS from `cloud`.`data_center` left join - `cloud`.`domain` ON data_center.domain_id = domain.id; - + `cloud`.`domain` ON data_center.domain_id = domain.id; + CREATE TABLE `cloud`.`baremetal_dhcp_devices` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', diff --git a/engine/schema/src/main/resources/META-INF/db/schema-410to420.sql b/engine/schema/src/main/resources/META-INF/db/schema-410to420.sql index 3556e7e1b4a..35f73b35d3c 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-410to420.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-410to420.sql @@ -113,7 +113,7 @@ CREATE TABLE `cloud`.`image_store` ( `uuid` varchar(255) COMMENT 'uuid of data store', `parent` varchar(255) COMMENT 'parent path for the storage server', `created` datetime COMMENT 'date the image store first signed on', - `removed` datetime COMMENT 'date removed if not null', + `removed` datetime COMMENT 'date removed if not null', `total_size` bigint unsigned COMMENT 'storage total size statistics', `used_bytes` bigint unsigned COMMENT 'storage available bytes statistics', PRIMARY KEY(`id`) @@ -131,7 +131,7 @@ CREATE TABLE `cloud`.`image_store_details` ( DROP VIEW IF EXISTS `cloud`.`image_store_view`; CREATE VIEW `cloud`.`image_store_view` AS - select + select image_store.id, image_store.uuid, image_store.name, @@ -153,9 +153,9 @@ CREATE VIEW `cloud`.`image_store_view` AS left join `cloud`.`image_store_details` ON image_store_details.store_id = image_store.id; - + -- here we have to allow null for store_id to accommodate baremetal case to search for ready templates since template state is only stored in this table --- FK also commented out due to this +-- FK also commented out due to this CREATE TABLE `cloud`.`template_store_ref` ( `id` bigint unsigned NOT NULL auto_increment, `store_id` bigint unsigned, @@ -165,7 +165,7 @@ CREATE TABLE `cloud`.`template_store_ref` ( `job_id` varchar(255), `download_pct` int(10) unsigned, `size` bigint unsigned, - `store_role` varchar(255), + `store_role` varchar(255), `physical_size` bigint unsigned DEFAULT 0, `download_state` varchar(255), `error_str` varchar(255), @@ -177,7 +177,7 @@ CREATE TABLE `cloud`.`template_store_ref` ( `is_copy` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'indicates whether this was copied ', `update_count` bigint unsigned, `ref_cnt` bigint unsigned DEFAULT 0, - `updated` datetime, + `updated` datetime, PRIMARY KEY (`id`), -- CONSTRAINT `fk_template_store_ref__store_id` FOREIGN KEY `fk_template_store_ref__store_id` (`store_id`) REFERENCES `image_store` (`id`) ON DELETE CASCADE, INDEX `i_template_store_ref__store_id`(`store_id`), @@ -193,7 +193,7 @@ CREATE TABLE `cloud`.`template_store_ref` ( -- ALTER TABLE `cloud`.`snapshots` DROP COLUMN `sechost_id`; -- change upload host_id FK to point to image_store table -ALTER TABLE `cloud`.`upload` DROP FOREIGN KEY `fk_upload__host_id`; +ALTER TABLE `cloud`.`upload` DROP FOREIGN KEY `fk_upload__host_id`; ALTER TABLE `cloud`.`upload` ADD CONSTRAINT `fk_upload__store_id` FOREIGN KEY(`host_id`) REFERENCES `image_store` (`id`) ON DELETE CASCADE; CREATE TABLE `cloud`.`snapshot_store_ref` ( @@ -208,11 +208,11 @@ CREATE TABLE `cloud`.`snapshot_store_ref` ( `physical_size` bigint unsigned DEFAULT 0, `parent_snapshot_id` bigint unsigned DEFAULT 0, `install_path` varchar(255), - `state` varchar(255) NOT NULL, - -- `removed` datetime COMMENT 'date removed if not null', + `state` varchar(255) NOT NULL, + -- `removed` datetime COMMENT 'date removed if not null', `update_count` bigint unsigned, `ref_cnt` bigint unsigned, - `updated` datetime, + `updated` datetime, `volume_id` bigint unsigned, PRIMARY KEY (`id`), INDEX `i_snapshot_store_ref__store_id`(`store_id`), @@ -238,11 +238,11 @@ CREATE TABLE `cloud`.`volume_store_ref` ( `install_path` varchar(255), `url` varchar(255), `download_url` varchar(255), - `state` varchar(255) NOT NULL, + `state` varchar(255) NOT NULL, `destroyed` tinyint(1) COMMENT 'indicates whether the volume_host entry was destroyed by the user or not', `update_count` bigint unsigned, `ref_cnt` bigint unsigned, - `updated` datetime, + `updated` datetime, PRIMARY KEY (`id`), CONSTRAINT `fk_volume_store_ref__store_id` FOREIGN KEY `fk_volume_store_ref__store_id` (`store_id`) REFERENCES `image_store` (`id`) ON DELETE CASCADE, INDEX `i_volume_store_ref__store_id`(`store_id`), @@ -662,12 +662,12 @@ ALTER TABLE `cloud`.`remote_access_vpn` ADD COLUMN `id` bigint unsigned NOT NULL ALTER TABLE `cloud`.`remote_access_vpn` ADD COLUMN `uuid` varchar(40) UNIQUE; -- START: support for LXC - + INSERT IGNORE INTO `cloud`.`hypervisor_capabilities`(uuid, hypervisor_type, hypervisor_version, max_guests_limit, security_group_enabled) VALUES (UUID(), 'LXC', 'default', 50, 1); ALTER TABLE `cloud`.`physical_network_traffic_types` ADD COLUMN `lxc_network_label` varchar(255) DEFAULT 'cloudbr0' COMMENT 'The network name label of the physical device dedicated to this traffic on a LXC host'; - + UPDATE configuration SET value='KVM,XenServer,VMware,BareMetal,Ovm,LXC' WHERE name='hypervisor.list'; - + INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) VALUES (10, UUID(), 'routing-10', 'SystemVM Template (LXC)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://download.cloudstack.org/templates/acton/acton-systemvm-02062012.qcow2.bz2', '2755de1f9ef2ce4d6f2bee2efbb4da92', 0, 'SystemVM Template (LXC)', 'QCOW2', 15, 0, 1, 'LXC'); @@ -717,10 +717,10 @@ CREATE TABLE `cloud`.`service_offering_details` ( CONSTRAINT `fk_service_offering_details__service_offering_id` FOREIGN KEY (`service_offering_id`) REFERENCES `service_offering`(`id`) ON DELETE CASCADE, CONSTRAINT UNIQUE KEY `uk_service_offering_id_name` (`service_offering_id`, `name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; - + DROP VIEW IF EXISTS `cloud`.`user_vm_view`; CREATE VIEW `cloud`.`user_vm_view` AS - select + select vm_instance.id id, vm_instance.name name, user_vm.display_name display_name, @@ -898,7 +898,7 @@ CREATE VIEW `cloud`.`user_vm_view` AS DROP VIEW IF EXISTS `cloud`.`affinity_group_view`; CREATE VIEW `cloud`.`affinity_group_view` AS - select + select affinity_group.id id, affinity_group.name name, affinity_group.type type, @@ -933,7 +933,7 @@ CREATE VIEW `cloud`.`affinity_group_view` AS DROP VIEW IF EXISTS `cloud`.`host_view`; CREATE VIEW `cloud`.`host_view` AS - select + select host.id, host.uuid, host.name, @@ -1001,10 +1001,10 @@ CREATE VIEW `cloud`.`host_view` AS `cloud`.`async_job` ON async_job.instance_id = host.id and async_job.instance_type = 'Host' and async_job.job_status = 0; - + DROP VIEW IF EXISTS `cloud`.`storage_pool_view`; CREATE VIEW `cloud`.`storage_pool_view` AS - select + select storage_pool.id, storage_pool.uuid, storage_pool.name, @@ -1024,7 +1024,7 @@ CREATE VIEW `cloud`.`storage_pool_view` AS cluster.cluster_type, data_center.id data_center_id, data_center.uuid data_center_uuid, - data_center.name data_center_name, + data_center.name data_center_name, data_center.networktype data_center_type, host_pod_ref.id pod_id, host_pod_ref.uuid pod_uuid, @@ -1054,11 +1054,11 @@ CREATE VIEW `cloud`.`storage_pool_view` AS `cloud`.`async_job` ON async_job.instance_id = storage_pool.id and async_job.instance_type = 'StoragePool' and async_job.job_status = 0; - + DROP VIEW IF EXISTS `cloud`.`domain_router_view`; CREATE VIEW `cloud`.`domain_router_view` AS - select + select vm_instance.id id, vm_instance.name name, account.id account_id, @@ -1157,7 +1157,7 @@ CREATE VIEW `cloud`.`domain_router_view` AS `cloud`.`async_job` ON async_job.instance_id = vm_instance.id and async_job.instance_type = 'DomainRouter' and async_job.job_status = 0; - + CREATE TABLE `cloud`.`external_cisco_vnmc_devices` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', `uuid` varchar(255) UNIQUE, @@ -1242,7 +1242,7 @@ INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'manag DROP VIEW IF EXISTS `cloud`.`service_offering_view`; CREATE VIEW `cloud`.`service_offering_view` AS - select + select service_offering.id, disk_offering.uuid, disk_offering.name, @@ -1289,7 +1289,7 @@ UPDATE `cloud_usage`.`account` SET `default`=1 WHERE id IN (1,2); UPDATE `cloud`.`user` SET `cloud`.`user`.`default`=1 WHERE id IN (1,2); CREATE OR REPLACE VIEW `cloud`.`user_view` AS - select + select user.id, user.uuid, user.username, @@ -1329,7 +1329,7 @@ CREATE OR REPLACE VIEW `cloud`.`user_view` AS `cloud`.`async_job` ON async_job.instance_id = user.id and async_job.instance_type = 'User' and async_job.job_status = 0; - + DROP VIEW IF EXISTS `cloud`.`account_view`; CREATE VIEW `cloud`.`account_view` AS @@ -1879,7 +1879,7 @@ ALTER TABLE `cloud`.`account_details` MODIFY value varchar(255); DROP VIEW IF EXISTS `cloud`.`template_view`; CREATE VIEW `cloud`.`template_view` AS - select + select vm_template.id, vm_template.uuid, vm_template.unique_name, @@ -1920,7 +1920,7 @@ CREATE VIEW `cloud`.`template_view` AS domain.path domain_path, projects.id project_id, projects.uuid project_uuid, - projects.name project_name, + projects.name project_name, data_center.id data_center_id, data_center.uuid data_center_uuid, data_center.name data_center_name, @@ -1950,23 +1950,23 @@ CREATE VIEW `cloud`.`template_view` AS from `cloud`.`vm_template` inner join - `cloud`.`guest_os` ON guest_os.id = vm_template.guest_os_id + `cloud`.`guest_os` ON guest_os.id = vm_template.guest_os_id inner join `cloud`.`account` ON account.id = vm_template.account_id inner join `cloud`.`domain` ON domain.id = account.domain_id left join - `cloud`.`projects` ON projects.project_account_id = account.id + `cloud`.`projects` ON projects.project_account_id = account.id left join - `cloud`.`vm_template_details` ON vm_template_details.template_id = vm_template.id + `cloud`.`vm_template_details` ON vm_template_details.template_id = vm_template.id left join - `cloud`.`vm_template` source_template ON source_template.id = vm_template.source_template_id + `cloud`.`vm_template` source_template ON source_template.id = vm_template.source_template_id left join `cloud`.`template_store_ref` ON template_store_ref.template_id = vm_template.id and template_store_ref.store_role = 'Image' left join - `cloud`.`image_store` ON image_store.removed is NULL AND template_store_ref.store_id is not NULL AND image_store.id = template_store_ref.store_id + `cloud`.`image_store` ON image_store.removed is NULL AND template_store_ref.store_id is not NULL AND image_store.id = template_store_ref.store_id left join - `cloud`.`template_zone_ref` ON template_zone_ref.template_id = vm_template.id AND template_store_ref.store_id is NULL AND template_zone_ref.removed is null + `cloud`.`template_zone_ref` ON template_zone_ref.template_id = vm_template.id AND template_store_ref.store_id is NULL AND template_zone_ref.removed is null left join `cloud`.`data_center` ON (image_store.data_center_id = data_center.id OR template_zone_ref.zone_id = data_center.id) left join @@ -1974,7 +1974,7 @@ CREATE VIEW `cloud`.`template_view` AS left join `cloud`.`resource_tags` ON resource_tags.resource_id = vm_template.id and (resource_tags.resource_type = 'Template' or resource_tags.resource_type='ISO'); - + INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'midonet.apiserver.address', 'http://localhost:8081', 'Specify the address at which the Midonet API server can be contacted (if using Midonet)'); INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'midonet.providerrouter.id', 'd7c5e6a3-e2f4-426b-b728-b7ce6a0448e5', 'Specifies the UUID of the Midonet provider router (if using Midonet)'); @@ -1996,7 +1996,7 @@ CREATE TABLE `cloud`.`account_vnet_map` ( ALTER TABLE `cloud`.`op_dc_vnet_alloc` ADD COLUMN account_vnet_map_id bigint unsigned; ALTER TABLE `cloud`.`op_dc_vnet_alloc` ADD CONSTRAINT `fk_op_dc_vnet_alloc__account_vnet_map_id` FOREIGN KEY `fk_op_dc_vnet_alloc__account_vnet_map_id` (`account_vnet_map_id`) REFERENCES `account_vnet_map` (`id`); - + update `cloud`.`vm_template` set state='Allocated' where state is NULL; update `cloud`.`vm_template` set update_count=0 where update_count is NULL; @@ -2100,7 +2100,7 @@ CREATE TABLE `cloud`.`vm_disk_statistics` ( CONSTRAINT `fk_vm_disk_statistics__account_id` FOREIGN KEY (`account_id`) REFERENCES `account` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; -insert into `cloud`.`vm_disk_statistics`(data_center_id,account_id,vm_id,volume_id) +insert into `cloud`.`vm_disk_statistics`(data_center_id,account_id,vm_id,volume_id) select volumes.data_center_id, volumes.account_id, vm_instance.id, volumes.id from volumes,vm_instance where vm_instance.vm_type="User" and vm_instance.state<>"Expunging" and volumes.instance_id=vm_instance.id order by vm_instance.id; DROP TABLE IF EXISTS `cloud`.`ovs_providers`; @@ -2166,7 +2166,7 @@ INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'manag INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'vm.disk.throttling.bytes_write_rate', 0, 'Default disk I/O write rate in bytes per second allowed in User vm\'s disk. '); -- Re-enable foreign key checking, at the end of the upgrade path -SET foreign_key_checks = 1; +SET foreign_key_checks = 1; UPDATE `cloud`.`snapshot_policy` set uuid=id WHERE uuid is NULL; #update shared sg enabled network with not null name in Advance Security Group enabled network @@ -2220,7 +2220,7 @@ CREATE TABLE `cloud`.`external_stratosphere_ssp_credentials` ( DROP VIEW IF EXISTS `cloud`.`project_view`; CREATE VIEW `cloud`.`project_view` AS - select + select projects.id, projects.uuid, projects.name, @@ -2264,7 +2264,7 @@ INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'manage ALTER TABLE `cloud`.`network_offerings` ADD COLUMN `concurrent_connections` int(10) unsigned COMMENT 'Load Balancer(haproxy) maximum number of concurrent connections(global max)'; - + ALTER TABLE `cloud`.`sync_queue` MODIFY `queue_size` smallint(6) NOT NULL DEFAULT '0' COMMENT 'number of items being processed by the queue'; ALTER TABLE `cloud`.`sync_queue` MODIFY `queue_size_limit` smallint(6) NOT NULL DEFAULT '1' COMMENT 'max number of items the queue can process concurrently'; @@ -2280,7 +2280,7 @@ INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'manag #update the account_vmstats_view - count only user vms DROP VIEW IF EXISTS `cloud`.`account_vmstats_view`; CREATE VIEW `cloud`.`account_vmstats_view` AS - SELECT + SELECT account_id, state, count(*) as vmcount from `cloud`.`vm_instance` @@ -2329,7 +2329,7 @@ INSERT IGNORE INTO `cloud`.`configuration` VALUES ("Advanced", 'DEFAULT', 'manag DROP VIEW IF EXISTS `cloud`.`data_center_view`; CREATE VIEW `cloud`.`data_center_view` AS - select + select data_center.id, data_center.uuid, data_center.name, diff --git a/engine/schema/src/main/resources/META-INF/db/schema-41310to41400.sql b/engine/schema/src/main/resources/META-INF/db/schema-41310to41400.sql index fbbf0a2aef8..603e7712ebc 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-41310to41400.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-41310to41400.sql @@ -19,7 +19,7 @@ -- Schema upgrade from 4.13.1.0 to 4.14.0.0 --; --- Update the description to indicate this only works with KVM + Ceph +-- Update the description to indicate this only works with KVM + Ceph -- (not implemented properly atm for KVM+NFS/local, and it accidentally works with XS + NFS. Not applicable for VMware) UPDATE `cloud`.`configuration` SET `description`='Indicates whether to always backup primary storage snapshot to secondary storage. Keeping snapshots only on Primary storage is applicable for KVM + Ceph only.' WHERE `name`='snapshot.backup.to.secondary'; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-41910to42000-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-41910to42000-cleanup.sql new file mode 100644 index 00000000000..4bbeadaf811 --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/schema-41910to42000-cleanup.sql @@ -0,0 +1,20 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. + +--; +-- Schema upgrade cleanup from 4.19.0.0 to 4.20.0.0 +--; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-41910to42000.sql b/engine/schema/src/main/resources/META-INF/db/schema-41910to42000.sql new file mode 100644 index 00000000000..eec4ac3f028 --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/schema-41910to42000.sql @@ -0,0 +1,427 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. + +--; +-- Schema upgrade from 4.19.0.0 to 4.20.0.0 +--; + +-- Add tag column to tables +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.resource_limit', 'tag', 'varchar(64) DEFAULT NULL COMMENT "tag for the limit" '); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.resource_count', 'tag', 'varchar(64) DEFAULT NULL COMMENT "tag for the resource count" '); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.resource_reservation', 'tag', 'varchar(64) DEFAULT NULL COMMENT "tag for the resource reservation" '); +CALL `cloud`.`IDEMPOTENT_DROP_INDEX`('i_resource_count__type_accountId', 'cloud.resource_count'); +CALL `cloud`.`IDEMPOTENT_DROP_INDEX`('i_resource_count__type_domaintId', 'cloud.resource_count'); + +DROP PROCEDURE IF EXISTS `cloud`.`IDEMPOTENT_ADD_UNIQUE_INDEX`; +CREATE PROCEDURE `cloud`.`IDEMPOTENT_ADD_UNIQUE_INDEX` ( + IN in_table_name VARCHAR(200), + IN in_index_name VARCHAR(200), + IN in_index_definition VARCHAR(1000) +) +BEGIN + DECLARE CONTINUE HANDLER FOR 1061 BEGIN END; SET @ddl = CONCAT('ALTER TABLE ', in_table_name, ' ', 'ADD UNIQUE INDEX ', in_index_name, ' ', in_index_definition); PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt; END; + +CALL `cloud`.`IDEMPOTENT_ADD_UNIQUE_INDEX`('cloud.resource_count', 'i_resource_count__type_tag_accountId', '(type, tag, account_id)'); +CALL `cloud`.`IDEMPOTENT_ADD_UNIQUE_INDEX`('cloud.resource_count', 'i_resource_count__type_tag_domainId', '(type, tag, domain_id)'); + +ALTER TABLE `cloud`.`resource_reservation` + MODIFY COLUMN `amount` bigint NOT NULL; + +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.resource_reservation', 'resource_id', 'bigint unsigned NULL COMMENT "id of the resource" '); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.resource_reservation', 'mgmt_server_id', 'bigint unsigned NULL COMMENT "management server id" '); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.resource_reservation', 'created', 'datetime DEFAULT NULL COMMENT "date when the reservation was created" '); + +UPDATE `cloud`.`resource_reservation` SET `created` = now() WHERE created IS NULL; + + +-- Update Default System offering for Router to 512MiB +UPDATE `cloud`.`service_offering` SET ram_size = 512 WHERE unique_name IN ("Cloud.Com-SoftwareRouter", "Cloud.Com-SoftwareRouter-Local", + "Cloud.Com-InternalLBVm", "Cloud.Com-InternalLBVm-Local", + "Cloud.Com-ElasticLBVm", "Cloud.Com-ElasticLBVm-Local") + AND system_use = 1 AND ram_size < 512; + +-- NSX Plugin -- +CREATE TABLE IF NOT EXISTS `cloud`.`nsx_providers` ( + `id` bigint unsigned NOT NULL auto_increment COMMENT 'id', + `uuid` varchar(40), + `zone_id` bigint unsigned NOT NULL COMMENT 'Zone ID', + `host_id` bigint unsigned NOT NULL COMMENT 'Host ID', + `provider_name` varchar(40), + `hostname` varchar(255) NOT NULL, + `port` varchar(255), + `username` varchar(255) NOT NULL, + `password` varchar(255) NOT NULL, + `tier0_gateway` varchar(255), + `edge_cluster` varchar(255), + `transport_zone` varchar(255), + `created` datetime NOT NULL COMMENT 'date created', + `removed` datetime COMMENT 'date removed if not null', + PRIMARY KEY (`id`), + CONSTRAINT `fk_nsx_providers__zone_id` FOREIGN KEY `fk_nsx_providers__zone_id` (`zone_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE, + INDEX `i_nsx_providers__zone_id`(`zone_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- NSX Plugin -- +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.network_offerings','for_nsx', 'int(1) unsigned DEFAULT "0" COMMENT "is nsx enabled for the resource"'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.network_offerings','nsx_mode', 'varchar(32) COMMENT "mode in which the network would route traffic"'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.vpc_offerings','for_nsx', 'int(1) unsigned DEFAULT "0" COMMENT "is nsx enabled for the resource"'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.vpc_offerings','nsx_mode', 'varchar(32) COMMENT "mode in which the network would route traffic"'); + +-- Create table to persist quota email template configurations +CREATE TABLE IF NOT EXISTS `cloud_usage`.`quota_email_configuration`( + `account_id` int(11) NOT NULL, + `email_template_id` bigint(20) NOT NULL, + `enabled` int(1) UNSIGNED NOT NULL, + PRIMARY KEY (`account_id`, `email_template_id`), + CONSTRAINT `FK_quota_email_configuration_account_id` FOREIGN KEY (`account_id`) REFERENCES `cloud_usage`.`quota_account`(`account_id`), + CONSTRAINT `FK_quota_email_configuration_email_template_id` FOREIGN KEY (`email_template_id`) REFERENCES `cloud_usage`.`quota_email_templates`(`id`)); + +-- Remove on delete cascade from snapshot schedule +ALTER TABLE `cloud`.`snapshot_schedule` DROP CONSTRAINT `fk__snapshot_schedule_async_job_id`; + +-- Add `is_implicit` column to `host_tags` table +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.host_tags', 'is_implicit', 'int(1) UNSIGNED NOT NULL DEFAULT 0 COMMENT "If host tag is implicit or explicit" '); + +-- Fields related to Snapshot Extraction +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.snapshot_store_ref', 'download_url', 'varchar(2048) DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.snapshot_store_ref', 'download_url_created', 'datetime DEFAULT NULL'); + +-- Webhooks feature +DROP TABLE IF EXISTS `cloud`.`webhook`; +CREATE TABLE `cloud`.`webhook` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id of the webhook', + `uuid` varchar(255) COMMENT 'uuid of the webhook', + `name` varchar(255) NOT NULL COMMENT 'name of the webhook', + `description` varchar(4096) COMMENT 'description for the webhook', + `state` char(32) NOT NULL COMMENT 'state of the webhook - Enabled or Disabled', + `domain_id` bigint unsigned NOT NULL COMMENT 'id of the owner domain of the webhook', + `account_id` bigint unsigned NOT NULL COMMENT 'id of the owner account of the webhook', + `payload_url` varchar(255) COMMENT 'payload URL for the webhook', + `secret_key` varchar(255) COMMENT 'secret key for the webhook', + `ssl_verification` boolean COMMENT 'for https payload url, if true then strict ssl verification', + `scope` char(32) NOT NULL COMMENT 'scope for the webhook - Local, Domain, Global', + `created` datetime COMMENT 'date the webhook was created', + `removed` datetime COMMENT 'date removed if not null', + PRIMARY KEY(`id`), + INDEX `i_webhook__account_id`(`account_id`), + CONSTRAINT `fk_webhook__account_id` FOREIGN KEY (`account_id`) REFERENCES `account`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +DROP TABLE IF EXISTS `cloud`.`webhook_delivery`; +CREATE TABLE `cloud`.`webhook_delivery` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id of the webhook delivery', + `uuid` varchar(255) COMMENT 'uuid of the webhook', + `event_id` bigint unsigned NOT NULL COMMENT 'id of the event', + `webhook_id` bigint unsigned NOT NULL COMMENT 'id of the webhook', + `mshost_msid` bigint unsigned NOT NULL COMMENT 'msid of the management server', + `headers` TEXT COMMENT 'headers for the webhook delivery', + `payload` TEXT COMMENT 'payload for the webhook delivery', + `success` boolean COMMENT 'webhook delivery succeeded or not', + `response` TEXT COMMENT 'response of the webhook delivery', + `start_time` datetime COMMENT 'start timestamp of the webhook delivery', + `end_time` datetime COMMENT 'end timestamp of the webhook delivery', + PRIMARY KEY(`id`), + INDEX `i_webhook__event_id`(`event_id`), + INDEX `i_webhook__webhook_id`(`webhook_id`), + CONSTRAINT `fk_webhook__event_id` FOREIGN KEY (`event_id`) REFERENCES `event`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_webhook__webhook_id` FOREIGN KEY (`webhook_id`) REFERENCES `webhook`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- Normalize quota.usage.smtp.useStartTLS, quota.usage.smtp.useAuth, alert.smtp.useAuth and project.smtp.useAuth values +UPDATE + `cloud`.`configuration` +SET + value = "true" +WHERE + name IN ("quota.usage.smtp.useStartTLS", "quota.usage.smtp.useAuth", "alert.smtp.useAuth", "project.smtp.useAuth") + AND value IN ("true", "y", "t", "1", "on", "yes"); + +UPDATE + `cloud`.`configuration` +SET + value = "false" +WHERE + name IN ("quota.usage.smtp.useStartTLS", "quota.usage.smtp.useAuth", "alert.smtp.useAuth", "project.smtp.useAuth") + AND value NOT IN ("true", "y", "t", "1", "on", "yes"); + +-- Create tables for static and dynamic routing +CREATE TABLE `cloud`.`dc_ip4_guest_subnets` ( + `id` bigint unsigned NOT NULL auto_increment COMMENT 'id', + `uuid` varchar(40) DEFAULT NULL, + `data_center_id` bigint(20) unsigned NOT NULL COMMENT 'zone it belongs to', + `subnet` varchar(255) NOT NULL COMMENT 'subnet of the ip4 network', + `domain_id` bigint unsigned DEFAULT NULL COMMENT 'domain the subnet belongs to', + `account_id` bigint unsigned DEFAULT NULL COMMENT 'owner of this subnet', + `created` datetime DEFAULT NULL, + `removed` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `fk_dc_ip4_guest_subnets__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center`(`id`), + CONSTRAINT `fk_dc_ip4_guest_subnets__domain_id` FOREIGN KEY (`domain_id`) REFERENCES `domain`(`id`), + CONSTRAINT `fk_dc_ip4_guest_subnets__account_id` FOREIGN KEY (`account_id`) REFERENCES `account`(`id`), + CONSTRAINT `uc_dc_ip4_guest_subnets__uuid` UNIQUE (`uuid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`ip4_guest_subnet_network_map` ( + `id` bigint unsigned NOT NULL auto_increment COMMENT 'id', + `uuid` varchar(40) DEFAULT NULL, + `parent_id` bigint(20) unsigned COMMENT 'ip4 guest subnet which subnet belongs to', + `subnet` varchar(255) NOT NULL COMMENT 'subnet of the ip4 network', + `network_id` bigint(20) unsigned DEFAULT NULL COMMENT 'network which subnet is associated to', + `vpc_id` bigint(20) unsigned DEFAULT NULL COMMENT 'VPC which subnet is associated to', + `state` varchar(255) NOT NULL COMMENT 'state of the subnet', + `allocated` datetime DEFAULT NULL, + `created` datetime DEFAULT NULL, + `removed` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `fk_ip4_guest_subnet_network_map__parent_id` FOREIGN KEY (`parent_id`) REFERENCES `dc_ip4_guest_subnets`(`id`), + CONSTRAINT `fk_ip4_guest_subnet_network_map__network_id` FOREIGN KEY (`network_id`) REFERENCES `networks`(`id`), + CONSTRAINT `fk_ip4_guest_subnet_network_map__vpc_id` FOREIGN KEY (`vpc_id`) REFERENCES `vpc`(`id`), + CONSTRAINT `uc_ip4_guest_subnet_network_map__uuid` UNIQUE (`uuid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CALL `cloud`.`IDEMPOTENT_CHANGE_COLUMN`('network_offerings', 'nsx_mode', 'network_mode', 'varchar(32) COMMENT "mode in which the network would route traffic"'); +CALL `cloud`.`IDEMPOTENT_CHANGE_COLUMN`('vpc_offerings', 'nsx_mode', 'network_mode', 'varchar(32) COMMENT "mode in which the network would route traffic"'); +ALTER TABLE `cloud`.`event` MODIFY COLUMN `type` varchar(50) NOT NULL; + +-- Add tables for AS Numbers and range +CREATE TABLE IF NOT EXISTS `cloud`.`as_number_range` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT, + `uuid` varchar(40) DEFAULT NULL, + `data_center_id` bigint unsigned NOT NULL COMMENT 'zone that it belongs to', + `start_as_number` bigint unsigned NOT NULL COMMENT 'start AS number of the range', + `end_as_number` bigint unsigned NOT NULL COMMENT 'end AS number of the range', + `created` datetime DEFAULT NULL COMMENT 'date created', + `removed` datetime DEFAULT NULL COMMENT 'date removed', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_as_number_range__uuid` (`uuid`), + UNIQUE KEY `uk_as_number_range__range` (`data_center_id`,`start_as_number`,`end_as_number`, `removed`), + CONSTRAINT `fk_as_number_range__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `cloud`.`as_number` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT, + `uuid` varchar(40) DEFAULT NULL, + `account_id` bigint unsigned DEFAULT NULL, + `domain_id` bigint unsigned DEFAULT NULL, + `as_number` bigint unsigned NOT NULL COMMENT 'the AS Number', + `as_number_range_id` bigint unsigned NOT NULL, + `data_center_id` bigint unsigned NOT NULL COMMENT 'zone that it belongs to', + `allocated` datetime DEFAULT NULL COMMENT 'Date this AS Number was allocated to some network', + `is_allocated` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'indicates if the AS Number is allocated to some network', + `network_id` bigint unsigned DEFAULT NULL COMMENT 'Network this AS Number is associated with', + `vpc_id` bigint unsigned DEFAULT NULL COMMENT 'VPC this AS Number is associated with', + `created` datetime DEFAULT NULL COMMENT 'date created', + `removed` datetime DEFAULT NULL COMMENT 'date removed', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_as_number__uuid` (`uuid`), + UNIQUE KEY `uk_as_number__number` (`data_center_id`,`as_number`,`as_number_range_id`), + CONSTRAINT `fk_as_number__account_id` FOREIGN KEY (`account_id`) REFERENCES `account` (`id`), + CONSTRAINT `fk_as_number__data_center_id` FOREIGN KEY (`data_center_id`) REFERENCES `data_center` (`id`) ON DELETE CASCADE, + CONSTRAINT `fk_as_number__network_id` FOREIGN KEY (`network_id`) REFERENCES `networks` (`id`), + CONSTRAINT `fk_as_number__as_number_range_id` FOREIGN KEY (`as_number_range_id`) REFERENCES `as_number_range` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.network_offerings','routing_mode', 'varchar(10) COMMENT "routing mode for the offering"'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.network_offerings','specify_as_number', 'tinyint(1) NOT NULL DEFAULT 0 COMMENT "specify AS number when using dynamic routing"'); + +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.vpc_offerings','routing_mode', 'varchar(10) COMMENT "routing mode for the offering"'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.vpc_offerings','specify_as_number', 'tinyint(1) NOT NULL DEFAULT 0 COMMENT "specify AS number when using dynamic routing"'); + +-- Tables for Dynamic Routing +CREATE TABLE IF NOT EXISTS `cloud`.`bgp_peers` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT, + `uuid` varchar(40) DEFAULT NULL, + `data_center_id` bigint(20) unsigned NOT NULL COMMENT 'zone it belongs to', + `ip4_address` varchar(40) DEFAULT NULL COMMENT 'IPv4 address of the BGP peer', + `ip6_address` varchar(40) DEFAULT NULL COMMENT 'IPv6 address of the BGP peer', + `as_number` bigint unsigned NOT NULL COMMENT 'AS number of the BGP peer', + `password` varchar(255) DEFAULT NULL COMMENT 'Password of the BGP peer', + `domain_id` bigint unsigned DEFAULT NULL COMMENT 'domain the subnet belongs to', + `account_id` bigint unsigned DEFAULT NULL COMMENT 'owner of this subnet', + `created` datetime DEFAULT NULL COMMENT 'date created', + `removed` datetime DEFAULT NULL COMMENT 'date removed', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_bgp_peers__uuid` (`uuid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`bgp_peer_details` ( + `id` bigint unsigned NOT NULL auto_increment, + `bgp_peer_id` bigint unsigned NOT NULL COMMENT 'bgp peer id', + `name` varchar(255) NOT NULL, + `value` varchar(1024) NOT NULL, + `display` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'True if the detail can be displayed to the end user', + PRIMARY KEY (`id`), + CONSTRAINT `fk_bgp_peer_details__bgp_peer_id` FOREIGN KEY `fk_bgp_peer_details__bgp_peer_id`(`bgp_peer_id`) REFERENCES `bgp_peers`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `cloud`.`bgp_peer_network_map` ( + `id` bigint unsigned NOT NULL auto_increment COMMENT 'id', + `bgp_peer_id` bigint(20) unsigned COMMENT 'id of the BGP peer', + `network_id` bigint(20) unsigned DEFAULT NULL COMMENT 'network which BGP peer is associated to', + `vpc_id` bigint(20) unsigned DEFAULT NULL COMMENT 'vpc which BGP peer is associated to', + `state` varchar(40) DEFAULT NULL, + `created` datetime DEFAULT NULL COMMENT 'date created', + `removed` datetime DEFAULT NULL COMMENT 'date removed', + PRIMARY KEY (`id`), + CONSTRAINT `fk_bgp_peer_network_map__bgp_peer_id` FOREIGN KEY (`bgp_peer_id`) REFERENCES `bgp_peers`(`id`), + CONSTRAINT `fk_bgp_peer_network_map__network_id` FOREIGN KEY (`network_id`) REFERENCES `networks`(`id`), + CONSTRAINT `fk_bgp_peer_network_map__vpc_id` FOREIGN KEY (`vpc_id`) REFERENCES `vpc`(`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`shared_filesystem`( + `id` bigint unsigned NOT NULL auto_increment COMMENT 'ID', + `uuid` varchar(40) COMMENT 'UUID', + `name` varchar(255) NOT NULL COMMENT 'Name of the shared filesystem', + `description` varchar(1024) COMMENT 'Description', + `domain_id` bigint unsigned NOT NULL COMMENT 'Domain ID', + `account_id` bigint unsigned NOT NULL COMMENT 'Account ID', + `data_center_id` bigint unsigned NOT NULL COMMENT 'Data center ID', + `state` varchar(12) NOT NULL COMMENT 'State of the shared filesystem in the FSM', + `fs_provider_name` varchar(255) COMMENT 'Name of the shared filesystem provider', + `protocol` varchar(10) COMMENT 'Protocol supported by the shared filesystem', + `volume_id` bigint unsigned COMMENT 'Volume which the shared filesystem is using as storage', + `vm_id` bigint unsigned COMMENT 'vm on which the shared filesystem is hosted', + `fs_type` varchar(10) NOT NULL COMMENT 'The filesystem format to be used for the shared filesystem', + `service_offering_id` bigint unsigned COMMENT 'Service offering for the vm', + `update_count` bigint unsigned COMMENT 'Update count for state change', + `updated` datetime COMMENT 'date updated', + `created` datetime NOT NULL COMMENT 'date created', + `removed` datetime COMMENT 'date removed if not null', + PRIMARY KEY (`id`), + CONSTRAINT `uc_shared_filesystem__uuid` UNIQUE (`uuid`), + INDEX `i_shared_filesystem__account_id`(`account_id`), + INDEX `i_shared_filesystem__domain_id`(`domain_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- Quota inject tariff result into subsequent ones +CALL `cloud_usage`.`IDEMPOTENT_ADD_COLUMN`('cloud_usage.quota_tariff', 'position', 'bigint(20) NOT NULL DEFAULT 1 COMMENT "Position in the execution sequence for tariffs of the same type"'); + +-- Idempotent IDEMPOTENT_MODIFY_COLUMN_CHAR_SET +DROP PROCEDURE IF EXISTS `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`; +CREATE PROCEDURE `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET` ( + IN in_table_name VARCHAR(200) +, IN in_column_name VARCHAR(200) +, IN in_column_type VARCHAR(200) +, IN in_column_definition VARCHAR(1000) +) +BEGIN + DECLARE CONTINUE HANDLER FOR 1060 BEGIN END; SET @ddl = CONCAT('ALTER TABLE ', in_table_name); SET @ddl = CONCAT(@ddl, ' ', ' MODIFY COLUMN') ; SET @ddl = CONCAT(@ddl, ' ', in_column_name); SET @ddl = CONCAT(@ddl, ' ', in_column_type); SET @ddl = CONCAT(@ddl, ' ', ' CHARACTER SET utf8mb4'); SET @ddl = CONCAT(@ddl, ' ', in_column_definition); PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt; END; + +DROP PROCEDURE IF EXISTS `cloud_usage`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`; +CREATE PROCEDURE `cloud_usage`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET` ( + IN in_table_name VARCHAR(200) +, IN in_column_name VARCHAR(200) +, IN in_column_type VARCHAR(200) +, IN in_column_definition VARCHAR(1000) +) +BEGIN + DECLARE CONTINUE HANDLER FOR 1060 BEGIN END; SET @ddl = CONCAT('ALTER TABLE ', in_table_name); SET @ddl = CONCAT(@ddl, ' ', ' MODIFY COLUMN') ; SET @ddl = CONCAT(@ddl, ' ', in_column_name); SET @ddl = CONCAT(@ddl, ' ', in_column_type); SET @ddl = CONCAT(@ddl, ' ', ' CHARACTER SET utf8mb4'); SET @ddl = CONCAT(@ddl, ' ', in_column_definition); PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt; END; + +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('async_job', 'job_result', 'TEXT', 'COMMENT \'job result info\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('async_job', 'job_cmd_info', 'TEXT', 'COMMENT \'command parameter info\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('event', 'description', 'VARCHAR(1024)', 'NOT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('usage_event', 'resource_name', 'VARCHAR(255)', 'DEFAULT NULL'); +CALL `cloud_usage`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('usage_event', 'resource_name', 'VARCHAR(255)', 'DEFAULT NULL'); + +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('account', 'account_name', 'VARCHAR(100)', 'DEFAULT NULL COMMENT \'an account name set by the creator of the account, defaults to username for single accounts\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('affinity_group', 'description', 'VARCHAR(4096)', 'DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('annotations', 'annotation', 'TEXT', ''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('autoscale_vmgroups', 'name', 'VARCHAR(255)', 'DEFAULT NULL COMMENT \'name of the autoscale vm group\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('backup_offering', 'name', 'VARCHAR(255)', 'NOT NULL COMMENT \'backup offering name\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('backup_offering', 'description', 'VARCHAR(255)', 'NOT NULL COMMENT \'backup offering description\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('disk_offering', 'name', 'VARCHAR(255)', 'NOT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('disk_offering', 'unique_name', 'VARCHAR(32)', 'DEFAULT NULL COMMENT \'unique name\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('disk_offering', 'display_text', 'VARCHAR(4096)', 'DEFAULT NULL COMMENT \'Optional text set by the admin for display purpose only\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('instance_group', 'name', 'VARCHAR(255)', 'NOT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('kubernetes_cluster', 'name', 'VARCHAR(255)', 'NOT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('kubernetes_cluster', 'description', 'VARCHAR(4096)', 'DEFAULT NULL COMMENT \'display text for this Kubernetes cluster\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('kubernetes_supported_version', 'name', 'VARCHAR(255)', 'NOT NULL COMMENT \'the name of this Kubernetes version\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('network_offerings', 'name', 'VARCHAR(64)', 'DEFAULT NULL COMMENT \'name of the network offering\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('network_offerings', 'unique_name', 'VARCHAR(64)', 'DEFAULT NULL COMMENT \'unique name of the network offering\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('network_offerings', 'display_text', 'VARCHAR(255)', 'NOT NULL COMMENT \'text to display to users\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('networks', 'name', 'VARCHAR(255)', 'DEFAULT NULL COMMENT \'name for this network\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('networks', 'display_text', 'VARCHAR(255)', 'DEFAULT NULL COMMENT \'display text for this network\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('project_role', 'description', 'TEXT', 'COMMENT \'description of the project role\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('projects', 'name', 'VARCHAR(255)', 'DEFAULT NULL COMMENT \'project name\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('projects', 'display_text', 'VARCHAR(255)', 'DEFAULT NULL COMMENT \'project display text\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('roles', 'description', 'TEXT', 'COMMENT \'description of the role\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('service_offering', 'name', 'VARCHAR(255)', 'NOT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('service_offering', 'unique_name', 'VARCHAR(32)', 'DEFAULT NULL COMMENT \'unique name for offerings\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('service_offering', 'display_text', 'VARCHAR(4096)', 'DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('snapshots', 'name', 'VARCHAR(255)', 'NOT NULL COMMENT \'snapshot name\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('ssh_keypairs', 'keypair_name', 'VARCHAR(256)', 'NOT NULL COMMENT \'name of the key pair\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('user_vm', 'display_name', 'VARCHAR(255)', 'DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('user_vm_details', 'value', 'VARCHAR(5120)', 'NOT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('user', 'firstname', 'VARCHAR(255)', 'DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('user', 'lastname', 'VARCHAR(255)', 'DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('user_data', 'name', 'VARCHAR(256)', 'NOT NULL COMMENT \'name of the user data\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('vm_instance', 'display_name', 'VARCHAR(255)', 'DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('vm_snapshots', 'display_name', 'VARCHAR(255)', 'DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('vm_snapshots', 'description', 'VARCHAR(255)', 'DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('vm_template', 'name', 'VARCHAR(255)', 'NOT NULL'); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('vm_template', 'display_text', 'VARCHAR(4096)', 'DEFAULT NULL COMMENT \'Description text set by the admin for display purpose only\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('volumes', 'name', 'VARCHAR(255)', 'DEFAULT NULL COMMENT \'A user specified name for the volume\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('vpc', 'name', 'VARCHAR(255)', 'DEFAULT NULL COMMENT \'vpc name\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('vpc', 'display_text', 'VARCHAR(255)', 'DEFAULT NULL COMMENT \'vpc display text\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('vpc_offerings', 'name', 'VARCHAR(255)', 'DEFAULT NULL COMMENT \'vpc offering name\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('vpc_offerings', 'unique_name', 'VARCHAR(64)', 'DEFAULT NULL COMMENT \'unique name of the vpc offering\''); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('vpc_offerings', 'display_text', 'VARCHAR(255)', 'DEFAULT NULL COMMENT \'display text\''); + +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.roles','state', 'varchar(10) NOT NULL default "enabled" COMMENT "role state"'); + +-- Multi-Arch Zones +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.cluster', 'arch', 'varchar(8) DEFAULT "x86_64" COMMENT "the CPU architecture of the hosts in the cluster"'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.host', 'arch', 'varchar(8) DEFAULT "x86_64" COMMENT "the CPU architecture of the host"'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.vm_template', 'arch', 'varchar(8) DEFAULT "x86_64" COMMENT "the CPU architecture of the template/ISO"'); + +-- NAS B&R Plugin Backup Repository +DROP TABLE IF EXISTS `cloud`.`backup_repository`; +CREATE TABLE `cloud`.`backup_repository` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id of the backup repository', + `uuid` varchar(255) NOT NULL COMMENT 'uuid of the backup repository', + `name` varchar(255) CHARACTER SET utf8mb4 NOT NULL COMMENT 'name of the backup repository', + `zone_id` bigint unsigned NOT NULL COMMENT 'id of zone', + `provider` varchar(255) NOT NULL COMMENT 'backup provider name', + `type` varchar(255) NOT NULL COMMENT 'backup repo type', + `address` varchar(1024) NOT NULL COMMENT 'url of the backup repository', + `mount_opts` varchar(1024) NOT NULL COMMENT 'mount options for the backup repository', + `used_bytes` bigint unsigned, + `capacity_bytes` bigint unsigned, + `created` datetime, + `removed` datetime, + PRIMARY KEY(`id`), + INDEX `i_backup_repository__uuid`(`uuid`), + INDEX `i_backup_repository__zone_id_provider`(`zone_id`, `provider`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- Drop foreign key on backup_schedule, drop unique key on vm_id and re-add foreign key to allow multiple backup schedules to be created +ALTER TABLE `cloud`.`backup_schedule` DROP FOREIGN KEY fk_backup_schedule__vm_id; +ALTER TABLE `cloud`.`backup_schedule` DROP INDEX vm_id; +ALTER TABLE `cloud`.`backup_schedule` ADD CONSTRAINT fk_backup_schedule__vm_id FOREIGN KEY (vm_id) REFERENCES vm_instance(id) ON DELETE CASCADE; + +-- Add volume details to the backups table to keep track of the volumes being backed up +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.backups', 'backed_volumes', 'text DEFAULT NULL COMMENT "details of backed-up volumes" '); +CALL `cloud`.`IDEMPOTENT_MODIFY_COLUMN_CHAR_SET`('backups', 'backed_volumes', 'TEXT', 'DEFAULT NULL COMMENT \'details of backed-up volumes\''); + +-- Add support for VMware 8.0u2 (8.0.2.x) and 8.0u3 (8.0.3.x) +INSERT IGNORE INTO `cloud`.`hypervisor_capabilities` (uuid, hypervisor_type, hypervisor_version, max_guests_limit, security_group_enabled, max_data_volumes_limit, max_hosts_per_cluster, storage_motion_supported, vm_snapshot_enabled) values (UUID(), 'VMware', '8.0.2', 1024, 0, 59, 64, 1, 1); +INSERT IGNORE INTO `cloud`.`guest_os_hypervisor` (uuid, hypervisor_type, hypervisor_version, guest_os_name, guest_os_id, created, is_user_defined) SELECT UUID(),'VMware', '8.0.2', guest_os_name, guest_os_id, utc_timestamp(), 0 FROM `cloud`.`guest_os_hypervisor` WHERE hypervisor_type='VMware' AND hypervisor_version='8.0'; +INSERT IGNORE INTO `cloud`.`hypervisor_capabilities` (uuid, hypervisor_type, hypervisor_version, max_guests_limit, security_group_enabled, max_data_volumes_limit, max_hosts_per_cluster, storage_motion_supported, vm_snapshot_enabled) values (UUID(), 'VMware', '8.0.3', 1024, 0, 59, 64, 1, 1); +INSERT IGNORE INTO `cloud`.`guest_os_hypervisor` (uuid, hypervisor_type, hypervisor_version, guest_os_name, guest_os_id, created, is_user_defined) SELECT UUID(),'VMware', '8.0.3', guest_os_name, guest_os_id, utc_timestamp(), 0 FROM `cloud`.`guest_os_hypervisor` WHERE hypervisor_type='VMware' AND hypervisor_version='8.0'; + +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.vm_instance', 'delete_protection', 'boolean DEFAULT FALSE COMMENT "delete protection for vm" '); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.volumes', 'delete_protection', 'boolean DEFAULT FALSE COMMENT "delete protection for volumes" '); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-42000to42010-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-42000to42010-cleanup.sql new file mode 100644 index 00000000000..a00d50a7e10 --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/schema-42000to42010-cleanup.sql @@ -0,0 +1,23 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. + +--; +-- Schema upgrade cleanup from 4.20.0.0 to 4.20.1.0 +--; + +-- Delete `project_account` entries for users that were removed +DELETE FROM `cloud`.`project_account` WHERE `user_id` IN (SELECT `id` FROM `cloud`.`user` WHERE `removed`); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-42000to42010.sql b/engine/schema/src/main/resources/META-INF/db/schema-42000to42010.sql new file mode 100644 index 00000000000..3dd6c18f57c --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/schema-42000to42010.sql @@ -0,0 +1,133 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. + +--; +-- Schema upgrade from 4.20.0.0 to 4.20.1.0 +--; + +-- Delete user vm details for guest CPU mode/model which are root admin only +DELETE FROM `cloud`.`user_vm_details` WHERE `name` IN ('guest.cpu.mode','guest.cpu.model'); + +-- Delete template details for guest CPU mode/model which are root admin only +DELETE FROM `cloud`.`vm_template_details` WHERE `name` IN ('guest.cpu.mode','guest.cpu.model'); + +-- Add column api_key_access to user and account tables +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.user', 'api_key_access', 'boolean DEFAULT NULL COMMENT "is api key access allowed for the user" AFTER `secret_key`'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.account', 'api_key_access', 'boolean DEFAULT NULL COMMENT "is api key access allowed for the account" '); +CALL `cloud_usage`.`IDEMPOTENT_ADD_COLUMN`('cloud_usage.account', 'api_key_access', 'boolean DEFAULT NULL COMMENT "is api key access allowed for the account" '); + +-- Create a new group for Usage Server related configurations +INSERT INTO `cloud`.`configuration_group` (`name`, `description`, `precedence`) VALUES ('Usage Server', 'Usage Server related configuration', 9); +UPDATE `cloud`.`configuration_subgroup` set `group_id` = (SELECT `id` FROM `cloud`.`configuration_group` WHERE `name` = 'Usage Server'), `precedence` = 1 WHERE `name`='Usage'; +UPDATE `cloud`.`configuration` SET `group_id` = (SELECT `id` FROM `cloud`.`configuration_group` WHERE `name` = 'Usage Server') where `subgroup_id` = (SELECT `id` FROM `cloud`.`configuration_subgroup` WHERE `name` = 'Usage'); + +-- Update the description to indicate this setting applies only to volume snapshots on running instances +UPDATE `cloud`.`configuration` SET `description`='whether volume snapshot is enabled on running instances on KVM hosts' WHERE `name`='kvm.snapshot.enabled'; + +-- Modify index for mshost_peer +DELETE FROM `cloud`.`mshost_peer`; +CALL `cloud`.`IDEMPOTENT_DROP_FOREIGN_KEY`('cloud.mshost_peer','fk_mshost_peer__owner_mshost'); +CALL `cloud`.`IDEMPOTENT_DROP_INDEX`('i_mshost_peer__owner_peer_runid','mshost_peer'); +CALL `cloud`.`IDEMPOTENT_ADD_UNIQUE_KEY`('cloud.mshost_peer', 'i_mshost_peer__owner_peer', '(owner_mshost, peer_mshost)'); +CALL `cloud`.`IDEMPOTENT_ADD_FOREIGN_KEY`('cloud.mshost_peer', 'fk_mshost_peer__owner_mshost', '(owner_mshost)', '`mshost`(`id`)'); + +-- Add last_id to the volumes table +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.volumes', 'last_id', 'bigint(20) unsigned DEFAULT NULL'); + +-- Add used_iops column to support IOPS data in storage stats +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.storage_pool', 'used_iops', 'bigint unsigned DEFAULT NULL COMMENT "IOPS currently in use for this storage pool" '); + +-- Add reason column for op_ha_work +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.op_ha_work', 'reason', 'varchar(32) DEFAULT NULL COMMENT "Reason for the HA work"'); + +-- Support for XCP-ng 8.3.0 and XenServer 8.4 by adding hypervisor capabilities +-- https://docs.xenserver.com/en-us/xenserver/8/system-requirements/configuration-limits.html +-- https://docs.xenserver.com/en-us/citrix-hypervisor/system-requirements/configuration-limits.html +INSERT IGNORE INTO `cloud`.`hypervisor_capabilities`(uuid, hypervisor_type, hypervisor_version, max_guests_limit, max_data_volumes_limit, max_hosts_per_cluster, storage_motion_supported) VALUES (UUID(), 'XenServer', '8.3.0', 1000, 254, 64, 1); +INSERT IGNORE INTO `cloud`.`hypervisor_capabilities`(uuid, hypervisor_type, hypervisor_version, max_guests_limit, max_data_volumes_limit, max_hosts_per_cluster, storage_motion_supported) VALUES (UUID(), 'XenServer', '8.4.0', 1000, 240, 64, 1); + +-- Add missing and new Guest OS mappings +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (2, 'Debian GNU/Linux 10 (64-bit)', 'XenServer', '8.2.1', 'Debian Buster 10'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (5, 'SUSE Linux Enterprise Server 15 (64-bit)', 'XenServer', '8.2.1', 'SUSE Linux Enterprise 15 (64-bit)'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (6, 'Windows Server 2022 (64-bit)', 'XenServer', '8.2.1', 'Windows Server 2022 (64-bit)'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (6, 'Windows 11 (64-bit)', 'XenServer', '8.2.1', 'Windows 11'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (10, 'Ubuntu 20.04 LTS', 'XenServer', '8.2.1', 'Ubuntu Focal Fossa 20.04'); + +-- Copy XS 8.2.1 hypervisor guest OS mappings to XS 8.3 and 8.3 mappings to 8.4 +INSERT IGNORE INTO `cloud`.`guest_os_hypervisor` (uuid,hypervisor_type, hypervisor_version, guest_os_name, guest_os_id, created, is_user_defined) SELECT UUID(),'Xenserver', '8.3.0', guest_os_name, guest_os_id, utc_timestamp(), 0 FROM `cloud`.`guest_os_hypervisor` WHERE hypervisor_type='Xenserver' AND hypervisor_version='8.2.1'; + +-- Add new and missing guest os mappings for XS 8.3 +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (1, 'Rocky Linux 9', 'XenServer', '8.3.0', 'Rocky Linux 9'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (1, 'Rocky Linux 8', 'XenServer', '8.3.0', 'Rocky Linux 8'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (1, 'AlmaLinux 9', 'XenServer', '8.3.0', 'AlmaLinux 9'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (1, 'AlmaLinux 8', 'XenServer', '8.3.0', 'AlmaLinux 8'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (2, 'Debian GNU/Linux 12 (64-bit)', 'XenServer', '8.3.0', 'Debian Bookworm 12'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (3, 'Oracle Linux 9', 'XenServer', '8.3.0', 'Oracle Linux 9'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (3, 'Oracle Linux 8', 'XenServer', '8.3.0', 'Oracle Linux 8'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (4, 'Red Hat Enterprise Linux 8.0', 'XenServer', '8.3.0', 'Red Hat Enterprise Linux 8'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (4, 'Red Hat Enterprise Linux 9.0', 'XenServer', '8.3.0', 'Red Hat Enterprise Linux 9'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (10, 'Ubuntu 22.04 LTS', 'XenServer', '8.3.0', 'Ubuntu Jammy Jellyfish 22.04'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (5, 'SUSE Linux Enterprise Server 12 SP5 (64-bit)', 'XenServer', '8.3.0', 'SUSE Linux Enterprise Server 12 SP5 (64-bit'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (4, 'NeoKylin Linux Server 7', 'XenServer', '8.3.0', 'NeoKylin Linux Server 7'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (1, 'CentOS Stream 9', 'XenServer', '8.3.0', 'CentOS Stream 9'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (4, 'Scientific Linux 7', 'XenServer', '8.3.0', 'Scientific Linux 7'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (7, 'Generic Linux UEFI', 'XenServer', '8.3.0', 'Generic Linux UEFI'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (7, 'Generic Linux BIOS', 'XenServer', '8.3.0', 'Generic Linux BIOS'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (2, 'Gooroom Platform 2.0', 'XenServer', '8.3.0', 'Gooroom Platform 2.0'); + +INSERT IGNORE INTO `cloud`.`guest_os_hypervisor` (uuid,hypervisor_type, hypervisor_version, guest_os_name, guest_os_id, created, is_user_defined) SELECT UUID(),'Xenserver', '8.4.0', guest_os_name, guest_os_id, utc_timestamp(), 0 FROM `cloud`.`guest_os_hypervisor` WHERE hypervisor_type='Xenserver' AND hypervisor_version='8.3.0'; + +-- Add new guest os mappings for XS 8.4 and KVM +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (6, 'Windows Server 2025', 'XenServer', '8.4.0', 'Windows Server 2025'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (10, 'Ubuntu 24.04 LTS', 'XenServer', '8.4.0', 'Ubuntu Noble Numbat 24.04'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (2, 'Debian GNU/Linux 10 (64-bit)', 'KVM', 'default', 'Debian GNU/Linux 10 (64-bit)'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (2, 'Debian GNU/Linux 11 (64-bit)', 'KVM', 'default', 'Debian GNU/Linux 11 (64-bit)'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (2, 'Debian GNU/Linux 12 (64-bit)', 'KVM', 'default', 'Debian GNU/Linux 12 (64-bit)'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (6, 'Windows 11 (64-bit)', 'KVM', 'default', 'Windows 11'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (6, 'Windows Server 2025', 'KVM', 'default', 'Windows Server 2025'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (10, 'Ubuntu 24.04 LTS', 'KVM', 'default', 'Ubuntu 24.04 LTS'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (1, 'CentOS Stream 10 (preview)', 'XenServer', '8.4.0', 'CentOS Stream 10 (preview)'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (1, 'CentOS Stream 9', 'XenServer', '8.4.0', 'CentOS Stream 9'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (4, 'Scientific Linux 7', 'XenServer', '8.4.0', 'Scientific Linux 7'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (4, 'NeoKylin Linux Server 7', 'XenServer', '8.4.0', 'NeoKylin Linux Server 7'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (5, 'SUSE Linux Enterprise Server 12 SP5 (64-bit)', 'XenServer', '8.4.0', 'SUSE Linux Enterprise Server 12 SP5 (64-bit'); +CALL ADD_GUEST_OS_AND_HYPERVISOR_MAPPING (2, 'Gooroom Platform 2.0', 'XenServer', '8.4.0', 'Gooroom Platform 2.0'); + +-- Grant access to 2FA APIs for the "Read-Only User - Default" role + +CALL `cloud`.`IDEMPOTENT_UPDATE_API_PERMISSION`('Read-Only User - Default', 'setupUserTwoFactorAuthentication', 'ALLOW'); +CALL `cloud`.`IDEMPOTENT_UPDATE_API_PERMISSION`('Read-Only User - Default', 'validateUserTwoFactorAuthenticationCode', 'ALLOW'); +CALL `cloud`.`IDEMPOTENT_UPDATE_API_PERMISSION`('Read-Only User - Default', 'listUserTwoFactorAuthenticatorProviders', 'ALLOW'); + +-- Grant access to 2FA APIs for the "Support User - Default" role + +CALL `cloud`.`IDEMPOTENT_UPDATE_API_PERMISSION`('Support User - Default', 'setupUserTwoFactorAuthentication', 'ALLOW'); +CALL `cloud`.`IDEMPOTENT_UPDATE_API_PERMISSION`('Support User - Default', 'validateUserTwoFactorAuthenticationCode', 'ALLOW'); +CALL `cloud`.`IDEMPOTENT_UPDATE_API_PERMISSION`('Support User - Default', 'listUserTwoFactorAuthenticatorProviders', 'ALLOW'); + +-- Grant access to 2FA APIs for the "Read-Only Admin - Default" role + +CALL `cloud`.`IDEMPOTENT_UPDATE_API_PERMISSION`('Read-Only Admin - Default', 'setupUserTwoFactorAuthentication', 'ALLOW'); +CALL `cloud`.`IDEMPOTENT_UPDATE_API_PERMISSION`('Read-Only Admin - Default', 'validateUserTwoFactorAuthenticationCode', 'ALLOW'); + +-- Grant access to 2FA APIs for the "Support Admin - Default" role + +CALL `cloud`.`IDEMPOTENT_UPDATE_API_PERMISSION`('Support Admin - Default', 'setupUserTwoFactorAuthentication', 'ALLOW'); +CALL `cloud`.`IDEMPOTENT_UPDATE_API_PERMISSION`('Support Admin - Default', 'validateUserTwoFactorAuthenticationCode', 'ALLOW'); + +-- Re-apply VPC: update default network offering for vpc tier to conserve_mode=1 (#8309) +UPDATE `cloud`.`network_offerings` SET conserve_mode=1 WHERE name='DefaultIsolatedNetworkOfferingForVpcNetworks'; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-420to421.sql b/engine/schema/src/main/resources/META-INF/db/schema-420to421.sql index b99af287bc5..25c025c5651 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-420to421.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-420to421.sql @@ -20,10 +20,10 @@ --; -INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 's3.singleupload.max.size', '5', +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 's3.singleupload.max.size', '5', 'The maximum size limit for S3 single part upload API(in GB). If it is set to 0, then it means always use multi-part upload to upload object to S3. If it is set to -1, then it means always use single-part upload to upload object to S3.'); -INSERT IGNORE INTO `cloud`.`configuration` VALUES ("Storage", 'DEFAULT', 'management-server', "enable.ha.storage.migration", "true", "Enable/disable storage migration across primary storage during HA"); +INSERT IGNORE INTO `cloud`.`configuration` VALUES ("Storage", 'DEFAULT', 'management-server', "enable.ha.storage.migration", "true", "Enable/disable storage migration across primary storage during HA"); UPDATE `cloud`.`configuration` SET description="Specify whether or not to reserve CPU based on CPU overprovisioning factor" where name="vmware.reserve.cpu"; UPDATE `cloud`.`configuration` SET description="Specify whether or not to reserve memory based on memory overprovisioning factor" where name="vmware.reserve.mem"; -- Remove Windows Server 8 from guest_os_type dropdown to use Windows Server 2012 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-442to450.sql b/engine/schema/src/main/resources/META-INF/db/schema-442to450.sql index 90a52bd4273..d2ba408241e 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-442to450.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-442to450.sql @@ -671,7 +671,7 @@ CREATE VIEW `cloud`.`user_vm_view` AS resource_tags.resource_id tag_resource_id, resource_tags.resource_uuid tag_resource_uuid, resource_tags.resource_type tag_resource_type, - resource_tags.customer tag_customer, + resource_tags.customer tag_customer, async_job.id job_id, async_job.uuid job_uuid, async_job.job_status job_status, @@ -752,7 +752,7 @@ CREATE VIEW `cloud`.`user_vm_view` AS left join `cloud`.`user_vm_details` `custom_speed` ON (((`custom_speed`.`vm_id` = `cloud`.`vm_instance`.`id`) and (`custom_speed`.`name` = 'CpuSpeed'))) left join - `cloud`.`user_vm_details` `custom_ram_size` ON (((`custom_ram_size`.`vm_id` = `cloud`.`vm_instance`.`id`) and (`custom_ram_size`.`name` = 'memory'))); + `cloud`.`user_vm_details` `custom_ram_size` ON (((`custom_ram_size`.`vm_id` = `cloud`.`vm_instance`.`id`) and (`custom_ram_size`.`name` = 'memory'))); INSERT IGNORE INTO `cloud`.`guest_os` (id, uuid, category_id, display_name, created) VALUES (231, UUID(), 1, 'CentOS 5 (32-bit)', utc_timestamp()); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-481to490-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-481to490-cleanup.sql index 1868a090800..b8dd0477db9 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-481to490-cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-481to490-cleanup.sql @@ -22,7 +22,7 @@ -- Added in CLOUDSTACK-9340: General DB optimization, 4 cases: ----- 1) Incorrect PRIMARY key -ALTER TABLE `cloud`.`ovs_tunnel_network` +ALTER TABLE `cloud`.`ovs_tunnel_network` DROP PRIMARY KEY, ADD PRIMARY KEY (`id`), DROP INDEX `id` , diff --git a/engine/schema/src/main/resources/META-INF/db/schema-481to490.sql b/engine/schema/src/main/resources/META-INF/db/schema-481to490.sql index 49cfc8346c5..bac3b1e6fab 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-481to490.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-481to490.sql @@ -23,9 +23,9 @@ ALTER TABLE `event` ADD INDEX `archived` (`archived`); ALTER TABLE `event` ADD INDEX `state` (`state`); DROP VIEW IF EXISTS `cloud`.`template_view`; -CREATE +CREATE VIEW `template_view` AS - SELECT + SELECT `vm_template`.`id` AS `id`, `vm_template`.`uuid` AS `uuid`, `vm_template`.`unique_name` AS `unique_name`, @@ -124,9 +124,9 @@ VIEW `template_view` AS OR (`resource_tags`.`resource_type` = 'ISO'))))); DROP VIEW IF EXISTS `cloud`.`volume_view`; -CREATE +CREATE VIEW `volume_view` AS - SELECT + SELECT `volumes`.`id` AS `id`, `volumes`.`uuid` AS `uuid`, `volumes`.`name` AS `name`, @@ -234,9 +234,9 @@ VIEW `volume_view` AS AND (`async_job`.`job_status` = 0)))); DROP VIEW IF EXISTS `cloud`.`user_vm_view`; -CREATE +CREATE VIEW `user_vm_view` AS - SELECT + SELECT `vm_instance`.`id` AS `id`, `vm_instance`.`name` AS `name`, `user_vm`.`display_name` AS `display_name`, @@ -423,10 +423,10 @@ ALTER TABLE `cloud`.`ssh_keypairs` ADD INDEX `i_public_key` (`public_key` (64) A ALTER TABLE `cloud`.`user_vm_details` ADD INDEX `i_name_vm_id` (`vm_id` ASC, `name` ASC); ALTER TABLE `cloud`.`instance_group` ADD INDEX `i_name` (`name` ASC); ------ 4) Some views query (Change view to improve account retrieval speed) +----- 4) Some views query (Change view to improve account retrieval speed) CREATE OR REPLACE VIEW `account_vmstats_view` AS - SELECT + SELECT `vm_instance`.`account_id` AS `account_id`, `vm_instance`.`state` AS `state`, COUNT(0) AS `vmcount` diff --git a/engine/schema/src/main/resources/META-INF/db/schema-4930to41000.sql b/engine/schema/src/main/resources/META-INF/db/schema-4930to41000.sql index dc0cd6d4d75..23670757247 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-4930to41000.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-4930to41000.sql @@ -147,7 +147,7 @@ CREATE TABLE IF NOT EXISTS `cloud`.`storage_pool_tags` ( ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- Insert storage tags from storage_pool_details -INSERT INTO `cloud`.`storage_pool_tags` (pool_id, tag) SELECT pool_id, +INSERT INTO `cloud`.`storage_pool_tags` (pool_id, tag) SELECT pool_id, name FROM `cloud`.`storage_pool_details` WHERE value = 'true'; -- Alter view storage_pool_view @@ -227,7 +227,7 @@ ALTER TABLE `cloud`.`vm_snapshots` ADD CONSTRAINT `fk_vm_snapshots_service_offer INSERT INTO `cloud`.`vm_snapshot_details` (vm_snapshot_id, name, value) SELECT s.id, d.name, d.value FROM `cloud`.`user_vm_details` d JOIN `cloud`.`vm_instance` v ON (d.vm_id = v.id) -JOIN `cloud`.`service_offering` o ON (v.service_offering_id = o.id) +JOIN `cloud`.`service_offering` o ON (v.service_offering_id = o.id) JOIN `cloud`.`vm_snapshots` s ON (s.service_offering_id = o.id AND s.vm_id = v.id) WHERE (o.cpu is null AND o.speed IS NULL AND o.ram_size IS NULL) AND (d.name = 'cpuNumber' OR d.name = 'cpuSpeed' OR d.name = 'memory'); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-level.sql b/engine/schema/src/main/resources/META-INF/db/schema-level.sql index 72aade4e501..fef961502fa 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-level.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-level.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-snapshot-217to224.sql b/engine/schema/src/main/resources/META-INF/db/schema-snapshot-217to224.sql index 7320bda5906..5e29435855d 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-snapshot-217to224.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-snapshot-217to224.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-snapshot-223to224.sql b/engine/schema/src/main/resources/META-INF/db/schema-snapshot-223to224.sql index 668cbb692b9..5c27eed68f0 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-snapshot-223to224.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-snapshot-223to224.sql @@ -5,9 +5,9 @@ -- to you 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 diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.account_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.account_view.sql index 27d70b4171c..dc64380fb57 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.account_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.account_view.sql @@ -15,11 +15,9 @@ -- specific language governing permissions and limitations -- under the License. --- cloud.account_view source - +-- VIEW `cloud`.`account_view`; DROP VIEW IF EXISTS `cloud`.`account_view`; - CREATE VIEW `cloud`.`account_view` AS select `account`.`id` AS `id`, @@ -31,8 +29,9 @@ select `account`.`created` AS `created`, `account`.`removed` AS `removed`, `account`.`cleanup_needed` AS `cleanup_needed`, - `account`.`network_domain` AS `network_domain`, + `account`.`network_domain` AS `network_domain` , `account`.`default` AS `default`, + `account`.`api_key_access` AS `api_key_access`, `domain`.`id` AS `domain_id`, `domain`.`uuid` AS `domain_uuid`, `domain`.`name` AS `domain_name`, @@ -74,93 +73,93 @@ select `async_job`.`job_status` AS `job_status`, `async_job`.`account_id` AS `job_account_id` from - (`free_ip_view` -join ((((((((((((((((((((((((((((((`account` -join `domain` on - ((`account`.`domain_id` = `domain`.`id`))) -left join `data_center` on - ((`account`.`default_zone_id` = `data_center`.`id`))) -left join `account_netstats_view` on - ((`account`.`id` = `account_netstats_view`.`account_id`))) -left join `resource_limit` `vmlimit` on - (((`account`.`id` = `vmlimit`.`account_id`) - and (`vmlimit`.`type` = 'user_vm')))) -left join `resource_count` `vmcount` on - (((`account`.`id` = `vmcount`.`account_id`) - and (`vmcount`.`type` = 'user_vm')))) -left join `account_vmstats_view` `runningvm` on - (((`account`.`id` = `runningvm`.`account_id`) - and (`runningvm`.`state` = 'Running')))) -left join `account_vmstats_view` `stoppedvm` on - (((`account`.`id` = `stoppedvm`.`account_id`) - and (`stoppedvm`.`state` = 'Stopped')))) -left join `resource_limit` `iplimit` on - (((`account`.`id` = `iplimit`.`account_id`) - and (`iplimit`.`type` = 'public_ip')))) -left join `resource_count` `ipcount` on - (((`account`.`id` = `ipcount`.`account_id`) - and (`ipcount`.`type` = 'public_ip')))) -left join `resource_limit` `volumelimit` on - (((`account`.`id` = `volumelimit`.`account_id`) - and (`volumelimit`.`type` = 'volume')))) -left join `resource_count` `volumecount` on - (((`account`.`id` = `volumecount`.`account_id`) - and (`volumecount`.`type` = 'volume')))) -left join `resource_limit` `snapshotlimit` on - (((`account`.`id` = `snapshotlimit`.`account_id`) - and (`snapshotlimit`.`type` = 'snapshot')))) -left join `resource_count` `snapshotcount` on - (((`account`.`id` = `snapshotcount`.`account_id`) - and (`snapshotcount`.`type` = 'snapshot')))) -left join `resource_limit` `templatelimit` on - (((`account`.`id` = `templatelimit`.`account_id`) - and (`templatelimit`.`type` = 'template')))) -left join `resource_count` `templatecount` on - (((`account`.`id` = `templatecount`.`account_id`) - and (`templatecount`.`type` = 'template')))) -left join `resource_limit` `vpclimit` on - (((`account`.`id` = `vpclimit`.`account_id`) - and (`vpclimit`.`type` = 'vpc')))) -left join `resource_count` `vpccount` on - (((`account`.`id` = `vpccount`.`account_id`) - and (`vpccount`.`type` = 'vpc')))) -left join `resource_limit` `projectlimit` on - (((`account`.`id` = `projectlimit`.`account_id`) - and (`projectlimit`.`type` = 'project')))) -left join `resource_count` `projectcount` on - (((`account`.`id` = `projectcount`.`account_id`) - and (`projectcount`.`type` = 'project')))) -left join `resource_limit` `networklimit` on - (((`account`.`id` = `networklimit`.`account_id`) - and (`networklimit`.`type` = 'network')))) -left join `resource_count` `networkcount` on - (((`account`.`id` = `networkcount`.`account_id`) - and (`networkcount`.`type` = 'network')))) -left join `resource_limit` `cpulimit` on - (((`account`.`id` = `cpulimit`.`account_id`) - and (`cpulimit`.`type` = 'cpu')))) -left join `resource_count` `cpucount` on - (((`account`.`id` = `cpucount`.`account_id`) - and (`cpucount`.`type` = 'cpu')))) -left join `resource_limit` `memorylimit` on - (((`account`.`id` = `memorylimit`.`account_id`) - and (`memorylimit`.`type` = 'memory')))) -left join `resource_count` `memorycount` on - (((`account`.`id` = `memorycount`.`account_id`) - and (`memorycount`.`type` = 'memory')))) -left join `resource_limit` `primary_storage_limit` on - (((`account`.`id` = `primary_storage_limit`.`account_id`) - and (`primary_storage_limit`.`type` = 'primary_storage')))) -left join `resource_count` `primary_storage_count` on - (((`account`.`id` = `primary_storage_count`.`account_id`) - and (`primary_storage_count`.`type` = 'primary_storage')))) -left join `resource_limit` `secondary_storage_limit` on - (((`account`.`id` = `secondary_storage_limit`.`account_id`) - and (`secondary_storage_limit`.`type` = 'secondary_storage')))) -left join `resource_count` `secondary_storage_count` on - (((`account`.`id` = `secondary_storage_count`.`account_id`) - and (`secondary_storage_count`.`type` = 'secondary_storage')))) -left join `async_job` on - (((`async_job`.`instance_id` = `account`.`id`) - and (`async_job`.`instance_type` = 'Account') - and (`async_job`.`job_status` = 0))))); + `cloud`.`free_ip_view`, + `cloud`.`account` + inner join + `cloud`.`domain` ON account.domain_id = domain.id + left join + `cloud`.`data_center` ON account.default_zone_id = data_center.id + left join + `cloud`.`account_netstats_view` ON account.id = account_netstats_view.account_id + left join + `cloud`.`resource_limit` vmlimit ON account.id = vmlimit.account_id + and vmlimit.type = 'user_vm' and vmlimit.tag IS NULL + left join + `cloud`.`resource_count` vmcount ON account.id = vmcount.account_id + and vmcount.type = 'user_vm' and vmcount.tag IS NULL + left join + `cloud`.`account_vmstats_view` runningvm ON account.id = runningvm.account_id + and runningvm.state = 'Running' + left join + `cloud`.`account_vmstats_view` stoppedvm ON account.id = stoppedvm.account_id + and stoppedvm.state = 'Stopped' + left join + `cloud`.`resource_limit` iplimit ON account.id = iplimit.account_id + and iplimit.type = 'public_ip' + left join + `cloud`.`resource_count` ipcount ON account.id = ipcount.account_id + and ipcount.type = 'public_ip' + left join + `cloud`.`resource_limit` volumelimit ON account.id = volumelimit.account_id + and volumelimit.type = 'volume' and volumelimit.tag IS NULL + left join + `cloud`.`resource_count` volumecount ON account.id = volumecount.account_id + and volumecount.type = 'volume' and volumecount.tag IS NULL + left join + `cloud`.`resource_limit` snapshotlimit ON account.id = snapshotlimit.account_id + and snapshotlimit.type = 'snapshot' + left join + `cloud`.`resource_count` snapshotcount ON account.id = snapshotcount.account_id + and snapshotcount.type = 'snapshot' + left join + `cloud`.`resource_limit` templatelimit ON account.id = templatelimit.account_id + and templatelimit.type = 'template' + left join + `cloud`.`resource_count` templatecount ON account.id = templatecount.account_id + and templatecount.type = 'template' + left join + `cloud`.`resource_limit` vpclimit ON account.id = vpclimit.account_id + and vpclimit.type = 'vpc' + left join + `cloud`.`resource_count` vpccount ON account.id = vpccount.account_id + and vpccount.type = 'vpc' + left join + `cloud`.`resource_limit` projectlimit ON account.id = projectlimit.account_id + and projectlimit.type = 'project' + left join + `cloud`.`resource_count` projectcount ON account.id = projectcount.account_id + and projectcount.type = 'project' + left join + `cloud`.`resource_limit` networklimit ON account.id = networklimit.account_id + and networklimit.type = 'network' + left join + `cloud`.`resource_count` networkcount ON account.id = networkcount.account_id + and networkcount.type = 'network' + left join + `cloud`.`resource_limit` cpulimit ON account.id = cpulimit.account_id + and cpulimit.type = 'cpu' and cpulimit.tag IS NULL + left join + `cloud`.`resource_count` cpucount ON account.id = cpucount.account_id + and cpucount.type = 'cpu' and cpucount.tag IS NULL + left join + `cloud`.`resource_limit` memorylimit ON account.id = memorylimit.account_id + and memorylimit.type = 'memory' and memorylimit.tag IS NULL + left join + `cloud`.`resource_count` memorycount ON account.id = memorycount.account_id + and memorycount.type = 'memory' and memorycount.tag IS NULL + left join + `cloud`.`resource_limit` primary_storage_limit ON account.id = primary_storage_limit.account_id + and primary_storage_limit.type = 'primary_storage' and primary_storage_limit.tag IS NULL + left join + `cloud`.`resource_count` primary_storage_count ON account.id = primary_storage_count.account_id + and primary_storage_count.type = 'primary_storage' and primary_storage_count.tag IS NULL + left join + `cloud`.`resource_limit` secondary_storage_limit ON account.id = secondary_storage_limit.account_id + and secondary_storage_limit.type = 'secondary_storage' + left join + `cloud`.`resource_count` secondary_storage_count ON account.id = secondary_storage_count.account_id + and secondary_storage_count.type = 'secondary_storage' + left join + `cloud`.`async_job` ON async_job.instance_id = account.id + and async_job.instance_type = 'Account' + and async_job.job_status = 0; diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.domain_router_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.domain_router_view.sql index 70394e8fd6d..a12e02bcfdb 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.domain_router_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.domain_router_view.sql @@ -58,6 +58,7 @@ select host.resource_state host_resource_state, vm_template.id template_id, vm_template.uuid template_uuid, + vm_template.arch arch, service_offering.id service_offering_id, service_offering.uuid service_offering_uuid, service_offering.name service_offering_name, diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.domain_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.domain_view.sql index 2d8a9b536f2..201ece95023 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.domain_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.domain_view.sql @@ -63,10 +63,10 @@ from `cloud`.`domain` left join `cloud`.`resource_limit` vmlimit ON domain.id = vmlimit.domain_id - and vmlimit.type = 'user_vm' + and vmlimit.type = 'user_vm' and vmlimit.tag IS NULL left join `cloud`.`resource_count` vmcount ON domain.id = vmcount.domain_id - and vmcount.type = 'user_vm' + and vmcount.type = 'user_vm' and vmcount.tag IS NULL left join `cloud`.`resource_limit` iplimit ON domain.id = iplimit.domain_id and iplimit.type = 'public_ip' @@ -75,10 +75,10 @@ from and ipcount.type = 'public_ip' left join `cloud`.`resource_limit` volumelimit ON domain.id = volumelimit.domain_id - and volumelimit.type = 'volume' + and volumelimit.type = 'volume' and volumelimit.tag IS NULL left join `cloud`.`resource_count` volumecount ON domain.id = volumecount.domain_id - and volumecount.type = 'volume' + and volumecount.type = 'volume' and volumecount.tag IS NULL left join `cloud`.`resource_limit` snapshotlimit ON domain.id = snapshotlimit.domain_id and snapshotlimit.type = 'snapshot' @@ -111,22 +111,22 @@ from and networkcount.type = 'network' left join `cloud`.`resource_limit` cpulimit ON domain.id = cpulimit.domain_id - and cpulimit.type = 'cpu' + and cpulimit.type = 'cpu' and cpulimit.tag IS NULL left join `cloud`.`resource_count` cpucount ON domain.id = cpucount.domain_id - and cpucount.type = 'cpu' + and cpucount.type = 'cpu' and cpucount.tag IS NULL left join `cloud`.`resource_limit` memorylimit ON domain.id = memorylimit.domain_id - and memorylimit.type = 'memory' + and memorylimit.type = 'memory' and memorylimit.tag IS NULL left join `cloud`.`resource_count` memorycount ON domain.id = memorycount.domain_id - and memorycount.type = 'memory' + and memorycount.type = 'memory' and memorycount.tag IS NULL left join `cloud`.`resource_limit` primary_storage_limit ON domain.id = primary_storage_limit.domain_id - and primary_storage_limit.type = 'primary_storage' + and primary_storage_limit.type = 'primary_storage' and primary_storage_limit.tag IS NULL left join `cloud`.`resource_count` primary_storage_count ON domain.id = primary_storage_count.domain_id - and primary_storage_count.type = 'primary_storage' + and primary_storage_count.type = 'primary_storage' and primary_storage_count.tag IS NULL left join `cloud`.`resource_limit` secondary_storage_limit ON domain.id = secondary_storage_limit.domain_id and secondary_storage_limit.type = 'secondary_storage' diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.host_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.host_view.sql index 5c6d4fd772b..6fc8fb80386 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.host_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.host_view.sql @@ -41,6 +41,7 @@ SELECT host.cpus, host.speed, host.ram, + host.arch, cluster.id cluster_id, cluster.uuid cluster_uuid, cluster.name cluster_name, @@ -53,7 +54,9 @@ SELECT host_pod_ref.uuid pod_uuid, host_pod_ref.name pod_name, GROUP_CONCAT(DISTINCT(host_tags.tag)) AS tag, - `host_tags`.`is_tag_a_rule` AS `is_tag_a_rule`, + GROUP_CONCAT(DISTINCT(explicit_host_tags.tag)) AS explicit_tag, + GROUP_CONCAT(DISTINCT(implicit_host_tags.tag)) AS implicit_tag, + `explicit_host_tags`.`is_tag_a_rule` AS `is_tag_a_rule`, guest_os_category.id guest_os_category_id, guest_os_category.uuid guest_os_category_uuid, guest_os_category.name guest_os_category_name, @@ -89,6 +92,10 @@ FROM LEFT JOIN `cloud`.`host_tags` ON host_tags.host_id = host.id LEFT JOIN + `cloud`.`host_tags` AS explicit_host_tags ON explicit_host_tags.host_id = host.id AND explicit_host_tags.is_implicit = 0 + LEFT JOIN + `cloud`.`host_tags` AS implicit_host_tags ON implicit_host_tags.host_id = host.id AND implicit_host_tags.is_implicit = 1 + LEFT JOIN `cloud`.`op_host_capacity` mem_caps ON host.id = mem_caps.host_id AND mem_caps.capacity_type = 0 LEFT JOIN diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.mshost_peer_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.mshost_peer_view.sql new file mode 100644 index 00000000000..5f741449d85 --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.mshost_peer_view.sql @@ -0,0 +1,44 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. + + +DROP VIEW IF EXISTS `cloud`.`mshost_peer_view`; + +CREATE VIEW `cloud`.`mshost_peer_view` AS +SELECT + `mshost_peer`.`id` AS `id`, + `mshost_peer`.`peer_state` AS `peer_state`, + `mshost_peer`.`last_update` AS `last_update`, + `owner_mshost`.`id` AS `owner_mshost_id`, + `owner_mshost`.`msid` AS `owner_mshost_msid`, + `owner_mshost`.`runid` AS `owner_mshost_runid`, + `owner_mshost`.`name` AS `owner_mshost_name`, + `owner_mshost`.`uuid` AS `owner_mshost_uuid`, + `owner_mshost`.`state` AS `owner_mshost_state`, + `owner_mshost`.`service_ip` AS `owner_mshost_service_ip`, + `owner_mshost`.`service_port` AS `owner_mshost_service_port`, + `peer_mshost`.`id` AS `peer_mshost_id`, + `peer_mshost`.`msid` AS `peer_mshost_msid`, + `peer_mshost`.`runid` AS `peer_mshost_runid`, + `peer_mshost`.`name` AS `peer_mshost_name`, + `peer_mshost`.`uuid` AS `peer_mshost_uuid`, + `peer_mshost`.`state` AS `peer_mshost_state`, + `peer_mshost`.`service_ip` AS `peer_mshost_service_ip`, + `peer_mshost`.`service_port` AS `peer_mshost_service_port` +FROM `cloud`.`mshost_peer` +LEFT JOIN `cloud`.`mshost` AS owner_mshost on `mshost_peer`.`owner_mshost` = `owner_mshost`.`id` +LEFT JOIN `cloud`.`mshost` AS peer_mshost on `mshost_peer`.`peer_mshost` = `peer_mshost`.`id`; diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.network_offering_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.network_offering_view.sql index 8ba291e154c..640b2397a46 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.network_offering_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.network_offering_view.sql @@ -60,7 +60,11 @@ SELECT `network_offerings`.`supports_vm_autoscaling` AS `supports_vm_autoscaling`, `network_offerings`.`for_vpc` AS `for_vpc`, `network_offerings`.`for_tungsten` AS `for_tungsten`, + `network_offerings`.`for_nsx` AS `for_nsx`, + `network_offerings`.`network_mode` AS `network_mode`, `network_offerings`.`service_package_id` AS `service_package_id`, + `network_offerings`.`routing_mode` AS `routing_mode`, + `network_offerings`.`specify_as_number` AS `specify_as_number`, GROUP_CONCAT(DISTINCT(domain.id)) AS domain_id, GROUP_CONCAT(DISTINCT(domain.uuid)) AS domain_uuid, GROUP_CONCAT(DISTINCT(domain.name)) AS domain_name, @@ -72,13 +76,9 @@ SELECT FROM `cloud`.`network_offerings` LEFT JOIN - `cloud`.`network_offering_details` AS `domain_details` ON `domain_details`.`network_offering_id` = `network_offerings`.`id` AND `domain_details`.`name`='domainid' + `cloud`.`domain` AS `domain` ON `domain`.id IN (SELECT value from `network_offering_details` where `name` = 'domainid' and `network_offering_id` = `network_offerings`.`id`) LEFT JOIN - `cloud`.`domain` AS `domain` ON FIND_IN_SET(`domain`.`id`, `domain_details`.`value`) - LEFT JOIN - `cloud`.`network_offering_details` AS `zone_details` ON `zone_details`.`network_offering_id` = `network_offerings`.`id` AND `zone_details`.`name`='zoneid' - LEFT JOIN - `cloud`.`data_center` AS `zone` ON FIND_IN_SET(`zone`.`id`, `zone_details`.`value`) + `cloud`.`data_center` AS `zone` ON `zone`.`id` IN (SELECT value from `network_offering_details` where `name` = 'zoneid' and `network_offering_id` = `network_offerings`.`id`) LEFT JOIN `cloud`.`network_offering_details` AS `offering_details` ON `offering_details`.`network_offering_id` = `network_offerings`.`id` AND `offering_details`.`name`='internetProtocol' GROUP BY diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.shared_filesystem_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.shared_filesystem_view.sql new file mode 100644 index 00000000000..1f72babd1ce --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.shared_filesystem_view.sql @@ -0,0 +1,83 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. + +-- VIEW `cloud`.`shared_filesystem_view`; + +DROP VIEW IF EXISTS `cloud`.`shared_filesystem_view`; + +CREATE VIEW `cloud`.`shared_filesystem_view` AS +SELECT + `shared_filesystem`.`id` AS `id`, + `shared_filesystem`.`uuid` AS `uuid`, + `shared_filesystem`.`name` AS `name`, + `shared_filesystem`.`description` AS `description`, + `shared_filesystem`.`state` AS `state`, + `shared_filesystem`.`fs_provider_name` AS `provider`, + `shared_filesystem`.`fs_type` AS `fs_type`, + `shared_filesystem`.`volume_id` AS `volume_id`, + `shared_filesystem`.`account_id` AS `account_id`, + `shared_filesystem`.`data_center_id` AS `zone_id`, + `zone`.`uuid` AS `zone_uuid`, + `zone`.`name` AS `zone_name`, + `instance`.`id` AS `instance_id`, + `instance`.`uuid` AS `instance_uuid`, + `instance`.`name` AS `instance_name`, + `instance`.`state` AS `instance_state`, + `volumes`.`size` AS `size`, + `volumes`.`uuid` AS `volume_uuid`, + `volumes`.`name` AS `volume_name`, + `volumes`.`provisioning_type` AS `provisioning_type`, + `volumes`.`format` AS `volume_format`, + `volumes`.`path` AS `volume_path`, + `volumes`.`chain_info` AS `volume_chain_info`, + `storage_pool`.`uuid` AS `pool_uuid`, + `storage_pool`.`name` AS `pool_name`, + `account`.`account_name` AS `account_name`, + `project`.`uuid` AS `project_uuid`, + `project`.`name` AS `project_name`, + `domain`.`uuid` AS `domain_uuid`, + `domain`.`name` AS `domain_name`, + `domain`.`path` AS `domain_path`, + `service_offering`.`uuid` AS `service_offering_uuid`, + `service_offering`.`name` AS `service_offering_name`, + `disk_offering`.`uuid` AS `disk_offering_uuid`, + `disk_offering`.`name` AS `disk_offering_name`, + `disk_offering`.`display_text` AS `disk_offering_display_text`, + `disk_offering`.`disk_size` AS `disk_offering_size`, + `disk_offering`.`customized` AS `disk_offering_custom` +FROM + `cloud`.`shared_filesystem` + LEFT JOIN + `cloud`.`data_center` AS `zone` ON `shared_filesystem`.`data_center_id` = `zone`.`id` + LEFT JOIN + `cloud`.`vm_instance` AS `instance` ON `shared_filesystem`.`vm_id` = `instance`.`id` + LEFT JOIN + `cloud`.`volumes` AS `volumes` ON `shared_filesystem`.`volume_id` = `volumes`.`id` + LEFT JOIN + `cloud`.`storage_pool` AS `storage_pool` ON `volumes`.`pool_id` = `storage_pool`.`id` + LEFT JOIN + `cloud`.`account` AS `account` ON `shared_filesystem`.`account_id` = `account`.`id` + LEFT JOIN + `cloud`.`projects` AS `project` ON `project`.`project_account_id` = `account`.`id` + LEFT JOIN + `cloud`.`domain` AS `domain` ON `shared_filesystem`.`domain_id` = `domain`.`id` + LEFT JOIN + `cloud`.`service_offering` AS `service_offering` ON `shared_filesystem`.`service_offering_id` = `service_offering`.`id` + LEFT JOIN + `cloud`.`disk_offering` AS `disk_offering` ON `volumes`.`disk_offering_id` = `disk_offering`.`id` +GROUP BY + `shared_filesystem`.`id`; diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.storage_pool_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.storage_pool_view.sql index e6cc9458208..5d7585baa3b 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.storage_pool_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.storage_pool_view.sql @@ -31,7 +31,9 @@ SELECT `storage_pool`.`created` AS `created`, `storage_pool`.`removed` AS `removed`, `storage_pool`.`capacity_bytes` AS `capacity_bytes`, + `storage_pool`.`used_bytes` AS `used_bytes`, `storage_pool`.`capacity_iops` AS `capacity_iops`, + `storage_pool`.`used_iops` AS `used_iops`, `storage_pool`.`scope` AS `scope`, `storage_pool`.`hypervisor` AS `hypervisor`, `storage_pool`.`storage_provider_name` AS `storage_provider_name`, diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.template_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.template_view.sql index 40b416b16de..339e43860d8 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.template_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.template_view.sql @@ -50,6 +50,7 @@ SELECT `vm_template`.`sort_key` AS `sort_key`, `vm_template`.`removed` AS `removed`, `vm_template`.`enable_sshkey` AS `enable_sshkey`, + `vm_template`.`arch` AS `arch`, `parent_template`.`id` AS `parent_template_id`, `parent_template`.`uuid` AS `parent_template_uuid`, `source_template`.`id` AS `source_template_id`, diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.user_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.user_view.sql index 7eedc03712b..340cfa9055f 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.user_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.user_view.sql @@ -39,6 +39,7 @@ select user.incorrect_login_attempts, user.source, user.default, + user.api_key_access, account.id account_id, account.uuid account_uuid, account.account_name account_name, diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.user_vm_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.user_vm_view.sql index 62294ed5d89..430031b1d97 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.user_vm_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.user_vm_view.sql @@ -25,6 +25,7 @@ SELECT `vm_instance`.`name` AS `name`, `user_vm`.`display_name` AS `display_name`, `user_vm`.`user_data` AS `user_data`, + `user_vm`.`user_vm_type` AS `user_vm_type`, `account`.`id` AS `account_id`, `account`.`uuid` AS `account_uuid`, `account`.`account_name` AS `account_name`, @@ -53,6 +54,7 @@ SELECT `vm_instance`.`instance_name` AS `instance_name`, `vm_instance`.`guest_os_id` AS `guest_os_id`, `vm_instance`.`display_vm` AS `display_vm`, + `vm_instance`.`delete_protection` AS `delete_protection`, `guest_os`.`uuid` AS `guest_os_uuid`, `vm_instance`.`pod_id` AS `pod_id`, `host_pod_ref`.`uuid` AS `pod_uuid`, @@ -81,6 +83,7 @@ SELECT `iso`.`uuid` AS `iso_uuid`, `iso`.`name` AS `iso_name`, `iso`.`display_text` AS `iso_display_text`, + `vm_template`.`arch` AS `arch`, `service_offering`.`id` AS `service_offering_id`, `service_offering`.`uuid` AS `service_offering_uuid`, `disk_offering`.`uuid` AS `disk_offering_uuid`, diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.volume_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.volume_view.sql index 950dcddf4c7..ffeb93e8fa7 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.volume_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.volume_view.sql @@ -40,6 +40,7 @@ SELECT `volumes`.`chain_info` AS `chain_info`, `volumes`.`external_uuid` AS `external_uuid`, `volumes`.`encrypt_format` AS `encrypt_format`, + `volumes`.`delete_protection` AS `delete_protection`, `account`.`id` AS `account_id`, `account`.`uuid` AS `account_uuid`, `account`.`account_name` AS `account_name`, diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.vpc_offering_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.vpc_offering_view.sql index cb762a57883..c74d50590de 100644 --- a/engine/schema/src/main/resources/META-INF/db/views/cloud.vpc_offering_view.sql +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.vpc_offering_view.sql @@ -17,7 +17,6 @@ -- cloud.vpc_offering_view source - DROP VIEW IF EXISTS `cloud`.`vpc_offering_view`; CREATE VIEW `cloud`.`vpc_offering_view` AS @@ -29,6 +28,8 @@ select `vpc_offerings`.`display_text` AS `display_text`, `vpc_offerings`.`state` AS `state`, `vpc_offerings`.`default` AS `default`, + `vpc_offerings`.`for_nsx` AS `for_nsx`, + `vpc_offerings`.`network_mode` AS `network_mode`, `vpc_offerings`.`created` AS `created`, `vpc_offerings`.`removed` AS `removed`, `vpc_offerings`.`service_offering_id` AS `service_offering_id`, @@ -36,6 +37,8 @@ select `vpc_offerings`.`supports_region_level_vpc` AS `supports_region_level_vpc`, `vpc_offerings`.`redundant_router_service` AS `redundant_router_service`, `vpc_offerings`.`sort_key` AS `sort_key`, + `vpc_offerings`.`routing_mode` AS `routing_mode`, + `vpc_offerings`.`specify_as_number` AS `specify_as_number`, group_concat(distinct `domain`.`id` separator ',') AS `domain_id`, group_concat(distinct `domain`.`uuid` separator ',') AS `domain_uuid`, group_concat(distinct `domain`.`name` separator ',') AS `domain_name`, diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.webhook_delivery_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.webhook_delivery_view.sql new file mode 100644 index 00000000000..54ba52fba4a --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.webhook_delivery_view.sql @@ -0,0 +1,48 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. + +-- VIEW `cloud`.`webhook_delivery_view`; + +DROP VIEW IF EXISTS `cloud`.`webhook_delivery_view`; +CREATE VIEW `cloud`.`webhook_delivery_view` AS + SELECT + webhook_delivery.id, + webhook_delivery.uuid, + webhook_delivery.headers, + webhook_delivery.payload, + webhook_delivery.success, + webhook_delivery.response, + webhook_delivery.start_time, + webhook_delivery.end_time, + event.id event_id, + event.uuid event_uuid, + event.type event_type, + webhook.id webhook_id, + webhook.uuid webhook_uuid, + webhook.name webhook_name, + mshost.id mshost_id, + mshost.uuid mshost_uuid, + mshost.msid mshost_msid, + mshost.name mshost_name + FROM + `cloud`.`webhook_delivery` + INNER JOIN + `cloud`.`event` ON webhook_delivery.event_id = event.id + INNER JOIN + `cloud`.`webhook` ON webhook_delivery.webhook_id = webhook.id + LEFT JOIN + `cloud`.`mshost` ON mshost.msid = webhook_delivery.mshost_msid; diff --git a/engine/schema/src/main/resources/META-INF/db/views/cloud.webhook_view.sql b/engine/schema/src/main/resources/META-INF/db/views/cloud.webhook_view.sql new file mode 100644 index 00000000000..443463eec4b --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/views/cloud.webhook_view.sql @@ -0,0 +1,52 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you 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. + +-- VIEW `cloud`.`webhook_view`; + +DROP VIEW IF EXISTS `cloud`.`webhook_view`; +CREATE VIEW `cloud`.`webhook_view` AS + SELECT + webhook.id, + webhook.uuid, + webhook.name, + webhook.description, + webhook.state, + webhook.payload_url, + webhook.secret_key, + webhook.ssl_verification, + webhook.scope, + webhook.created, + webhook.removed, + account.id account_id, + account.uuid account_uuid, + account.account_name account_name, + account.type account_type, + domain.id domain_id, + domain.uuid domain_uuid, + domain.name domain_name, + domain.path domain_path, + projects.id project_id, + projects.uuid project_uuid, + projects.name project_name + FROM + `cloud`.`webhook` + INNER JOIN + `cloud`.`account` ON webhook.account_id = account.id + INNER JOIN + `cloud`.`domain` ON webhook.domain_id = domain.id + LEFT JOIN + `cloud`.`projects` ON projects.project_account_id = webhook.account_id; diff --git a/engine/schema/src/test/java/com/cloud/capacity/dao/CapacityDaoImplTest.java b/engine/schema/src/test/java/com/cloud/capacity/dao/CapacityDaoImplTest.java new file mode 100644 index 00000000000..76c1092546a --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/capacity/dao/CapacityDaoImplTest.java @@ -0,0 +1,99 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.capacity.dao; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.capacity.CapacityVO; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@RunWith(MockitoJUnitRunner.class) +public class CapacityDaoImplTest { + @Spy + @InjectMocks + CapacityDaoImpl capacityDao = new CapacityDaoImpl(); + + private SearchBuilder searchBuilder; + private SearchCriteria searchCriteria; + + @Before + public void setUp() { + searchBuilder = mock(SearchBuilder.class); + CapacityVO capacityVO = mock(CapacityVO.class); + when(searchBuilder.entity()).thenReturn(capacityVO); + searchCriteria = mock(SearchCriteria.class); + doReturn(searchBuilder).when(capacityDao).createSearchBuilder(); + when(searchBuilder.create()).thenReturn(searchCriteria); + } + + @Test + public void testListByHostIdTypes() { + // Prepare inputs + Long hostId = 1L; + List capacityTypes = Arrays.asList((short)1, (short)2); + CapacityVO capacity1 = new CapacityVO(); + CapacityVO capacity2 = new CapacityVO(); + List mockResult = Arrays.asList(capacity1, capacity2); + doReturn(mockResult).when(capacityDao).listBy(any(SearchCriteria.class)); + List result = capacityDao.listByHostIdTypes(hostId, capacityTypes); + verify(searchBuilder).and(eq("hostId"), any(), eq(SearchCriteria.Op.EQ)); + verify(searchBuilder).and(eq("type"), any(), eq(SearchCriteria.Op.IN)); + verify(searchBuilder).done(); + verify(searchCriteria).setParameters("hostId", hostId); + verify(searchCriteria).setParameters("type", capacityTypes.toArray()); + verify(capacityDao).listBy(searchCriteria); + assertEquals(2, result.size()); + assertSame(capacity1, result.get(0)); + assertSame(capacity2, result.get(1)); + } + + @Test + public void testListByHostIdTypesEmptyResult() { + Long hostId = 1L; + List capacityTypes = Arrays.asList((short)1, (short)2); + doReturn(Collections.emptyList()).when(capacityDao).listBy(any(SearchCriteria.class)); + List result = capacityDao.listByHostIdTypes(hostId, capacityTypes); + verify(searchBuilder).and(Mockito.eq("hostId"), any(), eq(SearchCriteria.Op.EQ)); + verify(searchBuilder).and(eq("type"), any(), eq(SearchCriteria.Op.IN)); + verify(searchBuilder).done(); + verify(searchCriteria).setParameters("hostId", hostId); + verify(searchCriteria).setParameters("type", capacityTypes.toArray()); + verify(capacityDao).listBy(searchCriteria); + assertTrue(result.isEmpty()); + } +} diff --git a/engine/schema/src/test/java/com/cloud/dc/dao/ClusterDaoImplTest.java b/engine/schema/src/test/java/com/cloud/dc/dao/ClusterDaoImplTest.java new file mode 100644 index 00000000000..f8673fa9c9f --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/dc/dao/ClusterDaoImplTest.java @@ -0,0 +1,118 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.dc.dao; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.cpu.CPU; +import com.cloud.dc.ClusterVO; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.utils.Pair; +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@RunWith(MockitoJUnitRunner.class) +public class ClusterDaoImplTest { + @Spy + @InjectMocks + ClusterDaoImpl clusterDao = new ClusterDaoImpl(); + + private GenericSearchBuilder genericSearchBuilder; + + @Before + public void setUp() { + genericSearchBuilder = mock(SearchBuilder.class); + ClusterVO entityVO = mock(ClusterVO.class); + when(genericSearchBuilder.entity()).thenReturn(entityVO); + doReturn(genericSearchBuilder).when(clusterDao).createSearchBuilder(Long.class); + } + + @Test + public void testListAllIds() { + List mockIds = Arrays.asList(1L, 2L, 3L); + doReturn(mockIds).when(clusterDao).customSearch(any(), isNull()); + List result = clusterDao.listAllIds(); + verify(clusterDao).customSearch(genericSearchBuilder.create(), null); + assertEquals(3, result.size()); + assertEquals(Long.valueOf(1L), result.get(0)); + assertEquals(Long.valueOf(2L), result.get(1)); + assertEquals(Long.valueOf(3L), result.get(2)); + } + + @Test + public void testListAllIdsEmptyResult() { + doReturn(Collections.emptyList()).when(clusterDao).customSearch(any(), isNull()); + List result = clusterDao.listAllIds(); + verify(clusterDao).customSearch(genericSearchBuilder.create(), null); + assertTrue(result.isEmpty()); + } + + @Test + public void listDistinctHypervisorsArchAcrossClusters_WithZone() { + Long zoneId = 123L; + ClusterVO cluster1 = mock(ClusterVO.class); + when(cluster1.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.XenServer); + when(cluster1.getArch()).thenReturn(CPU.CPUArch.amd64); + ClusterVO cluster2 = mock(ClusterVO.class); + when(cluster2.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + when(cluster2.getArch()).thenReturn(CPU.CPUArch.arm64); + List dummyHosts = Arrays.asList(cluster1, cluster2); + doReturn(dummyHosts).when(clusterDao).search(any(SearchCriteria.class), isNull()); + List> result = clusterDao.listDistinctHypervisorsArchAcrossClusters(zoneId); + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals(Hypervisor.HypervisorType.XenServer, result.get(0).first()); + assertEquals(CPU.CPUArch.amd64, result.get(0).second()); + assertEquals(Hypervisor.HypervisorType.KVM, result.get(1).first()); + assertEquals(CPU.CPUArch.arm64, result.get(1).second()); + } + + @Test + public void listDistinctHypervisorsArchAcrossClusters_WithoutZone() { + Long zoneId = null; + ClusterVO cluster = mock(ClusterVO.class); + when(cluster.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.VMware); + when(cluster.getArch()).thenReturn(CPU.CPUArch.amd64); + List dummyHosts = Collections.singletonList(cluster); + doReturn(dummyHosts).when(clusterDao).search(any(SearchCriteria.class), isNull()); + List> result = clusterDao.listDistinctHypervisorsArchAcrossClusters(zoneId); + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(Hypervisor.HypervisorType.VMware, result.get(0).first()); + assertEquals(CPU.CPUArch.amd64, result.get(0).second()); + } +} diff --git a/engine/schema/src/test/java/com/cloud/host/HostVOTest.java b/engine/schema/src/test/java/com/cloud/host/HostVOTest.java index 76bc5270b4f..3262c4cc291 100755 --- a/engine/schema/src/test/java/com/cloud/host/HostVOTest.java +++ b/engine/schema/src/test/java/com/cloud/host/HostVOTest.java @@ -1,84 +1,149 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you 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. -package com.cloud.host; - -import com.cloud.service.ServiceOfferingVO; -import com.cloud.vm.VirtualMachine; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Test; -import org.junit.Before; - -public class HostVOTest { - HostVO host; - ServiceOfferingVO offering; - - @Before - public void setUp() throws Exception { - host = new HostVO(); - offering = new ServiceOfferingVO("TestSO", 0, 0, 0, 0, 0, - false, "TestSO", false,VirtualMachine.Type.User,false); - } - - @Test - public void testNoSO() { - assertFalse(host.checkHostServiceOfferingTags(null)); - } - - @Test - public void testNoTag() { - assertTrue(host.checkHostServiceOfferingTags(offering)); - } - - @Test - public void testRightTag() { - host.setHostTags(Arrays.asList("tag1","tag2"), false); - offering.setHostTag("tag2,tag1"); - assertTrue(host.checkHostServiceOfferingTags(offering)); - } - - @Test - public void testWrongTag() { - host.setHostTags(Arrays.asList("tag1","tag2"), false); - offering.setHostTag("tag2,tag4"); - assertFalse(host.checkHostServiceOfferingTags(offering)); - } - - @Test - public void checkHostServiceOfferingTagsTestRuleTagWithServiceTagThatMatches() { - host.setHostTags(List.of("tags[0] == 'A'"), true); - offering.setHostTag("A"); - assertTrue(host.checkHostServiceOfferingTags(offering)); - } - - @Test - public void checkHostServiceOfferingTagsTestRuleTagWithServiceTagThatDoesNotMatch() { - host.setHostTags(List.of("tags[0] == 'A'"), true); - offering.setHostTag("B"); - assertFalse(host.checkHostServiceOfferingTags(offering)); - } - - @Test - public void checkHostServiceOfferingTagsTestRuleTagWithNullServiceTag() { - host.setHostTags(List.of("tags[0] == 'A'"), true); - offering.setHostTag(null); - assertFalse(host.checkHostServiceOfferingTags(offering)); - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.host; + +import com.cloud.offering.ServiceOffering; +import com.cloud.service.ServiceOfferingVO; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.vm.VirtualMachine; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class HostVOTest { + HostVO host; + ServiceOfferingVO offering; + + @Before + public void setUp() throws Exception { + host = new HostVO(); + offering = new ServiceOfferingVO("TestSO", 0, 0, 0, 0, 0, + false, "TestSO", false, VirtualMachine.Type.User, false); + } + + @Test + public void testNoSO() { + assertFalse(host.checkHostServiceOfferingTags(null)); + } + + @Test + public void testNoTag() { + assertTrue(host.checkHostServiceOfferingTags(offering)); + } + + @Test + public void testRightTag() { + host.setHostTags(Arrays.asList("tag1", "tag2"), false); + offering.setHostTag("tag2,tag1"); + assertTrue(host.checkHostServiceOfferingTags(offering)); + } + + @Test + public void testWrongTag() { + host.setHostTags(Arrays.asList("tag1", "tag2"), false); + offering.setHostTag("tag2,tag4"); + assertFalse(host.checkHostServiceOfferingTags(offering)); + } + + @Test + public void checkHostServiceOfferingTagsTestRuleTagWithServiceTagThatMatches() { + host.setHostTags(List.of("tags[0] == 'A'"), true); + offering.setHostTag("A"); + assertTrue(host.checkHostServiceOfferingTags(offering)); + } + + @Test + public void checkHostServiceOfferingTagsTestRuleTagWithServiceTagThatDoesNotMatch() { + host.setHostTags(List.of("tags[0] == 'A'"), true); + offering.setHostTag("B"); + assertFalse(host.checkHostServiceOfferingTags(offering)); + } + + @Test + public void checkHostServiceOfferingTagsTestRuleTagWithNullServiceTag() { + host.setHostTags(List.of("tags[0] == 'A'"), true); + offering.setHostTag(null); + assertFalse(host.checkHostServiceOfferingTags(offering)); + } + + @Test + public void testEitherNoSOOrTemplate() { + assertFalse(host.checkHostServiceOfferingAndTemplateTags(null, Mockito.mock(VirtualMachineTemplate.class), null)); + assertFalse(host.checkHostServiceOfferingAndTemplateTags(Mockito.mock(ServiceOffering.class), null, null)); + } + + @Test + public void testNoTagOfferingTemplate() { + assertTrue(host.checkHostServiceOfferingAndTemplateTags(offering, Mockito.mock(VirtualMachineTemplate.class), Collections.emptySet())); + assertTrue(host.getHostServiceOfferingAndTemplateMissingTags(offering, Mockito.mock(VirtualMachineTemplate.class), Collections.emptySet()).isEmpty()); + assertTrue(host.checkHostServiceOfferingAndTemplateTags(offering, Mockito.mock(VirtualMachineTemplate.class), Set.of("tag1", "tag2"))); + assertTrue(host.getHostServiceOfferingAndTemplateMissingTags(offering, Mockito.mock(VirtualMachineTemplate.class), Set.of("tag1", "tag2")).isEmpty()); + } + + @Test + public void testRightTagOfferingTemplate() { + host.setHostTags(Arrays.asList("tag1", "tag2"), false); + offering.setHostTag("tag2,tag1"); + assertTrue(host.checkHostServiceOfferingAndTemplateTags(offering, Mockito.mock(VirtualMachineTemplate.class), Set.of("tag1"))); + Set actualMissingTags = host.getHostServiceOfferingAndTemplateMissingTags(offering, Mockito.mock(VirtualMachineTemplate.class), Set.of("tag1")); + assertTrue(actualMissingTags.isEmpty()); + + host.setHostTags(Arrays.asList("tag1", "tag2", "tag3"), false); + offering.setHostTag("tag2,tag1"); + VirtualMachineTemplate template = Mockito.mock(VirtualMachineTemplate.class); + Mockito.when(template.getTemplateTag()).thenReturn("tag3"); + assertTrue(host.checkHostServiceOfferingAndTemplateTags(offering, template, Set.of("tag2", "tag3"))); + actualMissingTags = host.getHostServiceOfferingAndTemplateMissingTags(offering, template, Set.of("tag2", "tag3")); + assertTrue(actualMissingTags.isEmpty()); + host.setHostTags(List.of("tag3"), false); + offering.setHostTag(null); + assertTrue(host.checkHostServiceOfferingAndTemplateTags(offering, template, Set.of("tag3"))); + actualMissingTags = host.getHostServiceOfferingAndTemplateMissingTags(offering, template, Set.of("tag3")); + assertTrue(actualMissingTags.isEmpty()); + + assertTrue(host.checkHostServiceOfferingAndTemplateTags(offering, template, Set.of("tag2", "tag1"))); + actualMissingTags = host.getHostServiceOfferingAndTemplateMissingTags(offering, template, Set.of("tag2", "tag1")); + assertTrue(actualMissingTags.isEmpty()); + } + + @Test + public void testWrongOfferingTag() { + host.setHostTags(Arrays.asList("tag1", "tag2"), false); + offering.setHostTag("tag2,tag4"); + VirtualMachineTemplate template = Mockito.mock(VirtualMachineTemplate.class); + Mockito.when(template.getTemplateTag()).thenReturn("tag1"); + assertFalse(host.checkHostServiceOfferingAndTemplateTags(offering, template, Set.of("tag1", "tag2", "tag3", "tag4"))); + Set actualMissingTags = host.getHostServiceOfferingAndTemplateMissingTags(offering, template, Set.of("tag1", "tag2", "tag3", "tag4")); + assertEquals(Set.of("tag4"), actualMissingTags); + + offering.setHostTag("tag1,tag2"); + template = Mockito.mock(VirtualMachineTemplate.class); + Mockito.when(template.getTemplateTag()).thenReturn("tag3"); + actualMissingTags = host.getHostServiceOfferingAndTemplateMissingTags(offering, template, Set.of("tag1", "tag2", "tag3", "tag4")); + assertFalse(host.checkHostServiceOfferingAndTemplateTags(offering, template, Set.of("tag1", "tag2", "tag3", "tag4"))); + assertEquals(Set.of("tag3"), actualMissingTags); + } +} diff --git a/engine/schema/src/test/java/com/cloud/host/dao/HostDaoImplTest.java b/engine/schema/src/test/java/com/cloud/host/dao/HostDaoImplTest.java new file mode 100644 index 00000000000..ad37ef38830 --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/host/dao/HostDaoImplTest.java @@ -0,0 +1,250 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.host.dao; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.cpu.CPU; +import com.cloud.host.Host; +import com.cloud.host.HostVO; +import com.cloud.host.Status; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.resource.ResourceState; +import com.cloud.utils.Pair; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@RunWith(MockitoJUnitRunner.class) +public class HostDaoImplTest { + + @Spy + HostDaoImpl hostDao = new HostDaoImpl(); + + @Mock + private SearchBuilder mockSearchBuilder; + @Mock + private SearchCriteria mockSearchCriteria; + + @Test + public void testCountUpAndEnabledHostsInZone() { + long testZoneId = 100L; + hostDao.HostTypeCountSearch = mockSearchBuilder; + when(mockSearchBuilder.create()).thenReturn(mockSearchCriteria); + Mockito.doNothing().when(mockSearchCriteria).setParameters(Mockito.anyString(), any()); + int expected = 5; + doReturn(expected).when(hostDao).getCount(mockSearchCriteria); + Integer count = hostDao.countUpAndEnabledHostsInZone(testZoneId); + Assert.assertSame(expected, count); + Mockito.verify(mockSearchCriteria).setParameters("type", Host.Type.Routing); + Mockito.verify(mockSearchCriteria).setParameters("resourceState", ResourceState.Enabled); + Mockito.verify(mockSearchCriteria).setParameters("zoneId", testZoneId); + Mockito.verify(hostDao).getCount(mockSearchCriteria); + } + + @Test + public void testCountAllHostsAndCPUSocketsByType() { + Host.Type type = Host.Type.Routing; + GenericDaoBase.SumCount mockSumCount = new GenericDaoBase.SumCount(); + mockSumCount.count = 10; + mockSumCount.sum = 20; + HostVO host = mock(HostVO.class); + GenericSearchBuilder sb = mock(GenericSearchBuilder.class); + when(sb.entity()).thenReturn(host); + doReturn(sb).when(hostDao).createSearchBuilder(GenericDaoBase.SumCount.class); + SearchCriteria sc = mock(SearchCriteria.class); + when(sb.create()).thenReturn(sc); + doReturn(List.of(mockSumCount)).when(hostDao).customSearch(any(SearchCriteria.class), any()); + Pair result = hostDao.countAllHostsAndCPUSocketsByType(type); + assertEquals(10, result.first().intValue()); + assertEquals(20, result.second().intValue()); + Mockito.verify(sc).setParameters("type", type); + } + + @Test + public void testIsHostUp() { + long testHostId = 101L; + List statuses = List.of(Status.Up); + HostVO host = mock(HostVO.class); + GenericSearchBuilder sb = mock(GenericSearchBuilder.class); + when(sb.entity()).thenReturn(host); + SearchCriteria sc = mock(SearchCriteria.class); + when(sb.create()).thenReturn(sc); + doReturn(sb).when(hostDao).createSearchBuilder(Status.class); + doReturn(statuses).when(hostDao).customSearch(any(SearchCriteria.class), any()); + boolean result = hostDao.isHostUp(testHostId); + Assert.assertTrue("Host should be up", result); + Mockito.verify(sc).setParameters("id", testHostId); + Mockito.verify(hostDao).customSearch(sc, null); + } + + @Test + public void testFindHostIdsByZoneClusterResourceStateTypeAndHypervisorType() { + Long zoneId = 1L; + Long clusterId = 2L; + List resourceStates = List.of(ResourceState.Enabled); + List types = List.of(Host.Type.Routing); + List hypervisorTypes = List.of(Hypervisor.HypervisorType.KVM); + List mockResults = List.of(1001L, 1002L); // Mocked result + HostVO host = mock(HostVO.class); + GenericSearchBuilder sb = mock(GenericSearchBuilder.class); + when(sb.entity()).thenReturn(host); + SearchCriteria sc = mock(SearchCriteria.class); + when(sb.create()).thenReturn(sc); + when(sb.and()).thenReturn(sb); + doReturn(sb).when(hostDao).createSearchBuilder(Long.class); + doReturn(mockResults).when(hostDao).customSearch(any(SearchCriteria.class), any()); + List hostIds = hostDao.findHostIdsByZoneClusterResourceStateTypeAndHypervisorType( + zoneId, clusterId, resourceStates, types, hypervisorTypes); + assertEquals(mockResults, hostIds); + Mockito.verify(sc).setParameters("zoneId", zoneId); + Mockito.verify(sc).setParameters("clusterId", clusterId); + Mockito.verify(sc).setParameters("resourceState", resourceStates.toArray()); + Mockito.verify(sc).setParameters("type", types.toArray()); + Mockito.verify(sc).setParameters("hypervisorTypes", hypervisorTypes.toArray()); + } + + @Test + public void testListDistinctHypervisorTypes() { + Long zoneId = 1L; + List mockResults = List.of(Hypervisor.HypervisorType.KVM, Hypervisor.HypervisorType.XenServer); + HostVO host = mock(HostVO.class); + GenericSearchBuilder sb = mock(GenericSearchBuilder.class); + when(sb.entity()).thenReturn(host); + SearchCriteria sc = mock(SearchCriteria.class); + when(sb.create()).thenReturn(sc); + doReturn(sb).when(hostDao).createSearchBuilder(String.class); + doReturn(mockResults.stream().map(h -> h.name()).collect(Collectors.toList())).when(hostDao) + .customSearch(any(SearchCriteria.class), any()); + List hypervisorTypes = hostDao.listDistinctHypervisorTypes(zoneId); + assertEquals(mockResults, hypervisorTypes); + Mockito.verify(sc).setParameters("zoneId", zoneId); + Mockito.verify(sc).setParameters("type", Host.Type.Routing); + } + + @Test + public void testListByIds() { + List ids = List.of(101L, 102L); + List mockResults = List.of(mock(HostVO.class), mock(HostVO.class)); + hostDao.IdsSearch = mockSearchBuilder; + when(mockSearchBuilder.create()).thenReturn(mockSearchCriteria); + doReturn(mockResults).when(hostDao).search(any(SearchCriteria.class), any()); + List hosts = hostDao.listByIds(ids); + assertEquals(mockResults, hosts); + Mockito.verify(mockSearchCriteria).setParameters("id", ids.toArray()); + Mockito.verify(hostDao).search(mockSearchCriteria, null); + } + + @Test + public void testListIdsBy() { + Host.Type type = Host.Type.Routing; + Status status = Status.Up; + ResourceState resourceState = ResourceState.Enabled; + Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.KVM; + Long zoneId = 1L, podId = 2L, clusterId = 3L; + List mockResults = List.of(1001L, 1002L); + HostVO host = mock(HostVO.class); + GenericSearchBuilder sb = mock(GenericSearchBuilder.class); + when(sb.entity()).thenReturn(host); + SearchCriteria sc = mock(SearchCriteria.class); + when(sb.create()).thenReturn(sc); + doReturn(sb).when(hostDao).createSearchBuilder(Long.class); + doReturn(mockResults).when(hostDao).customSearch(any(SearchCriteria.class), any()); + List hostIds = hostDao.listIdsBy(type, status, resourceState, hypervisorType, zoneId, podId, clusterId); + assertEquals(mockResults, hostIds); + Mockito.verify(sc).setParameters("type", type); + Mockito.verify(sc).setParameters("status", status); + Mockito.verify(sc).setParameters("resourceState", resourceState); + Mockito.verify(sc).setParameters("hypervisorType", hypervisorType); + Mockito.verify(sc).setParameters("zoneId", zoneId); + Mockito.verify(sc).setParameters("podId", podId); + Mockito.verify(sc).setParameters("clusterId", clusterId); + } + + @Test + public void testListDistinctHypervisorArchTypes_WithZone() { + Long zoneId = 123L; + HostVO host1 = mock(HostVO.class); + when(host1.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.XenServer); + when(host1.getArch()).thenReturn(CPU.CPUArch.amd64); + HostVO host2 = mock(HostVO.class); + when(host2.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + when(host2.getArch()).thenReturn(CPU.CPUArch.arm64); + List dummyHosts = Arrays.asList(host1, host2); + doReturn(dummyHosts).when(hostDao).search(any(SearchCriteria.class), isNull()); + List> result = hostDao.listDistinctHypervisorArchTypes(zoneId); + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals(Hypervisor.HypervisorType.XenServer, result.get(0).first()); + assertEquals(CPU.CPUArch.amd64, result.get(0).second()); + assertEquals(Hypervisor.HypervisorType.KVM, result.get(1).first()); + assertEquals(CPU.CPUArch.arm64, result.get(1).second()); + } + + @Test + public void testListDistinctHypervisorArchTypes_WithoutZone() { + Long zoneId = null; + HostVO host1 = mock(HostVO.class); + when(host1.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.VMware); + when(host1.getArch()).thenReturn(CPU.CPUArch.amd64); + List dummyHosts = Collections.singletonList(host1); + doReturn(dummyHosts).when(hostDao).search(any(SearchCriteria.class), isNull()); + List> result = hostDao.listDistinctHypervisorArchTypes(zoneId); + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(Hypervisor.HypervisorType.VMware, result.get(0).first()); + assertEquals(CPU.CPUArch.amd64, result.get(0).second()); + } + + @Test + public void testListDistinctArchTypes() { + Long clusterId = 1L; + List mockResults = List.of(CPU.CPUArch.amd64, CPU.CPUArch.arm64); + HostVO host = mock(HostVO.class); + GenericSearchBuilder sb = mock(GenericSearchBuilder.class); + when(sb.entity()).thenReturn(host); + SearchCriteria sc = mock(SearchCriteria.class); + when(sb.create()).thenReturn(sc); + doReturn(sb).when(hostDao).createSearchBuilder(String.class); + doReturn(mockResults.stream().map(h -> h.getType()).collect(Collectors.toList())).when(hostDao) + .customSearch(any(SearchCriteria.class), any()); + List hypervisorTypes = hostDao.listDistinctArchTypes(clusterId); + assertEquals(mockResults, hypervisorTypes); + Mockito.verify(sc).setParameters("clusterId", clusterId); + Mockito.verify(sc).setParameters("type", Host.Type.Routing); + } +} diff --git a/engine/schema/src/test/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImplTest.java b/engine/schema/src/test/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImplTest.java index e13ad42ec80..6de8960ae74 100644 --- a/engine/schema/src/test/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImplTest.java +++ b/engine/schema/src/test/java/com/cloud/network/as/dao/AutoScaleVmGroupVmMapDaoImplTest.java @@ -19,11 +19,9 @@ package com.cloud.network.as.dao; -import com.cloud.network.as.AutoScaleVmGroupVmMapVO; -import com.cloud.utils.db.GenericSearchBuilder; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.vm.VirtualMachine; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.junit.Assert; import org.junit.Before; @@ -33,9 +31,13 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; -import java.util.Arrays; -import java.util.List; +import com.cloud.network.as.AutoScaleVmGroupVmMapVO; +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.vm.VirtualMachine; @RunWith(MockitoJUnitRunner.class) public class AutoScaleVmGroupVmMapDaoImplTest { @@ -198,4 +200,33 @@ public class AutoScaleVmGroupVmMapDaoImplTest { Mockito.verify(searchCriteriaAutoScaleVmGroupVmMapVOMock).setParameters("vmGroupId", groupId); Mockito.verify(AutoScaleVmGroupVmMapDaoImplSpy).remove(searchCriteriaAutoScaleVmGroupVmMapVOMock); } + + @Test + public void testExpungeByVmListNoVms() { + Assert.assertEquals(0, AutoScaleVmGroupVmMapDaoImplSpy.expungeByVmList( + new ArrayList<>(), 100L)); + Assert.assertEquals(0, AutoScaleVmGroupVmMapDaoImplSpy.expungeByVmList( + null, 100L)); + } + + @Test + public void testExpungeByVmList() { + SearchBuilder sb = Mockito.mock(SearchBuilder.class); + SearchCriteria sc = Mockito.mock(SearchCriteria.class); + Mockito.when(sb.create()).thenReturn(sc); + Mockito.doAnswer((Answer) invocationOnMock -> { + Long batchSize = (Long)invocationOnMock.getArguments()[1]; + return batchSize == null ? 0 : batchSize.intValue(); + }).when(AutoScaleVmGroupVmMapDaoImplSpy).batchExpunge(Mockito.any(SearchCriteria.class), Mockito.anyLong()); + Mockito.when(AutoScaleVmGroupVmMapDaoImplSpy.createSearchBuilder()).thenReturn(sb); + final AutoScaleVmGroupVmMapVO mockedVO = Mockito.mock(AutoScaleVmGroupVmMapVO.class); + Mockito.when(sb.entity()).thenReturn(mockedVO); + List vmIds = List.of(1L, 2L); + Object[] array = vmIds.toArray(); + Long batchSize = 50L; + Assert.assertEquals(batchSize.intValue(), AutoScaleVmGroupVmMapDaoImplSpy.expungeByVmList(List.of(1L, 2L), batchSize)); + Mockito.verify(sc).setParameters("vmIds", array); + Mockito.verify(AutoScaleVmGroupVmMapDaoImplSpy, Mockito.times(1)) + .batchExpunge(sc, batchSize); + } } diff --git a/engine/schema/src/test/java/com/cloud/network/dao/IPAddressDaoImplTest.java b/engine/schema/src/test/java/com/cloud/network/dao/IPAddressDaoImplTest.java new file mode 100644 index 00000000000..d8f6a08d8d3 --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/network/dao/IPAddressDaoImplTest.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.network.dao; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; + +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@RunWith(MockitoJUnitRunner.class) +public class IPAddressDaoImplTest { + + @Spy + IPAddressDaoImpl ipAddressDaoImplSpy; + + @Test + public void testExpungeByVmListNoVms() { + Assert.assertEquals(0, ipAddressDaoImplSpy.expungeByVmList( + new ArrayList<>(), 100L)); + Assert.assertEquals(0, ipAddressDaoImplSpy.expungeByVmList( + null, 100L)); + } + + @Test + public void testExpungeByVmList() { + SearchBuilder sb = Mockito.mock(SearchBuilder.class); + SearchCriteria sc = Mockito.mock(SearchCriteria.class); + Mockito.when(sb.create()).thenReturn(sc); + Mockito.doAnswer((Answer) invocationOnMock -> { + Long batchSize = (Long)invocationOnMock.getArguments()[1]; + return batchSize == null ? 0 : batchSize.intValue(); + }).when(ipAddressDaoImplSpy).batchExpunge(Mockito.any(SearchCriteria.class), Mockito.anyLong()); + Mockito.when(ipAddressDaoImplSpy.createSearchBuilder()).thenReturn(sb); + final IPAddressVO mockedVO = Mockito.mock(IPAddressVO.class); + Mockito.when(sb.entity()).thenReturn(mockedVO); + List vmIds = List.of(1L, 2L); + Object[] array = vmIds.toArray(); + Long batchSize = 50L; + Assert.assertEquals(batchSize.intValue(), ipAddressDaoImplSpy.expungeByVmList(List.of(1L, 2L), batchSize)); + Mockito.verify(sc).setParameters("vmIds", array); + Mockito.verify(ipAddressDaoImplSpy, Mockito.times(1)) + .batchExpunge(sc, batchSize); + } +} diff --git a/engine/schema/src/test/java/com/cloud/network/dao/InlineLoadBalancerNicMapDaoImplTest.java b/engine/schema/src/test/java/com/cloud/network/dao/InlineLoadBalancerNicMapDaoImplTest.java new file mode 100644 index 00000000000..8e06c7618f6 --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/network/dao/InlineLoadBalancerNicMapDaoImplTest.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.network.dao; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; + +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@RunWith(MockitoJUnitRunner.class) +public class InlineLoadBalancerNicMapDaoImplTest { + + @Spy + InlineLoadBalancerNicMapDaoImpl inlineLoadBalancerNicMapDaoImplSpy; + + @Test + public void testExpungeByNicListNoVms() { + Assert.assertEquals(0, inlineLoadBalancerNicMapDaoImplSpy.expungeByNicList( + new ArrayList<>(), 100L)); + Assert.assertEquals(0, inlineLoadBalancerNicMapDaoImplSpy.expungeByNicList( + null, 100L)); + } + + @Test + public void testExpungeByNicList() { + SearchBuilder sb = Mockito.mock(SearchBuilder.class); + SearchCriteria sc = Mockito.mock(SearchCriteria.class); + Mockito.when(sb.create()).thenReturn(sc); + Mockito.doAnswer((Answer) invocationOnMock -> { + Long batchSize = (Long)invocationOnMock.getArguments()[1]; + return batchSize == null ? 0 : batchSize.intValue(); + }).when(inlineLoadBalancerNicMapDaoImplSpy).batchExpunge(Mockito.any(SearchCriteria.class), Mockito.anyLong()); + Mockito.when(inlineLoadBalancerNicMapDaoImplSpy.createSearchBuilder()).thenReturn(sb); + final InlineLoadBalancerNicMapVO mockedVO = Mockito.mock(InlineLoadBalancerNicMapVO.class); + Mockito.when(sb.entity()).thenReturn(mockedVO); + List vmIds = List.of(1L, 2L); + Object[] array = vmIds.toArray(); + Long batchSize = 50L; + Assert.assertEquals(batchSize.intValue(), inlineLoadBalancerNicMapDaoImplSpy.expungeByNicList(List.of(1L, 2L), batchSize)); + Mockito.verify(sc).setParameters("nicIds", array); + Mockito.verify(inlineLoadBalancerNicMapDaoImplSpy, Mockito.times(1)) + .batchExpunge(sc, batchSize); + } +} diff --git a/engine/schema/src/test/java/com/cloud/network/dao/LoadBalancerVMMapDaoImplTest.java b/engine/schema/src/test/java/com/cloud/network/dao/LoadBalancerVMMapDaoImplTest.java new file mode 100644 index 00000000000..fa957194903 --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/network/dao/LoadBalancerVMMapDaoImplTest.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.network.dao; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; + +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@RunWith(MockitoJUnitRunner.class) +public class LoadBalancerVMMapDaoImplTest { + + @Spy + LoadBalancerVMMapDaoImpl loadBalancerVMMapDaoImplSpy; + + @Test + public void testExpungeByVmListNoVms() { + Assert.assertEquals(0, loadBalancerVMMapDaoImplSpy.expungeByVmList( + new ArrayList<>(), 100L)); + Assert.assertEquals(0, loadBalancerVMMapDaoImplSpy.expungeByVmList( + null, 100L)); + } + + @Test + public void testExpungeByVmList() { + SearchBuilder sb = Mockito.mock(SearchBuilder.class); + SearchCriteria sc = Mockito.mock(SearchCriteria.class); + Mockito.when(sb.create()).thenReturn(sc); + Mockito.doAnswer((Answer) invocationOnMock -> { + Long batchSize = (Long)invocationOnMock.getArguments()[1]; + return batchSize == null ? 0 : batchSize.intValue(); + }).when(loadBalancerVMMapDaoImplSpy).batchExpunge(Mockito.any(SearchCriteria.class), Mockito.anyLong()); + Mockito.when(loadBalancerVMMapDaoImplSpy.createSearchBuilder()).thenReturn(sb); + final LoadBalancerVMMapVO mockedVO = Mockito.mock(LoadBalancerVMMapVO.class); + Mockito.when(sb.entity()).thenReturn(mockedVO); + List vmIds = List.of(1L, 2L); + Object[] array = vmIds.toArray(); + Long batchSize = 50L; + Assert.assertEquals(batchSize.intValue(), loadBalancerVMMapDaoImplSpy.expungeByVmList(List.of(1L, 2L), batchSize)); + Mockito.verify(sc).setParameters("vmIds", array); + Mockito.verify(loadBalancerVMMapDaoImplSpy, Mockito.times(1)) + .batchExpunge(sc, batchSize); + } +} diff --git a/engine/schema/src/test/java/com/cloud/network/dao/OpRouterMonitorServiceDaoImplTest.java b/engine/schema/src/test/java/com/cloud/network/dao/OpRouterMonitorServiceDaoImplTest.java new file mode 100644 index 00000000000..7d0b1b069ba --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/network/dao/OpRouterMonitorServiceDaoImplTest.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.network.dao; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; + +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@RunWith(MockitoJUnitRunner.class) +public class OpRouterMonitorServiceDaoImplTest { + + @Spy + OpRouterMonitorServiceDaoImpl opRouterMonitorServiceDaoImplSpy; + + @Test + public void testExpungeByVmListNoVms() { + Assert.assertEquals(0, opRouterMonitorServiceDaoImplSpy.expungeByVmList( + new ArrayList<>(), 100L)); + Assert.assertEquals(0, opRouterMonitorServiceDaoImplSpy.expungeByVmList( + null, 100L)); + } + + @Test + public void testExpungeByVmList() { + SearchBuilder sb = Mockito.mock(SearchBuilder.class); + SearchCriteria sc = Mockito.mock(SearchCriteria.class); + Mockito.when(sb.create()).thenReturn(sc); + Mockito.doAnswer((Answer) invocationOnMock -> { + Long batchSize = (Long)invocationOnMock.getArguments()[1]; + return batchSize == null ? 0 : batchSize.intValue(); + }).when(opRouterMonitorServiceDaoImplSpy).batchExpunge(Mockito.any(SearchCriteria.class), Mockito.anyLong()); + Mockito.when(opRouterMonitorServiceDaoImplSpy.createSearchBuilder()).thenReturn(sb); + final OpRouterMonitorServiceVO mockedVO = Mockito.mock(OpRouterMonitorServiceVO.class); + Mockito.when(sb.entity()).thenReturn(mockedVO); + List vmIds = List.of(1L, 2L); + Object[] array = vmIds.toArray(); + Long batchSize = 50L; + Assert.assertEquals(batchSize.intValue(), opRouterMonitorServiceDaoImplSpy.expungeByVmList(List.of(1L, 2L), batchSize)); + Mockito.verify(sc).setParameters("vmIds", array); + Mockito.verify(opRouterMonitorServiceDaoImplSpy, Mockito.times(1)) + .batchExpunge(sc, batchSize); + } +} diff --git a/engine/schema/src/test/java/com/cloud/network/rules/dao/PortForwardingRulesDaoImplTest.java b/engine/schema/src/test/java/com/cloud/network/rules/dao/PortForwardingRulesDaoImplTest.java new file mode 100644 index 00000000000..c60e9b1f1bf --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/network/rules/dao/PortForwardingRulesDaoImplTest.java @@ -0,0 +1,68 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.network.rules.dao; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; + +import com.cloud.network.rules.PortForwardingRuleVO; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@RunWith(MockitoJUnitRunner.class) +public class PortForwardingRulesDaoImplTest { + + @Spy + PortForwardingRulesDaoImpl portForwardingRulesDaoImplSpy; + + @Test + public void testExpungeByVmListNoVms() { + Assert.assertEquals(0, portForwardingRulesDaoImplSpy.expungeByVmList( + new ArrayList<>(), 100L)); + Assert.assertEquals(0, portForwardingRulesDaoImplSpy.expungeByVmList( + null, 100L)); + } + + @Test + public void testExpungeByVmList() { + SearchBuilder sb = Mockito.mock(SearchBuilder.class); + SearchCriteria sc = Mockito.mock(SearchCriteria.class); + Mockito.when(sb.create()).thenReturn(sc); + Mockito.doAnswer((Answer) invocationOnMock -> { + Long batchSize = (Long)invocationOnMock.getArguments()[1]; + return batchSize == null ? 0 : batchSize.intValue(); + }).when(portForwardingRulesDaoImplSpy).batchExpunge(Mockito.any(SearchCriteria.class), Mockito.anyLong()); + Mockito.when(portForwardingRulesDaoImplSpy.createSearchBuilder()).thenReturn(sb); + final PortForwardingRuleVO mockedVO = Mockito.mock(PortForwardingRuleVO.class); + Mockito.when(sb.entity()).thenReturn(mockedVO); + List vmIds = List.of(1L, 2L); + Object[] array = vmIds.toArray(); + Long batchSize = 50L; + Assert.assertEquals(batchSize.intValue(), portForwardingRulesDaoImplSpy.expungeByVmList(List.of(1L, 2L), batchSize)); + Mockito.verify(sc).setParameters("vmIds", array); + Mockito.verify(portForwardingRulesDaoImplSpy, Mockito.times(1)) + .batchExpunge(sc, batchSize); + } +} diff --git a/engine/schema/src/test/java/com/cloud/offerings/dao/NetworkOfferingDaoImplTest.java b/engine/schema/src/test/java/com/cloud/offerings/dao/NetworkOfferingDaoImplTest.java index 6c894de7fb2..64941d99bb6 100644 --- a/engine/schema/src/test/java/com/cloud/offerings/dao/NetworkOfferingDaoImplTest.java +++ b/engine/schema/src/test/java/com/cloud/offerings/dao/NetworkOfferingDaoImplTest.java @@ -17,6 +17,7 @@ package com.cloud.offerings.dao; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -37,9 +38,16 @@ public class NetworkOfferingDaoImplTest { final long offeringId = 1L; + private AutoCloseable closeable; + @Before public void setup() { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); + } + + @After + public void tearDown() throws Exception { + closeable.close(); } @Test diff --git a/engine/schema/src/test/java/com/cloud/secstorage/CommandExecLogDaoImplTest.java b/engine/schema/src/test/java/com/cloud/secstorage/CommandExecLogDaoImplTest.java new file mode 100644 index 00000000000..f86df6bdd36 --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/secstorage/CommandExecLogDaoImplTest.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.secstorage; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; + +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@RunWith(MockitoJUnitRunner.class) +public class CommandExecLogDaoImplTest { + + @Spy + CommandExecLogDaoImpl commandExecLogDaoImplSpy; + + @Test + public void testExpungeByVmListNoVms() { + Assert.assertEquals(0, commandExecLogDaoImplSpy.expungeByVmList( + new ArrayList<>(), 100L)); + Assert.assertEquals(0, commandExecLogDaoImplSpy.expungeByVmList( + null, 100L)); + } + + @Test + public void testExpungeByVmList() { + SearchBuilder sb = Mockito.mock(SearchBuilder.class); + SearchCriteria sc = Mockito.mock(SearchCriteria.class); + Mockito.when(sb.create()).thenReturn(sc); + Mockito.doAnswer((Answer) invocationOnMock -> { + Long batchSize = (Long)invocationOnMock.getArguments()[1]; + return batchSize == null ? 0 : batchSize.intValue(); + }).when(commandExecLogDaoImplSpy).batchExpunge(Mockito.any(SearchCriteria.class), Mockito.anyLong()); + Mockito.when(commandExecLogDaoImplSpy.createSearchBuilder()).thenReturn(sb); + final CommandExecLogVO mockedVO = Mockito.mock(CommandExecLogVO.class); + Mockito.when(sb.entity()).thenReturn(mockedVO); + List vmIds = List.of(1L, 2L); + Object[] array = vmIds.toArray(); + Long batchSize = 50L; + Assert.assertEquals(batchSize.intValue(), commandExecLogDaoImplSpy.expungeByVmList(List.of(1L, 2L), batchSize)); + Mockito.verify(sc).setParameters("vmIds", array); + Mockito.verify(commandExecLogDaoImplSpy, Mockito.times(1)) + .batchExpunge(sc, batchSize); + } +} diff --git a/engine/schema/src/test/java/com/cloud/storage/dao/StoragePoolTagsDaoImplTest.java b/engine/schema/src/test/java/com/cloud/storage/dao/StoragePoolTagsDaoImplTest.java index 9277bf915c1..85fe0e09542 100755 --- a/engine/schema/src/test/java/com/cloud/storage/dao/StoragePoolTagsDaoImplTest.java +++ b/engine/schema/src/test/java/com/cloud/storage/dao/StoragePoolTagsDaoImplTest.java @@ -21,7 +21,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; @@ -72,7 +72,7 @@ public class StoragePoolTagsDaoImplTest extends TestCase { public void setup() { when(_configDao.getValue(batchSizeConfigurationKey)).thenReturn(batchSizeValue); doReturn(storagePoolTagList).when(_storagePoolTagsDaoImpl).searchIncludingRemoved( - Matchers.any(SearchCriteria.class), Matchers.isNull(Filter.class), Matchers.isNull(Boolean.class), Matchers.eq(false)); + ArgumentMatchers.any(SearchCriteria.class), ArgumentMatchers.isNull(Filter.class), ArgumentMatchers.isNull(Boolean.class), ArgumentMatchers.eq(false)); } @Test @@ -91,7 +91,7 @@ public class StoragePoolTagsDaoImplTest extends TestCase { List storagePoolTags = new ArrayList(); _storagePoolTagsDaoImpl.searchForStoragePoolIdsInternal(0, storageTagsIds.length, storageTagsIds, storagePoolTags); - verify(_storagePoolTagsDaoImpl).searchIncludingRemoved(Matchers.any(SearchCriteria.class), Matchers.isNull(Filter.class), Matchers.isNull(Boolean.class), Matchers.eq(false)); + verify(_storagePoolTagsDaoImpl).searchIncludingRemoved(ArgumentMatchers.any(SearchCriteria.class), ArgumentMatchers.isNull(Filter.class), ArgumentMatchers.isNull(Boolean.class), ArgumentMatchers.eq(false)); assertEquals(2, storagePoolTags.size()); } @@ -99,30 +99,30 @@ public class StoragePoolTagsDaoImplTest extends TestCase { public void testSearchForStoragePoolIdsInternalStorageTagsNullSearch() { List storagePoolTags = new ArrayList(); doReturn(null).when(_storagePoolTagsDaoImpl).searchIncludingRemoved( - Matchers.any(SearchCriteria.class), Matchers.isNull(Filter.class), Matchers.isNull(Boolean.class), Matchers.eq(false)); + ArgumentMatchers.any(SearchCriteria.class), ArgumentMatchers.isNull(Filter.class), ArgumentMatchers.isNull(Boolean.class), ArgumentMatchers.eq(false)); _storagePoolTagsDaoImpl.searchForStoragePoolIdsInternal(0, storageTagsIds.length, storageTagsIds, storagePoolTags); - verify(_storagePoolTagsDaoImpl).searchIncludingRemoved(Matchers.any(SearchCriteria.class), Matchers.isNull(Filter.class), Matchers.isNull(Boolean.class), Matchers.eq(false)); + verify(_storagePoolTagsDaoImpl).searchIncludingRemoved(ArgumentMatchers.any(SearchCriteria.class), ArgumentMatchers.isNull(Filter.class), ArgumentMatchers.isNull(Boolean.class), ArgumentMatchers.eq(false)); assertEquals(0, storagePoolTags.size()); } @Test public void testSearchByIdsStorageTagsIdsGreaterOrEqualThanBatchSize() { when(_configDao.getValue(batchSizeConfigurationKey)).thenReturn(batchSizeLow); - doNothing().when(_storagePoolTagsDaoImpl).searchForStoragePoolIdsInternal(Matchers.anyInt(), Matchers.anyInt(), Matchers.any(Long[].class), Matchers.anyList()); + doNothing().when(_storagePoolTagsDaoImpl).searchForStoragePoolIdsInternal(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(Long[].class), ArgumentMatchers.anyList()); _storagePoolTagsDaoImpl.searchByIds(storageTagsIds); int batchSize = Integer.parseInt(batchSizeLow); int difference = storageTagsIds.length - 2 * batchSize; - verify(_storagePoolTagsDaoImpl, Mockito.times(2)).searchForStoragePoolIdsInternal(Matchers.anyInt(), Matchers.eq(batchSize), Matchers.any(Long[].class), Matchers.anyList()); - verify(_storagePoolTagsDaoImpl).searchForStoragePoolIdsInternal(Matchers.eq(2 * batchSize), Matchers.eq(difference), Matchers.any(Long[].class), Matchers.anyList()); + verify(_storagePoolTagsDaoImpl, Mockito.times(2)).searchForStoragePoolIdsInternal(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(batchSize), ArgumentMatchers.any(Long[].class), ArgumentMatchers.anyList()); + verify(_storagePoolTagsDaoImpl).searchForStoragePoolIdsInternal(ArgumentMatchers.eq(2 * batchSize), ArgumentMatchers.eq(difference), ArgumentMatchers.any(Long[].class), ArgumentMatchers.anyList()); } @Test public void testSearchByIdsStorageTagsIdsLowerThanBatchSize() { - doNothing().when(_storagePoolTagsDaoImpl).searchForStoragePoolIdsInternal(Matchers.anyInt(), Matchers.anyInt(), Matchers.any(Long[].class), Matchers.anyList()); + doNothing().when(_storagePoolTagsDaoImpl).searchForStoragePoolIdsInternal(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(Long[].class), ArgumentMatchers.anyList()); _storagePoolTagsDaoImpl.searchByIds(storageTagsIds); - verify(_storagePoolTagsDaoImpl).searchForStoragePoolIdsInternal(Matchers.eq(0), Matchers.eq(storageTagsIds.length), Matchers.any(Long[].class), Matchers.anyList()); + verify(_storagePoolTagsDaoImpl).searchForStoragePoolIdsInternal(ArgumentMatchers.eq(0), ArgumentMatchers.eq(storageTagsIds.length), ArgumentMatchers.any(Long[].class), ArgumentMatchers.anyList()); } } diff --git a/engine/schema/src/test/java/com/cloud/storage/dao/VMTemplateDaoImplTest.java b/engine/schema/src/test/java/com/cloud/storage/dao/VMTemplateDaoImplTest.java new file mode 100644 index 00000000000..e97a887cc47 --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/storage/dao/VMTemplateDaoImplTest.java @@ -0,0 +1,210 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +package com.cloud.storage.dao; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.cpu.CPU; +import com.cloud.host.dao.HostDao; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.storage.Storage; +import com.cloud.storage.VMTemplateVO; +import com.cloud.utils.Pair; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@RunWith(MockitoJUnitRunner.class) +public class VMTemplateDaoImplTest { + + @Mock + HostDao hostDao; + + @Spy + @InjectMocks + VMTemplateDaoImpl templateDao = new VMTemplateDaoImpl(); + + @Test + public void testFindLatestTemplateByName_ReturnsTemplate() { + VMTemplateVO expectedTemplate = new VMTemplateVO(); + List returnedList = Collections.singletonList(expectedTemplate); + doReturn(returnedList).when(templateDao).listBy(any(SearchCriteria.class), any(Filter.class)); + VMTemplateVO result = templateDao.findLatestTemplateByName("test", CPU.CPUArch.getDefault()); + assertNotNull("Expected a non-null template", result); + assertEquals("Expected the returned template to be the first element", expectedTemplate, result); + } + + @Test + public void testFindLatestTemplateByName_ReturnsNullWhenNoTemplateFound() { + List emptyList = Collections.emptyList(); + doReturn(emptyList).when(templateDao).listBy(any(SearchCriteria.class), any(Filter.class)); + VMTemplateVO result = templateDao.findLatestTemplateByName("test", CPU.CPUArch.getDefault()); + assertNull("Expected null when no templates are found", result); + } + + @Test + public void testFindLatestTemplateByName_NullArch() { + VMTemplateVO expectedTemplate = new VMTemplateVO(); + List returnedList = Collections.singletonList(expectedTemplate); + doReturn(returnedList).when(templateDao).listBy(any(SearchCriteria.class), any(Filter.class)); + VMTemplateVO result = templateDao.findLatestTemplateByName("test", null); + assertNotNull("Expected a non-null template even if arch is null", result); + assertEquals("Expected the returned template to be the first element", expectedTemplate, result); + } + + @Test + public void testGetSortedTemplatesListWithPreferredArch_PreferredProvided() { + VMTemplateVO templatePreferred = Mockito.mock(VMTemplateVO.class); + when(templatePreferred.getArch()).thenReturn(CPU.CPUArch.amd64); + VMTemplateVO templateOther = Mockito.mock(VMTemplateVO.class); + when(templateOther.getArch()).thenReturn(CPU.CPUArch.arm64); + + Map, VMTemplateVO> uniqueTemplates = new HashMap<>(); + uniqueTemplates.put(new Pair<>(Hypervisor.HypervisorType.KVM, CPU.CPUArch.amd64), templatePreferred); + uniqueTemplates.put(new Pair<>(Hypervisor.HypervisorType.KVM, CPU.CPUArch.arm64), templateOther); + List sortedList = templateDao.getSortedTemplatesListWithPreferredArch(uniqueTemplates, + CPU.CPUArch.amd64.getType()); + assertEquals(2, sortedList.size()); + assertEquals(templatePreferred, sortedList.get(0)); + assertEquals(templateOther, sortedList.get(1)); + } + + @Test + public void testGetSortedTemplatesListWithPreferredArch_NoPreferred() { + VMTemplateVO template1 = Mockito.mock(VMTemplateVO.class); + when(template1.getId()).thenReturn(1L); + VMTemplateVO template2 = Mockito.mock(VMTemplateVO.class); + when(template2.getId()).thenReturn(2L); + Map, VMTemplateVO> uniqueTemplates = new HashMap<>(); + uniqueTemplates.put(new Pair<>(Hypervisor.HypervisorType.KVM, CPU.CPUArch.amd64), template1); + uniqueTemplates.put(new Pair<>(Hypervisor.HypervisorType.KVM, CPU.CPUArch.arm64), template2); + List sortedList = templateDao.getSortedTemplatesListWithPreferredArch(uniqueTemplates, ""); + assertEquals(2, sortedList.size()); + assertEquals(template2, sortedList.get(0)); + assertEquals(template1, sortedList.get(1)); + } + + @Test + public void testFindSystemVMReadyTemplates() { + long zoneId = 1L; + Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.KVM; + String preferredArch = CPU.CPUArch.arm64.getType(); + List> availableHypervisors = new ArrayList<>(); + availableHypervisors.add(new Pair<>(Hypervisor.HypervisorType.KVM, CPU.CPUArch.amd64)); + availableHypervisors.add(new Pair<>(Hypervisor.HypervisorType.KVM, CPU.CPUArch.arm64)); + doReturn(availableHypervisors).when(hostDao).listDistinctHypervisorArchTypes(zoneId); + VMTemplateVO template1 = Mockito.mock(VMTemplateVO.class); + when(template1.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + when(template1.getArch()).thenReturn(CPU.CPUArch.amd64); + VMTemplateVO template2 = Mockito.mock(VMTemplateVO.class); + when(template2.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + when(template2.getArch()).thenReturn(CPU.CPUArch.arm64); + List templatesFromDb = Arrays.asList(template1, template2); + doReturn(templatesFromDb).when(templateDao).listBy(any(), any()); + SearchBuilder sb = mock(SearchBuilder.class); + templateDao.readySystemTemplateSearch = sb; + when(sb.create()).thenReturn(mock(SearchCriteria.class)); + List result = templateDao.findSystemVMReadyTemplates(zoneId, hypervisorType, preferredArch); + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals(template2, result.get(0)); + assertEquals(template1, result.get(1)); + } + + @Test + public void testFindRoutingTemplates() { + Hypervisor.HypervisorType hType = Hypervisor.HypervisorType.KVM; + String templateName = "TestRouting"; + String preferredArch = CPU.CPUArch.amd64.getType(); + VMTemplateVO template = Mockito.mock(VMTemplateVO.class); + when(template.getArch()).thenReturn(CPU.CPUArch.amd64); + List templatesFromDb = Collections.singletonList(template); + doReturn(templatesFromDb).when(templateDao).listBy(any(), any()); + SearchBuilder sb = mock(SearchBuilder.class); + when(sb.create()).thenReturn(mock(SearchCriteria.class)); + templateDao.tmpltTypeHyperSearch2 = sb; + List result = templateDao.findRoutingTemplates(hType, templateName, preferredArch); + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(template, result.get(0)); + } + + @Test + public void testFindLatestTemplateByTypeAndHypervisorAndArch_Found() { + Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.KVM; + CPU.CPUArch arch = CPU.CPUArch.amd64; + Storage.TemplateType type = Storage.TemplateType.SYSTEM; + VMTemplateVO template = Mockito.mock(VMTemplateVO.class); + List templatesFromDb = Collections.singletonList(template); + doReturn(templatesFromDb).when(templateDao).listBy(any(), any()); + VMTemplateVO result = templateDao.findLatestTemplateByTypeAndHypervisorAndArch(hypervisorType, arch, type); + assertNotNull(result); + assertEquals(template, result); + } + + @Test + public void testFindLatestTemplateByTypeAndHypervisorAndArch_NotFound() { + Hypervisor.HypervisorType hypervisorType = Hypervisor.HypervisorType.KVM; + CPU.CPUArch arch = CPU.CPUArch.x86; + Storage.TemplateType type = Storage.TemplateType.SYSTEM; + doReturn(Collections.emptyList()).when(templateDao).listBy(any(), any()); + VMTemplateVO result = templateDao.findLatestTemplateByTypeAndHypervisorAndArch(hypervisorType, arch, type); + assertNull(result); + } + + @Test + public void testFindSystemVMReadyTemplate() { + Long zoneId = 1L; + VMTemplateVO systemVmTemplate1 = mock(VMTemplateVO.class); + Mockito.when(systemVmTemplate1.getArch()).thenReturn(CPU.CPUArch.x86); + VMTemplateVO systemVmTemplate2 = mock(VMTemplateVO.class); + Mockito.when(systemVmTemplate2.getArch()).thenReturn(CPU.CPUArch.x86); + VMTemplateVO systemVmTemplate3 = mock(VMTemplateVO.class); + Mockito.when(systemVmTemplate3.getArch()).thenReturn(CPU.CPUArch.arm64); + Mockito.when(systemVmTemplate3.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + List templates = Arrays.asList(systemVmTemplate1, systemVmTemplate2, systemVmTemplate3); + Mockito.when(hostDao.listDistinctHypervisorTypes(zoneId)).thenReturn(Arrays.asList(Hypervisor.HypervisorType.KVM)); + SearchBuilder sb = mock(SearchBuilder.class); + templateDao.readySystemTemplateSearch = sb; + when(sb.create()).thenReturn(mock(SearchCriteria.class)); + doReturn(templates).when(templateDao).listBy(any(SearchCriteria.class), any(Filter.class)); + VMTemplateVO readyTemplate = templateDao.findSystemVMReadyTemplate(zoneId, Hypervisor.HypervisorType.KVM, CPU.CPUArch.arm64.getType()); + Assert.assertEquals(CPU.CPUArch.arm64, readyTemplate.getArch()); + } +} diff --git a/engine/schema/src/test/java/com/cloud/storage/dao/VolumeDaoImplTest.java b/engine/schema/src/test/java/com/cloud/storage/dao/VolumeDaoImplTest.java index 7968ee4a375..9445efeb089 100644 --- a/engine/schema/src/test/java/com/cloud/storage/dao/VolumeDaoImplTest.java +++ b/engine/schema/src/test/java/com/cloud/storage/dao/VolumeDaoImplTest.java @@ -26,16 +26,25 @@ import static org.mockito.Mockito.when; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.collections.CollectionUtils; import org.junit.AfterClass; +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import com.cloud.storage.VolumeVO; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.TransactionLegacy; @RunWith(MockitoJUnitRunner.class) @@ -48,6 +57,7 @@ public class VolumeDaoImplTest { private static MockedStatic mockedTransactionLegacy; + @Spy private final VolumeDaoImpl volumeDao = new VolumeDaoImpl(); @BeforeClass @@ -102,4 +112,34 @@ public class VolumeDaoImplTest { verify(preparedStatementMock, times(2)).setLong(anyInt(), anyLong()); verify(preparedStatementMock, times(1)).executeQuery(); } + + @Test + public void testSearchRemovedByVmsNoVms() { + Assert.assertTrue(CollectionUtils.isEmpty(volumeDao.searchRemovedByVms( + new ArrayList<>(), 100L))); + Assert.assertTrue(CollectionUtils.isEmpty(volumeDao.searchRemovedByVms( + null, 100L))); + } + + @Test + public void testSearchRemovedByVms() { + SearchBuilder sb = Mockito.mock(SearchBuilder.class); + SearchCriteria sc = Mockito.mock(SearchCriteria.class); + Mockito.when(sb.create()).thenReturn(sc); + Mockito.doReturn(new ArrayList<>()).when(volumeDao).searchIncludingRemoved( + Mockito.any(SearchCriteria.class), Mockito.any(Filter.class), Mockito.eq(null), + Mockito.eq(false)); + Mockito.when(volumeDao.createSearchBuilder()).thenReturn(sb); + final VolumeVO mockedVO = Mockito.mock(VolumeVO.class); + Mockito.when(sb.entity()).thenReturn(mockedVO); + List vmIds = List.of(1L, 2L); + Object[] array = vmIds.toArray(); + Long batchSize = 50L; + volumeDao.searchRemovedByVms(List.of(1L, 2L), batchSize); + Mockito.verify(sc).setParameters("vmIds", array); + Mockito.verify(volumeDao, Mockito.times(1)).searchIncludingRemoved( + Mockito.any(SearchCriteria.class), Mockito.any(Filter.class), Mockito.eq(null), + Mockito.eq(false)); + } + } diff --git a/engine/schema/src/test/java/com/cloud/upgrade/SystemVmTemplateRegistrationTest.java b/engine/schema/src/test/java/com/cloud/upgrade/SystemVmTemplateRegistrationTest.java new file mode 100644 index 00000000000..6573a5565f3 --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/upgrade/SystemVmTemplateRegistrationTest.java @@ -0,0 +1,427 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package com.cloud.upgrade; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; +import org.apache.cloudstack.utils.security.DigestHelper; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.cpu.CPU; +import com.cloud.dc.dao.ClusterDao; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.utils.HttpUtils; +import com.cloud.utils.Pair; +import com.cloud.utils.UriUtils; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.script.Script; + +@RunWith(MockitoJUnitRunner.class) +public class SystemVmTemplateRegistrationTest { + + @Mock + ClusterDao clusterDao; + + @Mock + VMTemplateDao vmTemplateDao; + + @Spy + @InjectMocks + SystemVmTemplateRegistration systemVmTemplateRegistration = new SystemVmTemplateRegistration(); + + private void setupMetadataFile(MockedStatic mockedStatic, String content) { + try { + String location = "metadata.ini"; + if (StringUtils.isNotBlank(content)) { + File tempFile = File.createTempFile("metadata", ".ini"); + location = tempFile.getAbsolutePath(); + Files.write(Paths.get(location), content.getBytes()); + tempFile.deleteOnExit(); + } + mockedStatic.when(SystemVmTemplateRegistration::getMetadataFilePath).thenReturn(location); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void test_parseMetadataFile_noFile() { + try (MockedStatic mockedStatic = + Mockito.mockStatic(SystemVmTemplateRegistration.class, Mockito.CALLS_REAL_METHODS)) { + setupMetadataFile(mockedStatic, null); + CloudRuntimeException exception = assertThrows(CloudRuntimeException.class, + SystemVmTemplateRegistration::parseMetadataFile); + assertTrue(exception.getMessage().contains("Failed to parse systemVM template metadata file")); + } + } + + @Test + public void test_parseMetadataFile_invalidContent() { + try (MockedStatic mockedStatic = + Mockito.mockStatic(SystemVmTemplateRegistration.class, Mockito.CALLS_REAL_METHODS)) { + setupMetadataFile(mockedStatic, "abc"); + CloudRuntimeException exception = assertThrows(CloudRuntimeException.class, + SystemVmTemplateRegistration::parseMetadataFile); + assertTrue(exception.getMessage().contains("Failed to parse systemVM template metadata file")); + } + } + + @Test + public void test_parseMetadataFile_success() { + String metadataFileContent = "[default]\n" + + "version = x.y.z.0\n" + + "\n" + + "[kvm-x86_64]\n" + + "templatename = systemvm-kvm-x.y.z\n" + + "checksum = abc1\n" + + "downloadurl = https://download.cloudstack.org/systemvm/x.y/systemvmtemplate-x.y.z-kvm.qcow2.bz2\n" + + "filename = systemvmtemplate-x.y.z-kvm.qcow2.bz2\n" + + "\n" + + "[kvm-aarch64]\n" + + "templatename = systemvm-kvm-x.y.z\n" + + "checksum = abc2\n" + + "downloadurl = https://download.cloudstack.org/systemvm/x.y/systemvmtemplate-x.y.z-kvm.qcow2.bz2\n" + + "filename = systemvmtemplate-x.y.z-kvm.qcow2.bz2\n" + + "\n" + + "[vmware]\n" + + "templatename = systemvm-vmware-x.y.z\n" + + "checksum = abc3\n" + + "downloadurl = https://download.cloudstack.org/systemvm/x.y/systemvmtemplate-x.y.z-vmware.ova\n" + + "filename = systemvmtemplate-x.y.z-vmware.ova\n"; + try (MockedStatic mockedStatic = + Mockito.mockStatic(SystemVmTemplateRegistration.class, Mockito.CALLS_REAL_METHODS)) { + setupMetadataFile(mockedStatic, metadataFileContent); + String version = SystemVmTemplateRegistration.parseMetadataFile(); + assertEquals("x.y.z.0", version); + } + assertNull(SystemVmTemplateRegistration.NewTemplateMap.get("xenserver")); + SystemVmTemplateRegistration.MetadataTemplateDetails templateDetails = + SystemVmTemplateRegistration.NewTemplateMap.get("kvm-x86_64"); + assertNotNull(templateDetails); + assertEquals(CPU.CPUArch.amd64, templateDetails.getArch()); + assertEquals(Hypervisor.HypervisorType.KVM, templateDetails.getHypervisorType()); + templateDetails = + SystemVmTemplateRegistration.NewTemplateMap.get("kvm-aarch64"); + assertNotNull(templateDetails); + assertEquals(CPU.CPUArch.arm64, templateDetails.getArch()); + assertEquals(Hypervisor.HypervisorType.KVM, templateDetails.getHypervisorType()); + templateDetails = + SystemVmTemplateRegistration.NewTemplateMap.get("vmware"); + assertNotNull(templateDetails); + assertNull(templateDetails.getArch()); + assertEquals(Hypervisor.HypervisorType.VMware, templateDetails.getHypervisorType()); + } + + @Test + public void testMountStore_nullStoreUrl() throws Exception { + try (MockedStatic + diff --git a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolBackupSnapshotCommandWrapper.java b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolBackupSnapshotCommandWrapper.java index 58264161bd6..00746334e02 100644 --- a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolBackupSnapshotCommandWrapper.java +++ b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolBackupSnapshotCommandWrapper.java @@ -39,7 +39,6 @@ import org.apache.cloudstack.utils.qemu.QemuImgFile; import org.apache.cloudstack.utils.qemu.QemuObject; import org.apache.cloudstack.utils.qemu.QemuObject.EncryptFormat; import org.apache.commons.io.FileUtils; -import org.apache.log4j.Logger; import com.cloud.agent.api.storage.StorPoolBackupSnapshotCommand; import com.cloud.agent.api.to.DataStoreTO; @@ -54,7 +53,6 @@ import com.cloud.resource.ResourceWrapper; @ResourceWrapper(handles = StorPoolBackupSnapshotCommand.class) public final class StorPoolBackupSnapshotCommandWrapper extends CommandWrapper { - private static final Logger s_logger = Logger.getLogger(StorPoolBackupSnapshotCommandWrapper.class); @Override public CopyCmdAnswer execute(final StorPoolBackupSnapshotCommand cmd, final LibvirtComputingResource libvirtComputingResource) { @@ -94,9 +92,10 @@ public final class StorPoolBackupSnapshotCommandWrapper extends CommandWrapper { - private static final Logger s_logger = Logger.getLogger(StorPoolBackupTemplateFromSnapshotCommandWrapper.class); @Override public CopyCmdAnswer execute(final StorPoolBackupTemplateFromSnapshotCommand cmd, final LibvirtComputingResource libvirtComputingResource) { @@ -142,7 +140,7 @@ public class StorPoolBackupTemplateFromSnapshotCommandWrapper extends CommandWra } catch (final Exception e) { final String error = "failed to backup snapshot: " + e.getMessage(); SP_LOG(error); - s_logger.debug(error); + logger.debug(error); return new CopyCmdAnswer(cmd, e); } finally { if (srcPath != null) { @@ -153,7 +151,7 @@ public class StorPoolBackupTemplateFromSnapshotCommandWrapper extends CommandWra try { secondaryPool.delete(); } catch (final Exception e) { - s_logger.debug("Failed to delete secondary storage", e); + logger.debug("Failed to delete secondary storage", e); } } } diff --git a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolCopyVolumeToSecondaryCommandWrapper.java b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolCopyVolumeToSecondaryCommandWrapper.java index bd50f43025f..113fb11ea54 100644 --- a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolCopyVolumeToSecondaryCommandWrapper.java +++ b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolCopyVolumeToSecondaryCommandWrapper.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.utils.qemu.QemuImg; import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; import org.apache.cloudstack.utils.qemu.QemuImgFile; -import org.apache.log4j.Logger; import com.cloud.agent.api.storage.StorPoolCopyVolumeToSecondaryCommand; import com.cloud.agent.api.to.DataStoreTO; @@ -45,7 +44,6 @@ import com.cloud.resource.ResourceWrapper; @ResourceWrapper(handles = StorPoolCopyVolumeToSecondaryCommand.class) public final class StorPoolCopyVolumeToSecondaryCommandWrapper extends CommandWrapper { - private static final Logger s_logger = Logger.getLogger(StorPoolCopyVolumeToSecondaryCommandWrapper.class); @Override public CopyCmdAnswer execute(final StorPoolCopyVolumeToSecondaryCommand cmd, final LibvirtComputingResource libvirtComputingResource) { @@ -104,7 +102,7 @@ public final class StorPoolCopyVolumeToSecondaryCommandWrapper extends CommandWr return new CopyCmdAnswer(dst); } catch (final Exception e) { final String error = "Failed to copy volume to secondary storage: " + e.getMessage(); - s_logger.debug(error); + logger.debug(error); return new CopyCmdAnswer(error); } finally { if (srcPath != null) { @@ -116,7 +114,7 @@ public final class StorPoolCopyVolumeToSecondaryCommandWrapper extends CommandWr SP_LOG("StorpoolCopyVolumeToSecondaryCommandWrapper.execute: secondaryPool=%s " , secondaryPool); secondaryPool.delete(); } catch (final Exception e) { - s_logger.debug("Failed to delete secondary storage", e); + logger.debug("Failed to delete secondary storage", e); } } } diff --git a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolDownloadTemplateCommandWrapper.java b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolDownloadTemplateCommandWrapper.java index 87a46ba62c9..3e7118ab81d 100644 --- a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolDownloadTemplateCommandWrapper.java +++ b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolDownloadTemplateCommandWrapper.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.utils.qemu.QemuImg; import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; import org.apache.cloudstack.utils.qemu.QemuImgFile; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import com.cloud.agent.api.storage.StorPoolDownloadTemplateCommand; import com.cloud.agent.api.to.DataStoreTO; @@ -47,7 +46,6 @@ import com.cloud.resource.ResourceWrapper; @ResourceWrapper(handles = StorPoolDownloadTemplateCommand.class) public final class StorPoolDownloadTemplateCommandWrapper extends CommandWrapper { - private static final Logger s_logger = Logger.getLogger(StorPoolDownloadTemplateCommandWrapper.class); @Override public CopyCmdAnswer execute(final StorPoolDownloadTemplateCommand cmd, final LibvirtComputingResource libvirtComputingResource) { @@ -120,7 +118,7 @@ public final class StorPoolDownloadTemplateCommandWrapper extends CommandWrapper return new CopyCmdAnswer(dst); } catch (final Exception e) { final String error = "Failed to copy template to primary: " + e.getMessage(); - s_logger.debug(error); + logger.debug(error); return new CopyCmdAnswer(cmd, e); } finally { if (dstPath != null) { @@ -131,7 +129,7 @@ public final class StorPoolDownloadTemplateCommandWrapper extends CommandWrapper try { secondaryPool.delete(); } catch (final Exception e) { - s_logger.debug("Failed to delete secondary storage", e); + logger.debug("Failed to delete secondary storage", e); } } } diff --git a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolDownloadVolumeCommandWrapper.java b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolDownloadVolumeCommandWrapper.java index d1a58a4aeb8..37284b597d2 100644 --- a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolDownloadVolumeCommandWrapper.java +++ b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/StorPoolDownloadVolumeCommandWrapper.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.utils.qemu.QemuImg; import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; import org.apache.cloudstack.utils.qemu.QemuImgFile; //import java.io.File; -import org.apache.log4j.Logger; import com.cloud.agent.api.storage.StorPoolDownloadVolumeCommand; import com.cloud.agent.api.to.DataStoreTO; @@ -48,7 +47,6 @@ import com.cloud.storage.Storage.StoragePoolType; @ResourceWrapper(handles = StorPoolDownloadVolumeCommand.class) public final class StorPoolDownloadVolumeCommandWrapper extends CommandWrapper { - private static final Logger s_logger = Logger.getLogger(StorPoolDownloadVolumeCommandWrapper.class); @Override public CopyCmdAnswer execute(final StorPoolDownloadVolumeCommand cmd, final LibvirtComputingResource libvirtComputingResource) { @@ -143,7 +141,7 @@ public final class StorPoolDownloadVolumeCommandWrapper extends CommandWrapper { - private static final Logger log = Logger.getLogger(StorPoolModifyStorageCommandWrapper.class); @Override public Answer execute(final StorPoolModifyStoragePoolCommand command, final LibvirtComputingResource libvirtComputingResource) { String clusterId = StorPoolStoragePool.getStorPoolConfigParam("SP_CLUSTER_ID"); if (clusterId == null) { - log.debug(String.format("Could not get StorPool cluster id for a command [%s]", command.getClass())); + logger.debug(String.format("Could not get StorPool cluster id for a command [%s]", command.getClass())); return new Answer(command, false, "spNotFound"); } try { @@ -63,14 +61,14 @@ public final class StorPoolModifyStorageCommandWrapper extends CommandWrapper tInfo = new HashMap<>(); return new StorPoolModifyStoragePoolAnswer(command, storagepool.getCapacity(), storagepool.getAvailable(), tInfo, clusterId, storagepool.getStorageNodeId()); } catch (Exception e) { - log.debug(String.format("Could not modify storage due to %s", e.getMessage())); + logger.debug(String.format("Could not modify storage due to %s", e.getMessage())); return new Answer(command, e); } } @@ -82,7 +80,7 @@ public final class StorPoolModifyStorageCommandWrapper extends CommandWrapper { - private static final Logger s_logger = Logger.getLogger(StorPoolResizeVolumeCommandWrapper.class); @Override public ResizeVolumeAnswer execute(final StorPoolResizeVolumeCommand command, final LibvirtComputingResource libvirtComputingResource) { @@ -51,7 +49,7 @@ public final class StorPoolResizeVolumeCommandWrapper extends CommandWrapper { - private static final Logger logger = Logger.getLogger(StorPoolSetVolumeEncryptionCommandWrapper.class); @Override public StorPoolSetVolumeEncryptionAnswer execute(StorPoolSetVolumeEncryptionCommand command, diff --git a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/storage/StorPoolStorageAdaptor.java b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/storage/StorPoolStorageAdaptor.java index 4091be10470..897b293f30d 100644 --- a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/storage/StorPoolStorageAdaptor.java +++ b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/storage/StorPoolStorageAdaptor.java @@ -28,7 +28,8 @@ import java.util.List; import java.util.Map; import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.agent.api.to.DiskTO; import com.cloud.storage.Storage; @@ -39,7 +40,6 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; -@StorageAdaptorInfo(storagePoolType=StoragePoolType.StorPool) public class StorPoolStorageAdaptor implements StorageAdaptor { public static void SP_LOG(String fmt, Object... args) { try (PrintWriter spLogFile = new PrintWriter(new BufferedWriter(new FileWriter("/var/log/cloudstack/agent/storpool-agent.log", true)))) { @@ -52,7 +52,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { } } - private static final Logger log = Logger.getLogger(StorPoolStorageAdaptor.class); + protected static Logger LOGGER = LogManager.getLogger(StorPoolStorageAdaptor.class); private static final Map storageUuidToStoragePool = new HashMap(); @@ -65,6 +65,11 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { return storagePool; } + @Override + public StoragePoolType getStoragePoolType() { + return StoragePoolType.StorPool; + } + @Override public KVMStoragePool getStoragePool(String uuid) { SP_LOG("StorPoolStorageAdaptor.getStoragePool: uuid=%s", uuid); @@ -99,7 +104,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { if (!file.exists()) { return 0; } - Script sc = new Script("blockdev", 0, log); + Script sc = new Script("blockdev", 0, LOGGER); sc.add("--getsize64", devPath); OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); @@ -108,7 +113,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { if (res != null) { SP_LOG("Unable to retrieve device size for %s. Res: %s", devPath, res); - log.debug(String.format("Unable to retrieve device size for %s. Res: %s", devPath, res)); + LOGGER.debug(String.format("Unable to retrieve device size for %s. Res: %s", devPath, res)); return 0; } @@ -134,6 +139,9 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { } public static String getVolumeNameFromPath(final String volumeUuid, boolean tildeNeeded) { + if (volumeUuid == null) { + return null; + } if (volumeUuid.startsWith("/dev/storpool/")) { return volumeUuid.split("/")[3]; } else if (volumeUuid.startsWith("/dev/storpool-byid/")) { @@ -156,7 +164,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { String err = null; for(int i = 0; i < numTries; i++) { - Script sc = new Script("storpool", 0, log); + Script sc = new Script("storpool", 0, LOGGER); sc.add("-M"); sc.add(command); sc.add(type, name); @@ -188,7 +196,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { if (err != null) { SP_LOG(err); - log.warn(err); + LOGGER.warn(err); throw new CloudRuntimeException(err); } @@ -207,7 +215,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { SP_LOG("StorPoolStorageAdaptor.resize: size=%s, uuid=%s, name=%s", newSize, volumeUuid, name); - Script sc = new Script("storpool", 0, log); + Script sc = new Script("storpool", 0, LOGGER); sc.add("-M"); sc.add("volume"); sc.add(name); @@ -224,7 +232,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { String err = String.format("Unable to resize volume %s. Error: %s", name, res); SP_LOG(err); - log.warn(err); + LOGGER.warn(err); throw new CloudRuntimeException(err); } @@ -232,7 +240,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { public KVMPhysicalDisk getPhysicalDisk(String volumeUuid, KVMStoragePool pool) { SP_LOG("StorPoolStorageAdaptor.getPhysicalDisk: uuid=%s, pool=%s", volumeUuid, pool); - log.debug(String.format("getPhysicalDisk: uuid=%s, pool=%s", volumeUuid, pool)); + LOGGER.debug(String.format("getPhysicalDisk: uuid=%s, pool=%s", volumeUuid, pool)); final long deviceSize = getDeviceSize(volumeUuid); @@ -247,7 +255,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { public boolean connectPhysicalDisk(String volumeUuid, KVMStoragePool pool, Map details, boolean isVMMigrate) { SP_LOG("StorPoolStorageAdaptor.connectPhysicalDisk: uuid=%s, pool=%s", volumeUuid, pool); - log.debug(String.format("connectPhysicalDisk: uuid=%s, pool=%s", volumeUuid, pool)); + LOGGER.debug(String.format("connectPhysicalDisk: uuid=%s, pool=%s", volumeUuid, pool)); return attachOrDetachVolume("attach", "volume", volumeUuid); } @@ -256,19 +264,19 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { public boolean disconnectPhysicalDisk(String volumeUuid, KVMStoragePool pool) { SP_LOG("StorPoolStorageAdaptor.disconnectPhysicalDisk: uuid=%s, pool=%s", volumeUuid, pool); - log.debug(String.format("disconnectPhysicalDisk: uuid=%s, pool=%s", volumeUuid, pool)); + LOGGER.debug(String.format("disconnectPhysicalDisk: uuid=%s, pool=%s", volumeUuid, pool)); return attachOrDetachVolume("detach", "volume", volumeUuid); } public boolean disconnectPhysicalDisk(Map volumeToDisconnect) { String volumeUuid = volumeToDisconnect.get(DiskTO.UUID); - log.debug(String.format("StorPoolStorageAdaptor.disconnectPhysicalDisk: map. uuid=%s", volumeUuid)); + LOGGER.debug(String.format("StorPoolStorageAdaptor.disconnectPhysicalDisk: map. uuid=%s", volumeUuid)); return attachOrDetachVolume("detach", "volume", volumeUuid); } @Override public boolean disconnectPhysicalDiskByPath(String localPath) { - log.debug(String.format("disconnectPhysicalDiskByPath: localPath=%s", localPath)); + LOGGER.debug(String.format("disconnectPhysicalDiskByPath: localPath=%s", localPath)); return attachOrDetachVolume("detach", "volume", localPath); } @@ -283,7 +291,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { throw new UnsupportedOperationException(err); } - Script sc = new Script("storpool", 0, log); + Script sc = new Script("storpool", 0, LOGGER); sc.add("-M"); sc.add("snapshot", name); sc.add("delete", name); @@ -294,7 +302,7 @@ public class StorPoolStorageAdaptor implements StorageAdaptor { if (res != null) { final String err = String.format("Unable to delete StorPool snapshot '%s'. Error: %s", name, res); SP_LOG(err); - log.warn(err); + LOGGER.warn(err); throw new UnsupportedOperationException(err); } return true; // apparently ignored diff --git a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/storage/StorPoolStoragePool.java b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/storage/StorPoolStoragePool.java index 953b55b6e9a..ac7138420c0 100644 --- a/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/storage/StorPoolStoragePool.java +++ b/plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/storage/StorPoolStoragePool.java @@ -21,7 +21,8 @@ import java.util.Map; import java.util.Map.Entry; import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.joda.time.Duration; import com.cloud.agent.api.to.HostTO; @@ -39,7 +40,7 @@ import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; public class StorPoolStoragePool implements KVMStoragePool { - private static final Logger log = Logger.getLogger(StorPoolStoragePool.class); + protected Logger logger = LogManager.getLogger(StorPoolStoragePool.class); private String _uuid; private String _sourceHost; private int _sourcePort; @@ -199,8 +200,8 @@ public class StorPoolStoragePool implements KVMStoragePool { boolean isStorageNodeUp = checkingHeartBeat(primaryStoragePool, null); if (!isStorageNodeUp && !hostValidation) { //restart the host - log.debug(String.format("The host [%s] will be restarted because the health check failed for the storage pool [%s]", hostPrivateIp, primaryStoragePool.getPool().getType())); - Script cmd = new Script(primaryStoragePool.getPool().getHearthBeatPath(), HeartBeatUpdateTimeout, log); + logger.debug(String.format("The host [%s] will be restarted because the health check failed for the storage pool [%s]", hostPrivateIp, primaryStoragePool.getPool().getType())); + Script cmd = new Script(primaryStoragePool.getPool().getHearthBeatPath(), HeartBeatUpdateTimeout, logger); cmd.add("-c"); cmd.execute(); return "Down"; @@ -214,7 +215,7 @@ public class StorPoolStoragePool implements KVMStoragePool { } public static final String getStorPoolConfigParam(String param) { - Script sc = new Script("storpool_confget", 0, Logger.getLogger(StorPoolStoragePool.class)); + Script sc = new Script("storpool_confget", 0, LogManager.getLogger(StorPoolStoragePool.class)); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String configParam = null; @@ -289,7 +290,7 @@ public class StorPoolStoragePool implements KVMStoragePool { } private String executeStorPoolServiceListCmd(OutputInterpreter.AllLinesParser parser) { - Script sc = new Script("storpool", 0, log); + Script sc = new Script("storpool", 0, logger); sc.add("-j"); sc.add("service"); sc.add("list"); diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/collector/StorPoolAbandonObjectsCollector.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/collector/StorPoolAbandonObjectsCollector.java index f4821e26926..6258767921d 100644 --- a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/collector/StorPoolAbandonObjectsCollector.java +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/collector/StorPoolAbandonObjectsCollector.java @@ -37,10 +37,9 @@ import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.StorPoolHelper; +//import org.apache.cloudstack.storage.datastore.util.StorPoolHelper; import org.apache.cloudstack.storage.datastore.util.StorPoolUtil; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.concurrency.NamedThreadFactory; @@ -53,14 +52,13 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class StorPoolAbandonObjectsCollector extends ManagerBase implements Configurable { - private static Logger log = Logger.getLogger(StorPoolAbandonObjectsCollector.class); @Inject private PrimaryDataStoreDao storagePoolDao; @Inject private StoragePoolDetailsDao storagePoolDetailsDao; private ScheduledExecutorService _volumeTagsUpdateExecutor; - private static final String ABANDON_LOG = "/var/log/cloudstack/management/storpool-abandoned-objects"; + private static final String ABANDON_LOGGER = "/var/log/cloudstack/management/storpool-abandoned-objects"; static final ConfigKey volumeCheckupTagsInterval = new ConfigKey("Advanced", Integer.class, @@ -91,7 +89,7 @@ public class StorPoolAbandonObjectsCollector extends ManagerBase implements Conf private void init() { List spPools = storagePoolDao.findPoolsByProvider(StorPoolUtil.SP_PROVIDER_NAME); if (CollectionUtils.isNotEmpty(spPools)) { - StorPoolHelper.appendLogger(log, ABANDON_LOG, "abandon"); +// StorPoolHelper.appendLogger(logger, ABANDON_LOGGER, "abandon"); } _volumeTagsUpdateExecutor = Executors.newScheduledThreadPool(2, new NamedThreadFactory("StorPoolAbandonObjectsCollector")); @@ -121,7 +119,7 @@ public class StorPoolAbandonObjectsCollector extends ManagerBase implements Conf JsonArray arr = StorPoolUtil.volumesList(StorPoolUtil.getSpConnection(storagePoolVO.getUuid(), storagePoolVO.getId(), storagePoolDetailsDao, storagePoolDao)); volumes.putAll(getStorPoolNamesAndCsTag(arr)); } catch (Exception e) { - log.debug(String.format("Could not collect abandon objects due to %s", e.getMessage()), e); + logger.debug(String.format("Could not collect abandon objects due to %s", e.getMessage()), e); } } Transaction.execute(new TransactionCallbackNoReturn() { @@ -139,10 +137,10 @@ public class StorPoolAbandonObjectsCollector extends ManagerBase implements Conf pstmt.executeUpdate(); } catch (SQLException e) { - log.info(String.format("[ignored] SQL failed to delete vm work job: %s ", + logger.info(String.format("[ignored] SQL failed to delete vm work job: %s ", e.getLocalizedMessage())); } catch (Throwable e) { - log.info(String.format("[ignored] caught an error during delete vm work job: %s", + logger.info(String.format("[ignored] caught an error during delete vm work job: %s", e.getLocalizedMessage())); } @@ -164,10 +162,10 @@ public class StorPoolAbandonObjectsCollector extends ManagerBase implements Conf String sqlVolumeOnHost = "SELECT f.* FROM `cloud`.`volumes_on_host1` f LEFT JOIN `cloud`.`storage_pool_details` v ON f.name=v.value where v.value is NULL"; findMissingRecordsInCS(txn, sqlVolumeOnHost, "volumes_on_host"); } catch (SQLException e) { - log.info(String.format("[ignored] SQL failed due to: %s ", + logger.info(String.format("[ignored] SQL failed due to: %s ", e.getLocalizedMessage())); } catch (Throwable e) { - log.info(String.format("[ignored] caught an error: %s", + logger.info(String.format("[ignored] caught an error: %s", e.getLocalizedMessage())); } finally { try { @@ -177,7 +175,7 @@ public class StorPoolAbandonObjectsCollector extends ManagerBase implements Conf pstmt.executeUpdate(); } catch (SQLException e) { txn.close(); - log.info(String.format("createTemporaryVolumeTable %s", e.getMessage())); + logger.info(String.format("createTemporaryVolumeTable %s", e.getMessage())); } txn.close(); } @@ -201,7 +199,7 @@ public class StorPoolAbandonObjectsCollector extends ManagerBase implements Conf JsonArray arr = StorPoolUtil.snapshotsList(StorPoolUtil.getSpConnection(storagePoolVO.getUuid(), storagePoolVO.getId(), storagePoolDetailsDao, storagePoolDao)); snapshots.putAll(getStorPoolNamesAndCsTag(arr)); } catch (Exception e) { - log.debug(String.format("Could not collect abandon objects due to %s", e.getMessage())); + logger.debug(String.format("Could not collect abandon objects due to %s", e.getMessage())); } } Transaction.execute(new TransactionCallbackNoReturn() { @@ -222,10 +220,10 @@ public class StorPoolAbandonObjectsCollector extends ManagerBase implements Conf "CREATE TEMPORARY TABLE `cloud`.`vm_templates1`(`id` bigint unsigned NOT NULL auto_increment, `name` varchar(255) NOT NULL,`tag` varchar(255) NOT NULL, PRIMARY KEY (`id`))"); pstmt.executeUpdate(); } catch (SQLException e) { - log.info(String.format("[ignored] SQL failed to delete vm work job: %s ", + logger.info(String.format("[ignored] SQL failed to delete vm work job: %s ", e.getLocalizedMessage())); } catch (Throwable e) { - log.info(String.format("[ignored] caught an error during delete vm work job: %s", + logger.info(String.format("[ignored] caught an error during delete vm work job: %s", e.getLocalizedMessage())); } @@ -262,10 +260,10 @@ public class StorPoolAbandonObjectsCollector extends ManagerBase implements Conf + " and spool.local_path is NULL"; findMissingRecordsInCS(txn, sqlTemplates, "snapshot"); } catch (SQLException e) { - log.info(String.format("[ignored] SQL failed due to: %s ", + logger.info(String.format("[ignored] SQL failed due to: %s ", e.getLocalizedMessage())); } catch (Throwable e) { - log.info(String.format("[ignored] caught an error: %s", + logger.info(String.format("[ignored] caught an error: %s", e.getLocalizedMessage())); } finally { try { @@ -277,7 +275,7 @@ public class StorPoolAbandonObjectsCollector extends ManagerBase implements Conf pstmt.executeUpdate(); } catch (SQLException e) { txn.close(); - log.info(String.format("createTemporaryVolumeTable %s", e.getMessage())); + logger.info(String.format("createTemporaryVolumeTable %s", e.getMessage())); } txn.close(); } @@ -304,7 +302,7 @@ public class StorPoolAbandonObjectsCollector extends ManagerBase implements Conf String name = null; while (rs.next()) { name = rs.getString(2); - log.info(String.format( + logger.info(String.format( "CloudStack does not know about StorPool %s %s, it had to be a %s", object, name, rs.getString(3))); } } diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/api/StorPoolVolumeDef.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/api/StorPoolVolumeDef.java new file mode 100644 index 00000000000..456f5b90639 --- /dev/null +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/api/StorPoolVolumeDef.java @@ -0,0 +1,109 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +package org.apache.cloudstack.storage.datastore.api; + +import java.io.Serializable; +import java.util.Map; + +public class StorPoolVolumeDef implements Serializable { + + private static final long serialVersionUID = 1L; + private transient String name; + private Long size; + private Map tags; + private String parent; + private Long iops; + private String template; + private String baseOn; + private String rename; + private Boolean shrinkOk; + + public StorPoolVolumeDef() { + } + + public StorPoolVolumeDef(String name, Long size, Map tags, String parent, Long iops, String template, + String baseOn, String rename, Boolean shrinkOk) { + super(); + this.name = name; + this.size = size; + this.tags = tags; + this.parent = parent; + this.iops = iops; + this.template = template; + this.baseOn = baseOn; + this.rename = rename; + this.shrinkOk = shrinkOk; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Long getSize() { + return size; + } + public void setSize(Long size) { + this.size = size; + } + public Map getTags() { + return tags; + } + public void setTags(Map tags) { + this.tags = tags; + } + public String getParent() { + return parent; + } + public void setParent(String parent) { + this.parent = parent; + } + public Long getIops() { + return iops; + } + public void setIops(Long iops) { + this.iops = iops; + } + public String getTemplate() { + return template; + } + public void setTemplate(String template) { + this.template = template; + } + public String getBaseOn() { + return baseOn; + } + public void setBaseOn(String baseOn) { + this.baseOn = baseOn; + } + public String getRename() { + return rename; + } + public void setRename(String rename) { + this.rename = rename; + } + + public Boolean getShrinkOk() { + return shrinkOk; + } + + public void setShrinkOk(Boolean shrinkOk) { + this.shrinkOk = shrinkOk; + } +} diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/driver/StorPoolPrimaryDataStoreDriver.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/driver/StorPoolPrimaryDataStoreDriver.java index f5fdc96cb48..6ca67cb5923 100644 --- a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/driver/StorPoolPrimaryDataStoreDriver.java +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/driver/StorPoolPrimaryDataStoreDriver.java @@ -24,6 +24,7 @@ import java.util.Map; import javax.inject.Inject; +import com.cloud.storage.dao.SnapshotDetailsVO; import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; @@ -39,12 +40,15 @@ import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.resourcedetail.DiskOfferingDetailVO; +import org.apache.cloudstack.resourcedetail.dao.DiskOfferingDetailsDao; import org.apache.cloudstack.storage.RemoteHostEndPoint; import org.apache.cloudstack.storage.command.CommandResult; import org.apache.cloudstack.storage.command.CopyCmdAnswer; import org.apache.cloudstack.storage.command.CreateObjectAnswer; import org.apache.cloudstack.storage.command.StorageSubSystemCommand; import org.apache.cloudstack.storage.datastore.api.StorPoolSnapshotDef; +import org.apache.cloudstack.storage.datastore.api.StorPoolVolumeDef; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; @@ -65,7 +69,6 @@ import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.storage.volume.VolumeObject; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; -import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.ResizeVolumeAnswer; @@ -82,12 +85,18 @@ import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.dc.dao.ClusterDao; +import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.kvm.storage.StorPoolStorageAdaptor; +import com.cloud.offering.DiskOffering; import com.cloud.server.ResourceTag; import com.cloud.server.ResourceTag.ResourceObjectType; +import com.cloud.service.ServiceOfferingDetailsVO; +import com.cloud.service.ServiceOfferingVO; +import com.cloud.service.dao.ServiceOfferingDao; +import com.cloud.service.dao.ServiceOfferingDetailsDao; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ResizeVolumePayload; import com.cloud.storage.Snapshot; @@ -102,7 +111,6 @@ import com.cloud.storage.VolumeDetailVO; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.SnapshotDetailsDao; -import com.cloud.storage.dao.SnapshotDetailsVO; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.VMTemplateDetailsDao; import com.cloud.storage.dao.VolumeDao; @@ -114,10 +122,12 @@ import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.dao.VMInstanceDao; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { - private static final Logger log = Logger.getLogger(StorPoolPrimaryDataStoreDriver.class); + protected Logger logger = LogManager.getLogger(getClass()); @Inject private VolumeDao volumeDao; @@ -155,6 +165,12 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { private StoragePoolHostDao storagePoolHostDao; @Inject DataStoreManager dataStoreManager; + @Inject + private DiskOfferingDetailsDao diskOfferingDetailsDao; + @Inject + private ServiceOfferingDetailsDao serviceOfferingDetailDao; + @Inject + private ServiceOfferingDao serviceOfferingDao; private SnapshotDataStoreVO getSnapshotImageStoreRef(long snapshotId, long zoneId) { List snaps = snapshotDataStoreDao.listReadyBySnapshot(snapshotId, DataStoreRole.Image); @@ -258,15 +274,25 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { public void createAsync(DataStore dataStore, DataObject data, AsyncCompletionCallback callback) { String path = null; Answer answer; + String tier = null; + String template = null; if (data.getType() == DataObjectType.VOLUME) { try { VolumeInfo vinfo = (VolumeInfo)data; String name = vinfo.getUuid(); Long size = vinfo.getPassphraseId() == null ? vinfo.getSize() : vinfo.getSize() + 2097152; + Long vmId = vinfo.getInstanceId(); + SpConnectionDesc conn = StorPoolUtil.getSpConnection(dataStore.getUuid(), dataStore.getId(), storagePoolDetailsDao, primaryStoreDao); - StorPoolUtil.spLog("StorpoolPrimaryDataStoreDriver.createAsync volume: name=%s, uuid=%s, isAttached=%s vm=%s, payload=%s, template: %s", vinfo.getName(), vinfo.getUuid(), vinfo.isAttachedVM(), vinfo.getAttachedVmName(), vinfo.getpayload(), conn.getTemplateName()); - SpApiResponse resp = StorPoolUtil.volumeCreate(name, null, size, getVMInstanceUUID(vinfo.getInstanceId()), null, "volume", vinfo.getMaxIops(), conn); + if (vinfo.getDiskOfferingId() != null) { + tier = getTierFromOfferingDetail(vinfo.getDiskOfferingId()); + if (tier == null) { + template = getTemplateFromOfferingDetail(vinfo.getDiskOfferingId()); + } + } + + SpApiResponse resp = createStorPoolVolume(template, tier, vinfo, name, size, vmId, conn); if (resp.getError() == null) { String volumeName = StorPoolUtil.getNameFromResponse(resp, false); path = StorPoolUtil.devPath(volumeName); @@ -297,6 +323,26 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { } } + private SpApiResponse createStorPoolVolume(String template, String tier, VolumeInfo vinfo, String name, Long size, + Long vmId, SpConnectionDesc conn) { + SpApiResponse resp = new SpApiResponse(); + Map tags = StorPoolHelper.addStorPoolTags(name, getVMInstanceUUID(vmId), "volume", getVcPolicyTag(vmId), tier); + if (tier != null || template != null) { + StorPoolUtil.spLog( + "Creating volume [%s] with template [%s] or tier tags [%s] described in disk/service offerings details", + vinfo.getUuid(), template, tier); + resp = StorPoolUtil.volumeCreate(size, null, template, tags, conn); + } else { + StorPoolUtil.spLog( + "StorpoolPrimaryDataStoreDriver.createAsync volume: name=%s, uuid=%s, isAttached=%s vm=%s, payload=%s, template: %s", + vinfo.getName(), vinfo.getUuid(), vinfo.isAttachedVM(), vinfo.getAttachedVmName(), + vinfo.getpayload(), conn.getTemplateName()); + resp = StorPoolUtil.volumeCreate(name, null, size, getVMInstanceUUID(vinfo.getInstanceId()), null, + "volume", vinfo.getMaxIops(), conn); + } + return resp; + } + private void updateVolume(DataStore dataStore, String path, VolumeInfo vinfo) { VolumeVO volume = volumeDao.findById(vinfo.getId()); volume.setPoolId(dataStore.getId()); @@ -335,68 +381,120 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { public void resize(DataObject data, AsyncCompletionCallback callback) { String path = null; String err = null; - ResizeVolumeAnswer answer = null; if (data.getType() == DataObjectType.VOLUME) { VolumeObject vol = (VolumeObject)data; - StoragePool pool = (StoragePool)data.getDataStore(); - ResizeVolumePayload payload = (ResizeVolumePayload)vol.getpayload(); + path = vol.getPath(); - final String name = StorPoolStorageAdaptor.getVolumeNameFromPath(vol.getPath(), true); - final long oldSize = vol.getSize(); - Long oldMaxIops = vol.getMaxIops(); - - try { - SpConnectionDesc conn = StorPoolUtil.getSpConnection(data.getDataStore().getUuid(), data.getDataStore().getId(), storagePoolDetailsDao, primaryStoreDao); - - long maxIops = payload.newMaxIops == null ? Long.valueOf(0) : payload.newMaxIops; - - StorPoolUtil.spLog("StorpoolPrimaryDataStoreDriverImpl.resize: name=%s, uuid=%s, oldSize=%d, newSize=%s, shrinkOk=%s, maxIops=%s", name, vol.getUuid(), oldSize, payload.newSize, payload.shrinkOk, maxIops); - - SpApiResponse resp = StorPoolUtil.volumeUpdate(name, payload.newSize, payload.shrinkOk, maxIops, conn); - if (resp.getError() != null) { - err = String.format("Could not resize StorPool volume %s. Error: %s", name, resp.getError()); - } else { - StorPoolResizeVolumeCommand resizeCmd = new StorPoolResizeVolumeCommand(vol.getPath(), new StorageFilerTO(pool), vol.getSize(), payload.newSize, payload.shrinkOk, - payload.instanceName, payload.hosts == null ? false : true); - answer = (ResizeVolumeAnswer) storageMgr.sendToPool(pool, payload.hosts, resizeCmd); - - if (answer == null || !answer.getResult()) { - err = answer != null ? answer.getDetails() : "return a null answer, resize failed for unknown reason"; - } else { - path = StorPoolUtil.devPath(StorPoolUtil.getNameFromResponse(resp, false)); - - vol.setSize(payload.newSize); - vol.update(); - if (payload.newMaxIops != null) { - VolumeVO volume = volumeDao.findById(vol.getId()); - volume.setMaxIops(payload.newMaxIops); - volumeDao.update(volume.getId(), volume); - } - - updateStoragePool(vol.getPoolId(), payload.newSize - oldSize); - } - } - if (err != null) { - // try restoring volume to its initial size - resp = StorPoolUtil.volumeUpdate(name, oldSize, true, oldMaxIops, conn); - if (resp.getError() != null) { - log.debug(String.format("Could not resize StorPool volume %s back to its original size. Error: %s", name, resp.getError())); - } - } - } catch (Exception e) { - log.debug("sending resize command failed", e); - err = e.toString(); - } + err = resizeVolume(data, path, vol); } else { err = String.format("Invalid object type \"%s\" passed to resize", data.getType()); } - CreateCmdResult res = new CreateCmdResult(path, answer); + CreateCmdResult res = new CreateCmdResult(path, new Answer(null, err != null, err)); res.setResult(err); callback.complete(res); } + private String resizeVolume(DataObject data, String path, VolumeObject vol) { + String err = null; + ResizeVolumePayload payload = (ResizeVolumePayload)vol.getpayload(); + boolean needResize = vol.getSize() != payload.newSize; + + final String name = StorPoolStorageAdaptor.getVolumeNameFromPath(path, true); + final long oldSize = vol.getSize(); + Long oldMaxIops = vol.getMaxIops(); + + try { + SpConnectionDesc conn = StorPoolUtil.getSpConnection(data.getDataStore().getUuid(), data.getDataStore().getId(), storagePoolDetailsDao, primaryStoreDao); + + err = updateStorPoolVolume(vol, payload, conn); + if (err == null && needResize) { + err = notifyQemuForTheNewSize(data, err, vol, payload); + } + if (err != null) { + // try restoring volume to its initial size + SpApiResponse response = StorPoolUtil.volumeUpdate(name, oldSize, true, oldMaxIops, conn); + if (response.getError() != null) { + logger.debug(String.format("Could not resize StorPool volume %s back to its original size. Error: %s", name, response.getError())); + } + } else { + updateVolumeWithTheNewSize(vol, payload); + } + } catch (Exception e) { + logger.debug("sending resize command failed", e); + err = e.toString(); + } + return err; + } + + private void updateVolumeWithTheNewSize(VolumeObject vol, ResizeVolumePayload payload) { + vol.setSize(payload.newSize); + vol.update(); + if (payload.newMaxIops != null) { + VolumeVO volume = volumeDao.findById(vol.getId()); + volume.setMaxIops(payload.newMaxIops); + volumeDao.update(volume.getId(), volume); + } + updateStoragePool(vol.getPoolId(), payload.newSize - vol.getSize()); + } + + private String notifyQemuForTheNewSize(DataObject data, String err, VolumeObject vol, ResizeVolumePayload payload) + throws StorageUnavailableException { + StoragePool pool = (StoragePool)data.getDataStore(); + + StorPoolResizeVolumeCommand resizeCmd = new StorPoolResizeVolumeCommand(vol.getPath(), new StorageFilerTO(pool), vol.getSize(), payload.newSize, payload.shrinkOk, + payload.instanceName, payload.hosts == null ? false : true); + ResizeVolumeAnswer answer = (ResizeVolumeAnswer) storageMgr.sendToPool(pool, payload.hosts, resizeCmd); + + if (answer == null || !answer.getResult()) { + err = answer != null ? answer.getDetails() : "return a null answer, resize failed for unknown reason"; + } + return err; + } + + private String updateStorPoolVolume(VolumeObject vol, ResizeVolumePayload payload, SpConnectionDesc conn) { + String err = null; + String name = StorPoolStorageAdaptor.getVolumeNameFromPath(vol.getPath(), true); + Long newDiskOfferingId = payload.getNewDiskOfferingId(); + String tier = null; + String template = null; + if (newDiskOfferingId != null) { + tier = getTierFromOfferingDetail(newDiskOfferingId); + if (tier == null) { + template = getTemplateFromOfferingDetail(newDiskOfferingId); + } + } + SpApiResponse resp = new SpApiResponse(); + if (tier != null || template != null) { + resp = updateVolumeByStorPoolQoS(payload, conn, name, tier, template); + } else { + resp = updateVolumeByOffering(vol, payload, conn, name); + } + if (resp.getError() != null) { + err = String.format("Could not resize StorPool volume %s. Error: %s", name, resp.getError()); + } + return err; + } + + private static SpApiResponse updateVolumeByStorPoolQoS(ResizeVolumePayload payload, SpConnectionDesc conn, String name, String tier, String template) { + Map tags = StorPoolHelper.addStorPoolTags(null, null, null, null, tier); + StorPoolVolumeDef spVolume = new StorPoolVolumeDef(name, payload.newSize, tags, null, null, template, null, null, + payload.shrinkOk); + return StorPoolUtil.volumeUpdate(spVolume, conn); + } + + private static SpApiResponse updateVolumeByOffering(VolumeObject vol, ResizeVolumePayload payload, SpConnectionDesc conn, String name) { + long maxIops = payload.newMaxIops == null ? Long.valueOf(0) : payload.newMaxIops; + + StorPoolVolumeDef spVolume = new StorPoolVolumeDef(name, payload.newSize, null, null, maxIops, null, null, null, + payload.shrinkOk); + StorPoolUtil.spLog( + "StorpoolPrimaryDataStoreDriverImpl.resize: name=%s, uuid=%s, oldSize=%d, newSize=%s, shrinkOk=%s, maxIops=%s", + name, vol.getUuid(), vol.getSize(), payload.newSize, payload.shrinkOk, maxIops); + return StorPoolUtil.volumeUpdate(spVolume, conn); + } + @Override public void deleteAsync(DataStore dataStore, DataObject data, AsyncCompletionCallback callback) { String err = null; @@ -430,7 +528,7 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { } if (err != null) { - log.error(err); + logger.error(err); StorPoolUtil.spLog(err); } @@ -551,57 +649,16 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { SnapshotDataStoreVO snap = getSnapshotImageStoreRef(sinfo.getId(), vinfo.getDataCenterId()); SnapshotDetailsVO snapshotDetail = snapshotDetailsDao.findDetail(sinfo.getId(), StorPoolUtil.SP_DELAY_DELETE); if (snapshotDetail != null) { - err = String.format("Could not create volume from snapshot due to: %s", resp.getError()); + err = String.format("Could not create volume from snapshot due to: %s. The snapshot was created with the delayDelete option.", resp.getError()); } else if (snap != null && StorPoolStorageAdaptor.getVolumeNameFromPath(snap.getInstallPath(), false) == null) { - resp = StorPoolUtil.volumeCreate(srcData.getUuid(), null, size, null, "no", "snapshot", sinfo.getBaseVolume().getMaxIops(), conn); - if (resp.getError() == null) { - VolumeObjectTO dstTO = (VolumeObjectTO) dstData.getTO(); - dstTO.setSize(size); - dstTO.setPath(StorPoolUtil.devPath(StorPoolUtil.getNameFromResponse(resp, false))); - cmd = new StorPoolDownloadTemplateCommand(srcData.getTO(), dstTO, StorPoolHelper.getTimeout(StorPoolHelper.PrimaryStorageDownloadWait, configDao), VirtualMachineManager.ExecuteInSequence.value(), "volume"); - - EndPoint ep = selector.select(srcData, dstData); - if (ep == null) { - err = "No remote endpoint to send command, check if host or ssvm is down?"; - } else { - answer = ep.sendMessage(cmd); - } - - if (answer != null && answer.getResult()) { - SpApiResponse resp2 = StorPoolUtil.volumeFreeze(StorPoolUtil.getNameFromResponse(resp, true), conn); - if (resp2.getError() != null) { - err = String.format("Could not freeze Storpool volume %s. Error: %s", srcData.getUuid(), resp2.getError()); - } else { - String name = StorPoolUtil.getNameFromResponse(resp, false); - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(sinfo.getId(), sinfo.getUuid()); - if (snapshotDetails != null) { - StorPoolHelper.updateSnapshotDetailsValue(snapshotDetails.getId(), StorPoolUtil.devPath(name), "snapshot"); - }else { - StorPoolHelper.addSnapshotDetails(sinfo.getId(), sinfo.getUuid(), StorPoolUtil.devPath(name), snapshotDetailsDao); - } - resp = StorPoolUtil.volumeCreate(volumeName, StorPoolUtil.getNameFromResponse(resp, true), size, null, null, "volume", sinfo.getBaseVolume().getMaxIops(), conn); - if (resp.getError() == null) { - updateStoragePool(dstData.getDataStore().getId(), size); - - VolumeObjectTO to = (VolumeObjectTO) dstData.getTO(); - to.setPath(StorPoolUtil.devPath(StorPoolUtil.getNameFromResponse(resp, false))); - to.setSize(size); - // successfully downloaded snapshot to primary storage - answer = new CopyCmdAnswer(to); - StorPoolUtil.spLog("Created volume=%s with uuid=%s from snapshot=%s with uuid=%s", name, to.getUuid(), snapshotName, sinfo.getUuid()); - - } else { - err = String.format("Could not create Storpool volume %s from snapshot %s. Error: %s", volumeName, snapshotName, resp.getError()); - } - } - } else { - err = answer != null ? answer.getDetails() : "Unknown error while downloading template. Null answer returned."; - } + SpApiResponse emptyVolumeCreateResp = StorPoolUtil.volumeCreate(volumeName, null, size, null, null, "volume", null, conn); + if (emptyVolumeCreateResp.getError() == null) { + answer = createVolumeFromSnapshot(srcData, dstData, size, emptyVolumeCreateResp); } else { - err = String.format("Could not create Storpool volume %s from snapshot %s. Error: %s", volumeName, snapshotName, resp.getError()); + answer = new Answer(cmd, false, String.format("Could not create Storpool volume %s from snapshot %s. Error: %s", volumeName, snapshotName, emptyVolumeCreateResp.getError())); } } else { - err = String.format("The snapshot %s does not exists neither on primary, neither on secondary storage. Cannot create volume from snapshot", snapshotName); + answer = new Answer(cmd, false, String.format("The snapshot %s does not exists neither on primary, neither on secondary storage. Cannot create volume from snapshot", snapshotName)); } } else { err = String.format("Could not create Storpool volume %s from snapshot %s. Error: %s", volumeName, snapshotName, resp.getError()); @@ -632,7 +689,7 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { SpApiResponse resp = StorPoolUtil.snapshotDelete(snapName, conn); if (resp.getError() != null) { final String err2 = String.format("Failed to cleanup StorPool snapshot '%s'. Error: %s.", snapName, resp.getError()); - log.error(err2); + logger.error(err2); StorPoolUtil.spLog(err2); } } @@ -663,7 +720,7 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { if (answer != null && answer.getResult()) { SpApiResponse resSnapshot = StorPoolUtil.volumeSnapshot(volumeName, template.getUuid(), null, "template", "no", conn); if (resSnapshot.getError() != null) { - log.debug(String.format("Could not snapshot volume with ID=%s", volume.getId())); + logger.debug(String.format("Could not snapshot volume with ID=%s", volume.getId())); StorPoolUtil.spLog("Volume snapshot failed with error=%s", resSnapshot.getError().getDescr()); err = resSnapshot.getError().getDescr(); } @@ -702,22 +759,17 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { err = String.format("Could not create Storpool volume for CS template %s. Error: %s", name, resp.getError()); } else { String volumeNameToSnapshot = StorPoolUtil.getNameFromResponse(resp, true); - SpApiResponse resp2 = StorPoolUtil.volumeFreeze(volumeNameToSnapshot, conn); - if (resp2.getError() != null) { - err = String.format("Could not freeze Storpool volume %s. Error: %s", name, resp2.getError()); - } else { - StorPoolUtil.spLog("Storpool snapshot [%s] for a template exists. Creating template on Storpool with name [%s]", tinfo.getUuid(), name); - TemplateObjectTO dstTO = (TemplateObjectTO) dstData.getTO(); - dstTO.setPath(StorPoolUtil.devPath(StorPoolUtil.getNameFromResponse(resp, false))); - dstTO.setSize(size); - answer = new CopyCmdAnswer(dstTO); - } + TemplateObjectTO dstTO = (TemplateObjectTO) dstData.getTO(); + + answer = createVolumeSnapshot(cmd, size, conn, volumeNameToSnapshot, dstTO); + StorPoolUtil.volumeDelete(volumeNameToSnapshot, conn); } } else { resp = StorPoolUtil.volumeCreate(name, null, size, null, "no", "template", null, conn); if (resp.getError() != null) { err = String.format("Could not create Storpool volume for CS template %s. Error: %s", name, resp.getError()); } else { + String volName = StorPoolUtil.getNameFromResponse(resp, true); TemplateObjectTO dstTO = (TemplateObjectTO)dstData.getTO(); dstTO.setPath(StorPoolUtil.devPath(StorPoolUtil.getNameFromResponse(resp, false))); dstTO.setSize(size); @@ -733,19 +785,13 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { if (answer != null && answer.getResult()) { // successfully downloaded template to primary storage - SpApiResponse resp2 = StorPoolUtil.volumeFreeze(StorPoolUtil.getNameFromResponse(resp, true), conn); - if (resp2.getError() != null) { - err = String.format("Could not freeze Storpool volume %s. Error: %s", name, resp2.getError()); - } + TemplateObjectTO templ = (TemplateObjectTO) ((CopyCmdAnswer) answer).getNewData(); + answer = createVolumeSnapshot(cmd, size, conn, volName, templ); } else { err = answer != null ? answer.getDetails() : "Unknown error while downloading template. Null answer returned."; } - } - } - if (err != null) { - resp = StorPoolUtil.volumeDelete(StorPoolUtil.getNameFromResponse(resp, true), conn); - if (resp.getError() != null) { - log.warn(String.format("Could not clean-up Storpool volume %s. Error: %s", name, resp.getError())); + + StorPoolUtil.volumeDelete(volName, conn); } } } else if (srcType == DataObjectType.TEMPLATE && dstType == DataObjectType.VOLUME) { @@ -771,8 +817,30 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { } StorPoolUtil.spLog(String.format("volume size is: %d", size)); Long vmId = vinfo.getInstanceId(); - SpApiResponse resp = StorPoolUtil.volumeCreate(name, parentName, size, getVMInstanceUUID(vmId), getVcPolicyTag(vmId), - "volume", vinfo.getMaxIops(), conn); + + String template = null; + String tier = null; + SpApiResponse resp = new SpApiResponse(); + + if (vinfo.getDiskOfferingId() != null) { + tier = getTierFromOfferingDetail(vinfo.getDiskOfferingId()); + if (tier == null) { + template = getTemplateFromOfferingDetail(vinfo.getDiskOfferingId()); + } + } + + if (tier != null || template != null) { + Map tags = StorPoolHelper.addStorPoolTags(name, getVMInstanceUUID(vmId), "volume", getVcPolicyTag(vmId), tier); + + StorPoolUtil.spLog( + "Creating volume [%s] with template [%s] or tier tags [%s] described in disk/service offerings details", + vinfo.getUuid(), template, tier); + resp = StorPoolUtil.volumeCreate(size, parentName, template, tags, conn); + } else { + resp = StorPoolUtil.volumeCreate(name, parentName, size, getVMInstanceUUID(vmId), + getVcPolicyTag(vmId), "volume", vinfo.getMaxIops(), conn); + } + if (resp.getError() == null) { updateStoragePool(dstData.getDataStore().getId(), vinfo.getSize()); updateVolumePoolType(vinfo); @@ -838,7 +906,7 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { if (err != null) { SpApiResponse resp3 = StorPoolUtil.volumeDelete(name, conn); if (resp3.getError() != null) { - log.warn(String.format("Could not clean-up Storpool volume %s. Error: %s", name, resp3.getError())); + logger.warn(String.format("Could not clean-up Storpool volume %s. Error: %s", name, resp3.getError())); } } } @@ -887,7 +955,7 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { final SpApiResponse resp2 = StorPoolUtil.snapshotDelete(snapshotName, conn); if (resp2.getError() != null) { final String err2 = String.format("Failed to delete temporary StorPool snapshot %s. Error: %s", StorPoolUtil.getNameFromResponse(resp, true), resp2.getError()); - log.error(err2); + logger.error(err2); StorPoolUtil.spLog(err2); } } @@ -907,7 +975,7 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { if (err != null) { StorPoolUtil.spLog("Failed due to %s", err); - log.error(err); + logger.error(err); answer = new Answer(cmd, false, err); } @@ -916,6 +984,41 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { callback.complete(res); } + private Answer createVolumeSnapshot(StorageSubSystemCommand cmd, Long size, SpConnectionDesc conn, + String volName, TemplateObjectTO dstTO) { + Answer answer; + SpApiResponse resp = StorPoolUtil.volumeSnapshot(volName, dstTO.getUuid(), null, "template", null, conn); + if (resp.getError() != null) { + answer = new Answer(cmd, false, String.format("Could not snapshot volume. Error: %s", resp.getError())); + } else { + dstTO.setPath(StorPoolUtil.devPath( + StorPoolUtil.getSnapshotNameFromResponse(resp, false, StorPoolUtil.GLOBAL_ID))); + answer = new CopyCmdAnswer(dstTO); + } + return answer; + } + + private Answer createVolumeFromSnapshot(DataObject srcData, DataObject dstData, final Long size, + SpApiResponse emptyVolumeCreateResp) { + Answer answer; + String name = StorPoolUtil.getNameFromResponse(emptyVolumeCreateResp, false); + VolumeObjectTO dstTO = (VolumeObjectTO) dstData.getTO(); + dstTO.setSize(size); + dstTO.setPath(StorPoolUtil.devPath(name)); + StorageSubSystemCommand cmd = new StorPoolDownloadTemplateCommand(srcData.getTO(), dstTO, StorPoolHelper.getTimeout(StorPoolHelper.PrimaryStorageDownloadWait, configDao), VirtualMachineManager.ExecuteInSequence.value(), "volume"); + + EndPoint ep = selector.select(srcData, dstData); + if (ep == null) { + answer = new Answer(cmd, false, "\"No remote endpoint to send command, check if host or ssvm is down?\""); + } else { + answer = ep.sendMessage(cmd); + } + if (answer == null || !answer.getResult()) { + answer = new Answer(cmd, false, answer != null ? answer.getDetails() : "Unknown error while downloading template. Null answer returned."); + } + return answer; + } + private void updateVolumePoolType(VolumeInfo vinfo) { VolumeVO volumeVO = volumeDao.findById(vinfo.getId()); volumeVO.setPoolType(StoragePoolType.StorPool); @@ -1124,7 +1227,7 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { } public void handleQualityOfServiceForVolumeMigration(VolumeInfo arg0, QualityOfServiceState arg1) { - log.debug(String.format("handleQualityOfServiceForVolumeMigration with volume name=%s is not supported", arg0.getName())); + logger.debug(String.format("handleQualityOfServiceForVolumeMigration with volume name=%s is not supported", arg0.getName())); } @@ -1208,10 +1311,10 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { VMInstanceVO userVM = vmInstanceDao.findById(vmId); SpApiResponse resp = StorPoolUtil.volumeUpdateIopsAndTags(volName, volume.getInstanceId() != null ? userVM.getUuid() : "", null, conn, getVcPolicyTag(vmId)); if (resp.getError() != null) { - log.warn(String.format("Could not update VC policy tags of a volume with id [%s]", volume.getUuid())); + logger.warn(String.format("Could not update VC policy tags of a volume with id [%s]", volume.getUuid())); } } catch (Exception e) { - log.warn(String.format("Could not update Virtual machine tags due to %s", e.getMessage())); + logger.warn(String.format("Could not update Virtual machine tags due to %s", e.getMessage())); } } } @@ -1231,10 +1334,10 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { String volName = StorPoolStorageAdaptor.getVolumeNameFromPath(volume.getPath(), true); SpApiResponse resp = StorPoolUtil.volumeUpdateVCTags(volName, conn, getVcPolicyTag(vmId)); if (resp.getError() != null) { - log.warn(String.format("Could not update VC policy tags of a volume with id [%s]", volume.getUuid())); + logger.warn(String.format("Could not update VC policy tags of a volume with id [%s]", volume.getUuid())); } } catch (Exception e) { - log.warn(String.format("Could not update Virtual machine tags due to %s", e.getMessage())); + logger.warn(String.format("Could not update Virtual machine tags due to %s", e.getMessage())); } } } @@ -1254,4 +1357,67 @@ public class StorPoolPrimaryDataStoreDriver implements PrimaryDataStoreDriver { StorPoolUtil.spLog("The volume [%s] is detach from all clusters [%s]", volName, resp); } } + + @Override + public boolean informStorageForDiskOfferingChange() { + return true; + } + + @Override + public void updateStorageWithTheNewDiskOffering(Volume volume, DiskOffering newDiskOffering) { + if (newDiskOffering == null) { + return; + } + + StoragePoolVO pool = primaryStoreDao.findById(volume.getPoolId()); + if (pool == null) { + return; + } + + String tier = getTierFromOfferingDetail(newDiskOffering.getId()); + String template = null; + if (tier == null) { + template = getTemplateFromOfferingDetail(newDiskOffering.getId()); + } + if (tier == null && template == null) { + return; + } + SpConnectionDesc conn = StorPoolUtil.getSpConnection(pool.getUuid(), pool.getId(), storagePoolDetailsDao, primaryStoreDao); + StorPoolUtil.spLog("Updating volume [%s] with tier tag [%s] or template [%s] from Disk offering", volume.getId(), tier, template); + String volumeName = StorPoolStorageAdaptor.getVolumeNameFromPath(volume.getPath(), true); + Map tags = StorPoolHelper.addStorPoolTags(null, null, null, null, tier); + StorPoolVolumeDef spVolume = new StorPoolVolumeDef(volumeName, null, tags, null, null, template, null, null, null); + SpApiResponse response = StorPoolUtil.volumeUpdate(spVolume, conn); + if (response.getError() != null) { + StorPoolUtil.spLog("Could not update volume [%s] with tier tag [%s] or template [%s] from Disk offering due to [%s]", volume.getId(), tier, template, response.getError()); + } + } + + private String getTemplateFromOfferingDetail(Long diskOfferingId) { + String template = null; + DiskOfferingDetailVO diskOfferingDetail = diskOfferingDetailsDao.findDetail(diskOfferingId, StorPoolUtil.SP_TEMPLATE); + if (diskOfferingDetail == null ) { + ServiceOfferingVO serviceOffering = serviceOfferingDao.findServiceOfferingByComputeOnlyDiskOffering(diskOfferingId, true); + if (serviceOffering != null) { + ServiceOfferingDetailsVO serviceOfferingDetail = serviceOfferingDetailDao.findDetail(serviceOffering.getId(), StorPoolUtil.SP_TEMPLATE); + if (serviceOfferingDetail != null) { + template = serviceOfferingDetail.getValue(); + } + } + } else { + template = diskOfferingDetail.getValue(); + } + return template; + } + + private String getTierFromOfferingDetail(Long diskOfferingId) { + String tier = null; + DiskOfferingDetailVO diskOfferingDetail = diskOfferingDetailsDao.findDetail(diskOfferingId, StorPoolUtil.SP_TIER); + if (diskOfferingDetail == null ) { + return tier; + } else { + tier = diskOfferingDetail.getValue(); + } + return tier; + } } diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/driver/StorPoolStatsCollector.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/driver/StorPoolStatsCollector.java index 44acd1eab75..56b150a04e6 100644 --- a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/driver/StorPoolStatsCollector.java +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/driver/StorPoolStatsCollector.java @@ -38,7 +38,6 @@ import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.datastore.util.StorPoolUtil; import org.apache.cloudstack.storage.snapshot.StorPoolConfigurationManager; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; import org.apache.commons.lang3.StringUtils; import com.cloud.storage.DataStoreRole; @@ -57,8 +56,6 @@ import com.google.gson.JsonObject; public class StorPoolStatsCollector extends ManagerBase { - private static Logger log = Logger.getLogger(StorPoolStatsCollector.class); - @Inject private PrimaryDataStoreDao storagePoolDao; @Inject @@ -116,19 +113,19 @@ public class StorPoolStatsCollector extends ManagerBase { if (CollectionUtils.isNotEmpty(spPools)) { volumesStats.clear(); - log.debug("Collecting StorPool volumes used space"); + logger.debug("Collecting StorPool volumes used space"); Map onePoolforZone = new HashMap<>(); for (StoragePoolVO storagePoolVO : spPools) { onePoolforZone.put(storagePoolVO.getDataCenterId(), storagePoolVO); } for (StoragePoolVO storagePool : onePoolforZone.values()) { try { - log.debug(String.format("Collecting volumes statistics for zone [%s]", storagePool.getDataCenterId())); + logger.debug(String.format("Collecting volumes statistics for zone [%s]", storagePool.getDataCenterId())); JsonArray arr = StorPoolUtil.volumesSpace(StorPoolUtil.getSpConnection(storagePool.getUuid(), storagePool.getId(), storagePoolDetailsDao, storagePoolDao)); volumesStats.putAll(getClusterVolumeOrTemplateSpace(arr, StorPoolObject.VOLUME)); } catch (Exception e) { - log.debug(String.format("Could not collect StorPool volumes statistics due to %s", e.getMessage())); + logger.debug(String.format("Could not collect StorPool volumes statistics due to %s", e.getMessage())); } } } @@ -149,12 +146,12 @@ public class StorPoolStatsCollector extends ManagerBase { } for (StoragePoolVO storagePool : onePoolforZone.values()) { try { - log.debug(String.format("Collecting templates statistics for zone [%s]", storagePool.getDataCenterId())); + logger.debug(String.format("Collecting templates statistics for zone [%s]", storagePool.getDataCenterId())); JsonArray arr = StorPoolUtil.templatesStats(StorPoolUtil.getSpConnection(storagePool.getUuid(), storagePool.getId(), storagePoolDetailsDao, storagePoolDao)); templatesStats.put(storagePool.getDataCenterId(), getClusterVolumeOrTemplateSpace(arr, StorPoolObject.TEMPLATE)); } catch (Exception e) { - log.debug(String.format("Could not collect StorPool templates statistics %s", e.getMessage())); + logger.debug(String.format("Could not collect StorPool templates statistics %s", e.getMessage())); } } } @@ -227,14 +224,14 @@ public class StorPoolStatsCollector extends ManagerBase { Map snapshotsWithDelayDelete = new HashMap<>(); try { - log.debug(String.format("Collecting snapshots marked to be deleted for zone [%s]", storagePool.getDataCenterId())); + logger.debug(String.format("Collecting snapshots marked to be deleted for zone [%s]", storagePool.getDataCenterId())); JsonArray arr = StorPoolUtil.snapshotsListAllClusters(StorPoolUtil.getSpConnection(storagePool.getUuid(), storagePool.getId(), storagePoolDetailsDao, storagePoolDao)); snapshotsWithDelayDelete.putAll(getSnapshotsMarkedForDeletion(arr)); - log.debug(String.format("Found snapshot details [%s] and snapshots on StorPool with delay delete flag [%s]", snapshotsDetails, snapshotsWithDelayDelete)); + logger.debug(String.format("Found snapshot details [%s] and snapshots on StorPool with delay delete flag [%s]", snapshotsDetails, snapshotsWithDelayDelete)); syncSnapshots(snapshotsDetails, snapshotsWithDelayDelete); } catch (Exception e) { - log.debug("Could not fetch the snapshots with delay delete flag " + e.getMessage()); + logger.debug("Could not fetch the snapshots with delay delete flag " + e.getMessage()); } } } @@ -276,7 +273,7 @@ public class StorPoolStatsCollector extends ManagerBase { } collectSnapshots(snapshotsWithDelayDelete, response); } - log.debug("Found snapshots on StorPool" + snapshotsWithDelayDelete); + logger.debug("Found snapshots on StorPool" + snapshotsWithDelayDelete); return snapshotsWithDelayDelete; } diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/StorPoolPrimaryDataStoreLifeCycle.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/StorPoolPrimaryDataStoreLifeCycle.java index 47f6089d734..60427e65ea6 100644 --- a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/StorPoolPrimaryDataStoreLifeCycle.java +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/StorPoolPrimaryDataStoreLifeCycle.java @@ -38,7 +38,6 @@ import org.apache.cloudstack.storage.datastore.util.StorPoolUtil; import org.apache.cloudstack.storage.datastore.util.StorPoolUtil.SpApiResponse; import org.apache.cloudstack.storage.datastore.util.StorPoolUtil.SpConnectionDesc; import org.apache.cloudstack.storage.volume.datastore.PrimaryDataStoreHelper; -import org.apache.log4j.Logger; import com.cloud.agent.api.StoragePoolInfo; import com.cloud.host.HostVO; @@ -61,8 +60,6 @@ import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.utils.exception.CloudRuntimeException; public class StorPoolPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLifeCycle { - private static final Logger log = Logger.getLogger(StorPoolPrimaryDataStoreLifeCycle.class); - @Inject protected PrimaryDataStoreHelper dataStoreHelper; @Inject @@ -92,7 +89,7 @@ public class StorPoolPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeC } StorPoolUtil.spLog(""); - log.debug("initialize"); + logger.debug("initialize"); String name = (String)dsInfos.get("name"); String providerName = (String)dsInfos.get("providerName"); @@ -186,18 +183,18 @@ public class StorPoolPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeC } StorPoolUtil.spLog(""); - log.debug("updateStoragePool"); + logger.debug("updateStoragePool"); return; } @Override public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { - log.debug("attachHost"); + logger.debug("attachHost"); return true; } @Override public boolean attachCluster(DataStore store, ClusterScope scope) { - log.debug("attachCluster"); + logger.debug("attachCluster"); if (!scope.getScopeType().equals(ScopeType.ZONE)) { throw new UnsupportedOperationException("Only Zone-Wide scope is supported!"); } @@ -206,7 +203,7 @@ public class StorPoolPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeC @Override public boolean attachZone(DataStore dataStore, ZoneScope scope, HypervisorType hypervisorType) { - log.debug("attachZone"); + logger.debug("attachZone"); if (hypervisorType != HypervisorType.KVM) { throw new UnsupportedOperationException("Only KVM hypervisors supported!"); @@ -214,9 +211,9 @@ public class StorPoolPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeC List kvmHosts = resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType.KVM, scope.getScopeId()); for (HostVO host : kvmHosts) { try { - storageMgr.connectHostToSharedPool(host.getId(), dataStore.getId()); + storageMgr.connectHostToSharedPool(host, dataStore.getId()); } catch (Exception e) { - log.warn(String.format("Unable to establish a connection between host %s and pool %s due to %s", host, dataStore, e)); + logger.warn(String.format("Unable to establish a connection between host %s and pool %s due to %s", host, dataStore, e)); } } dataStoreHelper.attachZone(dataStore, hypervisorType); @@ -225,7 +222,7 @@ public class StorPoolPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeC @Override public boolean maintain(DataStore dataStore) { - log.debug("maintain"); + logger.debug("maintain"); storagePoolAutmation.maintain(dataStore); dataStoreHelper.maintain(dataStore); @@ -234,7 +231,7 @@ public class StorPoolPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeC @Override public boolean cancelMaintain(DataStore store) { - log.debug("cancelMaintain"); + logger.debug("cancelMaintain"); dataStoreHelper.cancelMaintain(store); storagePoolAutmation.cancelMaintain(store); @@ -243,7 +240,7 @@ public class StorPoolPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeC @Override public boolean deleteDataStore(DataStore store) { - log.debug("deleteDataStore"); + logger.debug("deleteDataStore"); long storagePoolId = store.getId(); List lstSnapshots = snapshotDao.listAll(); @@ -303,19 +300,19 @@ public class StorPoolPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeC @Override public boolean migrateToObjectStore(DataStore store) { - log.debug("migrateToObjectStore"); + logger.debug("migrateToObjectStore"); return false; } @Override public void enableStoragePool(DataStore dataStore) { - log.debug("enableStoragePool"); + logger.debug("enableStoragePool"); dataStoreHelper.enable(dataStore); } @Override public void disableStoragePool(DataStore dataStore) { - log.debug("disableStoragePool"); + logger.debug("disableStoragePool"); dataStoreHelper.disable(dataStore); } } diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/provider/StorPoolHostListener.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/provider/StorPoolHostListener.java index bf7642b9122..7e0986bc63b 100644 --- a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/provider/StorPoolHostListener.java +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/provider/StorPoolHostListener.java @@ -40,7 +40,8 @@ import org.apache.cloudstack.storage.datastore.util.StorPoolUtil.SpConnectionDes import org.apache.cloudstack.storage.snapshot.StorPoolConfigurationManager; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -62,7 +63,7 @@ import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.utils.exception.CloudRuntimeException; public class StorPoolHostListener implements HypervisorHostListener { - private static final Logger log = Logger.getLogger(StorPoolHostListener .class); + protected Logger logger = LogManager.getLogger(getClass()); @Inject private AgentManager agentMgr; @@ -113,7 +114,7 @@ public class StorPoolHostListener implements HypervisorHostListener { if (!isCurrentVersionSupportsEverythingFromPrevious) { String msg = "The current StorPool driver does not support all functionality from the one before upgrade to CS"; StorPoolUtil.spLog("Storage pool [%s] is not connected to host [%s] because the functionality after the upgrade is not full", - poolId, hostId); + pool, host); alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, pool.getDataCenterId(), pool.getPodId(), msg, msg); return false; } @@ -125,24 +126,23 @@ public class StorPoolHostListener implements HypervisorHostListener { boolean isPoolConnectedToTheHost = poolHost != null; if (answer == null) { - StorPoolUtil.spLog("Storage pool [%s] is not connected to the host [%s]", poolVO.getName(), host.getName()); + StorPoolUtil.spLog("Storage pool [%s] is not connected to the host [%s]", poolVO, host); deleteVolumeWhenHostCannotConnectPool(conn, volumeOnPool); removePoolOnHost(poolHost, isPoolConnectedToTheHost); - throw new CloudRuntimeException("Unable to get an answer to the modify storage pool command" + pool.getId()); + throw new CloudRuntimeException(String.format("Unable to get an answer to the modify storage pool command for pool %s", pool)); } if (!answer.getResult()) { - StorPoolUtil.spLog("Storage pool [%s] is not connected to the host [%s]", poolVO.getName(), host.getName()); + StorPoolUtil.spLog("Storage pool [%s] is not connected to the host [%s]", poolVO, host); removePoolOnHost(poolHost, isPoolConnectedToTheHost); if (answer.getDetails() != null && isStorPoolVolumeOrStorageNotExistsOnHost(answer)) { deleteVolumeWhenHostCannotConnectPool(conn, volumeOnPool); return false; } - String msg = "Unable to attach storage pool" + poolId + " to the host" + hostId; + String msg = String.format("Unable to attach storage pool %s to the host %s", pool, host); alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, pool.getDataCenterId(), pool.getPodId(), msg, msg); - throw new CloudRuntimeException("Unable establish connection from storage head to storage pool " + pool.getId() + " due to " + answer.getDetails() + - pool.getId()); + throw new CloudRuntimeException(String.format("Unable establish connection from storage head to storage pool %s due to %s", pool, answer.getDetails())); } StorPoolModifyStoragePoolAnswer mspAnswer = (StorPoolModifyStoragePoolAnswer)answer; @@ -151,9 +151,8 @@ public class StorPoolHostListener implements HypervisorHostListener { List localStoragePools = primaryStoreDao.listLocalStoragePoolByPath(pool.getDataCenterId(), datastoreName); for (StoragePoolVO localStoragePool : localStoragePools) { if (datastoreName.equals(localStoragePool.getPath())) { - log.warn("Storage pool: " + pool.getId() + " has already been added as local storage: " + localStoragePool.getName()); - throw new StorageConflictException("Cannot add shared storage pool: " + pool.getId() + " because it has already been added as local storage:" - + localStoragePool.getName()); + logger.warn("Storage pool: {} has already been added as local storage: {}", pool, localStoragePool); + throw new StorageConflictException(String.format("Cannot add shared storage pool: %s because it has already been added as local storage: %s", pool, localStoragePool)); } } } @@ -172,7 +171,7 @@ public class StorPoolHostListener implements HypervisorHostListener { StorPoolHelper.setSpClusterIdIfNeeded(hostId, mspAnswer.getClusterId(), clusterDao, hostDao, clusterDetailsDao); - StorPoolUtil.spLog("Connection established between storage pool [%s] and host [%s]", poolVO.getName(), host.getName()); + StorPoolUtil.spLog("Connection established between storage pool [%s] and host [%s]", poolVO, host); return true; } @@ -259,7 +258,7 @@ public class StorPoolHostListener implements HypervisorHostListener { } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { String err = "Could not add StorPoolModifyStoragePoolCommand to s_commandsAllowedInMaintenanceMode array due to: %s"; StorPoolUtil.spLog(err, e.getMessage()); - log.warn(String.format(err, e.getMessage())); + logger.warn(String.format(err, e.getMessage())); } } diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/util/StorPoolHelper.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/util/StorPoolHelper.java index 9395f134fe1..f13d296af3b 100644 --- a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/util/StorPoolHelper.java +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/util/StorPoolHelper.java @@ -19,10 +19,7 @@ package org.apache.cloudstack.storage.datastore.util; -import java.io.IOException; import java.sql.PreparedStatement; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -41,10 +38,6 @@ import org.apache.cloudstack.storage.datastore.util.StorPoolUtil.SpApiResponse; import org.apache.cloudstack.storage.snapshot.StorPoolConfigurationManager; import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.commons.collections4.CollectionUtils; -import org.apache.log4j.Appender; -import org.apache.log4j.Logger; -import org.apache.log4j.PatternLayout; -import org.apache.log4j.RollingFileAppender; import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.ClusterDetailsVO; @@ -170,11 +163,12 @@ public class StorPoolHelper { return null; } - public static Map addStorPoolTags(String name, String vmUuid, String csTag, String vcPolicy) { + public static Map addStorPoolTags(String name, String vmUuid, String csTag, String vcPolicy, String qcTier) { Map tags = new HashMap<>(); tags.put("uuid", name); tags.put("cvm", vmUuid); tags.put(StorPoolUtil.SP_VC_POLICY, vcPolicy); + tags.put("qc", qcTier); if (csTag != null) { tags.put("cs", csTag); } @@ -182,30 +176,30 @@ public class StorPoolHelper { } // Initialize custom logger for updated volume and snapshots - public static void appendLogger(Logger log, String filePath, String kindOfLog) { - Appender appender = null; - PatternLayout patternLayout = new PatternLayout(); - patternLayout.setConversionPattern("%d{YYYY-MM-dd HH:mm:ss.SSS} %m%n"); - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); - Timestamp timestamp = new Timestamp(System.currentTimeMillis()); - String path = filePath + "-" + sdf.format(timestamp) + ".log"; - try { - appender = new RollingFileAppender(patternLayout, path); - log.setAdditivity(false); - log.addAppender(appender); - } catch (IOException e) { - e.printStackTrace(); - } - if (kindOfLog.equals("update")) { - StorPoolUtil.spLog( - "You can find information about volumes and snapshots, which will be updated in Database with their globalIs in %s log file", - path); - } else if (kindOfLog.equals("abandon")) { - StorPoolUtil.spLog( - "You can find information about volumes and snapshots, for which CloudStack doesn't have information in %s log file", - path); - } - } +// public static void appendLogger(Logger log, String filePath, String kindOfLog) { +// Appender appender = null; +// PatternLayout patternLayout = new PatternLayout(); +// patternLayout.setConversionPattern("%d{YYYY-MM-dd HH:mm:ss.SSS} %m%n"); +// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); +// Timestamp timestamp = new Timestamp(System.currentTimeMillis()); +// String path = filePath + "-" + sdf.format(timestamp) + ".log"; +// try { +// appender = new RollingFileAppender(patternLayout, path); +// log.setAdditivity(false); +// log.addAppender(appender); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// if (kindOfLog.equals("update")) { +// StorPoolUtil.spLog( +// "You can find information about volumes and snapshots, which will be updated in Database with their globalIs in %s log file", +// path); +// } else if (kindOfLog.equals("abandon")) { +// StorPoolUtil.spLog( +// "You can find information about volumes and snapshots, for which CloudStack doesn't have information in %s log file", +// path); +// } +// } public static void setSpClusterIdIfNeeded(long hostId, String clusterId, ClusterDao clusterDao, HostDao hostDao, ClusterDetailsDao clusterDetails) { @@ -225,17 +219,17 @@ public class StorPoolHelper { } public static Long findClusterIdByGlobalId(String globalId, ClusterDao clusterDao) { - List clusterVo = clusterDao.listAll(); - if (clusterVo.size() == 1) { + List clusterIds = clusterDao.listAllIds(); + if (clusterIds.size() == 1) { StorPoolUtil.spLog("There is only one cluster, sending backup to secondary command"); return null; } - for (ClusterVO clusterVO2 : clusterVo) { - if (globalId != null && StorPoolConfigurationManager.StorPoolClusterId.valueIn(clusterVO2.getId()) != null - && globalId.contains(StorPoolConfigurationManager.StorPoolClusterId.valueIn(clusterVO2.getId()).toString())) { - StorPoolUtil.spLog("Found cluster with id=%s for object with globalId=%s", clusterVO2.getId(), + for (Long clusterId : clusterIds) { + if (globalId != null && StorPoolConfigurationManager.StorPoolClusterId.valueIn(clusterId) != null + && globalId.contains(StorPoolConfigurationManager.StorPoolClusterId.valueIn(clusterId))) { + StorPoolUtil.spLog("Found cluster with id=%s for object with globalId=%s", clusterId, globalId); - return clusterVO2.getId(); + return clusterId; } } throw new CloudRuntimeException( diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/util/StorPoolUtil.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/util/StorPoolUtil.java index 58e87b2fba6..fd62157f136 100644 --- a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/util/StorPoolUtil.java +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/datastore/util/StorPoolUtil.java @@ -30,6 +30,7 @@ import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import org.apache.cloudstack.storage.datastore.api.StorPoolSnapshotDef; +import org.apache.cloudstack.storage.datastore.api.StorPoolVolumeDef; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO; import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; @@ -46,7 +47,8 @@ import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import java.io.BufferedReader; import java.io.File; @@ -69,7 +71,7 @@ import java.util.Map; import java.util.UUID; public class StorPoolUtil { - private static final Logger log = Logger.getLogger(StorPoolUtil.class); + protected static Logger LOGGER = LogManager.getLogger(StorPoolUtil.class); private static final File spLogFile = new File( Files.exists(Paths.get("/var/log/cloudstack/management/")) ? @@ -79,23 +81,23 @@ public class StorPoolUtil { private static PrintWriter spLogFileInitialize() { try { - log.info("INITIALIZE SP-LOG_FILE"); + LOGGER.info("INITIALIZE SP-LOGGER_FILE"); if (spLogFile.exists()) { final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); final Timestamp timestamp = new Timestamp(System.currentTimeMillis()); final File spLogFileRename = new File(spLogFile + "-" + sdf.format(timestamp)); final boolean ret = spLogFile.renameTo(spLogFileRename); if (!ret) { - log.warn("Unable to rename" + spLogFile + " to " + spLogFileRename); + LOGGER.warn("Unable to rename" + spLogFile + " to " + spLogFileRename); } else { - log.debug("Renamed " + spLogFile + " to " + spLogFileRename); + LOGGER.debug("Renamed " + spLogFile + " to " + spLogFileRename); } } else { spLogFile.getParentFile().mkdirs(); } return new PrintWriter(spLogFile); } catch (Exception e) { - log.info("INITIALIZE SP-LOG_FILE: " + e.getMessage()); + LOGGER.info("INITIALIZE SP-LOGGER_FILE: " + e.getMessage()); throw new RuntimeException(e); } } @@ -134,6 +136,9 @@ public class StorPoolUtil { public static final String DELAY_DELETE = "delayDelete"; + public static final String SP_TIER = "SP_QOSCLASS"; + + public static final String OBJECT_DOES_NOT_EXIST = "objectDoesNotExist"; public static enum StorpoolRights { RO("ro"), RW("rw"), DETACH("detach"); @@ -187,19 +192,19 @@ public class StorPoolUtil { extractUriParams(url); return; } catch (URISyntaxException e) { - log.debug("[ignore] the uri is not valid"); + LOGGER.debug("[ignore] the uri is not valid"); } String[] urlSplit = url.split(";"); if (urlSplit.length == 1 && !urlSplit[0].contains("=")) { this.templateName = url; - Script sc = new Script("storpool_confget", 0, log); + Script sc = new Script("storpool_confget", 0, LOGGER); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); final String err = sc.execute(parser); if (err != null) { final String errMsg = String.format("Could not execute storpool_confget. Error: %s", err); - log.warn(errMsg); + LOGGER.warn(errMsg); throw new CloudRuntimeException(errMsg); } @@ -407,7 +412,7 @@ public class StorPoolUtil { Gson gson = new Gson(); String js = gson.toJson(json); StringEntity input = new StringEntity(js, ContentType.APPLICATION_JSON); - log.info("Request:" + js); + LOGGER.info("Request:" + js); req.setEntity(input); } @@ -455,7 +460,7 @@ public class StorPoolUtil { } private static boolean objectExists(SpApiError err) { - if (!err.getName().equals("objectDoesNotExist")) { + if (!err.getName().equals(OBJECT_DOES_NOT_EXIST)) { throw new CloudRuntimeException(err.getDescr()); } return false; @@ -498,7 +503,19 @@ public class StorPoolUtil { json.put("parent", parentName); json.put("size", size); json.put("template", conn.getTemplateName()); - Map tags = StorPoolHelper.addStorPoolTags(name, vmUuid, csTag, vcPolicy); + Map tags = StorPoolHelper.addStorPoolTags(name, vmUuid, csTag, vcPolicy, null); + json.put("tags", tags); + return POST("MultiCluster/VolumeCreate", json, conn); + } + + public static SpApiResponse volumeCreate(Long size, String parentName, String template, Map tags, SpConnectionDesc conn) { + template = template != null ? template : conn.getTemplateName(); + + Map json = new LinkedHashMap<>(); + json.put("name", ""); + json.put("parent", parentName); + json.put("size", size); + json.put("template", template); json.put("tags", tags); return POST("MultiCluster/VolumeCreate", json, conn); } @@ -522,7 +539,7 @@ public class StorPoolUtil { json.put("iops", iops); } json.put("template", conn.getTemplateName()); - Map tags = StorPoolHelper.addStorPoolTags(name, cvmTag, csTag, vcPolicyTag); + Map tags = StorPoolHelper.addStorPoolTags(name, cvmTag, csTag, vcPolicyTag, null); json.put("tags", tags); return POST("MultiCluster/VolumeCreate", json, conn); } @@ -550,7 +567,7 @@ public class StorPoolUtil { public static SpApiResponse volumeRemoveTags(String name, SpConnectionDesc conn) { Map json = new HashMap<>(); - Map tags = StorPoolHelper.addStorPoolTags(null, "", null, ""); + Map tags = StorPoolHelper.addStorPoolTags(null, "", null, "", null); json.put("tags", tags); return POST("MultiCluster/VolumeUpdate/" + name, json, conn); } @@ -558,7 +575,7 @@ public class StorPoolUtil { public static SpApiResponse volumeUpdateIopsAndTags(final String name, final String uuid, Long iops, SpConnectionDesc conn, String vcPolicy) { Map json = new HashMap<>(); - Map tags = StorPoolHelper.addStorPoolTags(null, uuid, null, vcPolicy); + Map tags = StorPoolHelper.addStorPoolTags(null, uuid, null, vcPolicy, null); json.put("iops", iops); json.put("tags", tags); return POST("MultiCluster/VolumeUpdate/" + name, json, conn); @@ -566,14 +583,14 @@ public class StorPoolUtil { public static SpApiResponse volumeUpdateCvmTags(final String name, final String uuid, SpConnectionDesc conn) { Map json = new HashMap<>(); - Map tags = StorPoolHelper.addStorPoolTags(null, uuid, null, null); + Map tags = StorPoolHelper.addStorPoolTags(null, uuid, null, null, null); json.put("tags", tags); return POST("MultiCluster/VolumeUpdate/" + name, json, conn); } public static SpApiResponse volumeUpdateVCTags(final String name, SpConnectionDesc conn, String vcPolicy) { Map json = new HashMap<>(); - Map tags = StorPoolHelper.addStorPoolTags(null, null, null, vcPolicy); + Map tags = StorPoolHelper.addStorPoolTags(null, null, null, vcPolicy, null); json.put("tags", tags); return POST("MultiCluster/VolumeUpdate/" + name, json, conn); } @@ -584,10 +601,14 @@ public class StorPoolUtil { return POST("MultiCluster/VolumeUpdate/" + name, json, conn); } + public static SpApiResponse volumeUpdate(StorPoolVolumeDef volume, SpConnectionDesc conn) { + return POST("MultiCluster/VolumeUpdate/" + volume.getName(), volume, conn); + } + public static SpApiResponse volumeSnapshot(final String volumeName, final String snapshotName, String vmUuid, String csTag, String vcPolicy, SpConnectionDesc conn) { Map json = new HashMap<>(); - Map tags = StorPoolHelper.addStorPoolTags(snapshotName, vmUuid, csTag, vcPolicy); + Map tags = StorPoolHelper.addStorPoolTags(snapshotName, vmUuid, csTag, vcPolicy, null); json.put("name", ""); json.put("tags", tags); @@ -601,7 +622,7 @@ public class StorPoolUtil { public static SpApiResponse volumesGroupSnapshot(final List volumeTOs, final String vmUuid, final String snapshotName, String csTag, SpConnectionDesc conn) { Map json = new LinkedHashMap<>(); - Map tags = StorPoolHelper.addStorPoolTags(snapshotName, vmUuid, csTag, null); + Map tags = StorPoolHelper.addStorPoolTags(snapshotName, vmUuid, csTag, null, null); List> volumes = new ArrayList<>(); for (VolumeObjectTO volumeTO : volumeTOs) { Map vol = new LinkedHashMap<>(); @@ -612,7 +633,7 @@ public class StorPoolUtil { } json.put("tags", tags); json.put("volumes", volumes); - log.info("json:" + json); + LOGGER.info("json:" + json); return POST("MultiCluster/VolumesGroupSnapshot", json, conn); } @@ -622,6 +643,12 @@ public class StorPoolUtil { return POST("MultiCluster/VolumeRevert/" + name, json, conn); } + /** + * @deprecated Use volumeSnapshot instead + * @param volumeName + * @param conn + * @return + */ public static SpApiResponse volumeFreeze(final String volumeName, SpConnectionDesc conn) { return POST("MultiCluster/VolumeFreeze/" + volumeName, null, conn); } diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/motion/StorPoolDataMotionStrategy.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/motion/StorPoolDataMotionStrategy.java index 6cfa5ec14a2..aa972d44343 100644 --- a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/motion/StorPoolDataMotionStrategy.java +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/motion/StorPoolDataMotionStrategy.java @@ -59,7 +59,8 @@ import org.apache.cloudstack.storage.snapshot.StorPoolConfigurationManager; import org.apache.cloudstack.storage.to.SnapshotObjectTO; import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.commons.collections.MapUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; @@ -99,7 +100,7 @@ import com.cloud.vm.dao.VMInstanceDao; @Component public class StorPoolDataMotionStrategy implements DataMotionStrategy { - private static final Logger log = Logger.getLogger(StorPoolDataMotionStrategy.class); + protected Logger logger = LogManager.getLogger(getClass()); @Inject private SnapshotDataFactory _snapshotDataFactory; @@ -192,7 +193,7 @@ public class StorPoolDataMotionStrategy implements DataMotionStrategy { CopyCmdAnswer answer = null; String err = null; if (res.getError() != null) { - log.debug(String.format("Could not create volume from snapshot with ID=%s", snapshot.getId())); + logger.debug("Could not create volume from snapshot [ID: {}, name: {}]", snapshot.getId(), snapshot.getName()); StorPoolUtil.spLog("Volume create failed with error=%s", res.getError().getDescr()); err = res.getError().getDescr(); } else { @@ -218,24 +219,23 @@ public class StorPoolDataMotionStrategy implements DataMotionStrategy { } else { answer = (CopyCmdAnswer) ep2.sendMessage(backupSnapshot); if (answer != null && answer.getResult()) { - SpApiResponse resSnapshot = StorPoolUtil.volumeFreeze(volumeName, conn); + SpApiResponse resSnapshot = StorPoolUtil.volumeSnapshot(volumeName, template.getUuid(), null, "template", null, conn); if (resSnapshot.getError() != null) { - log.debug(String.format("Could not snapshot volume with ID=%s", snapshot.getId())); - StorPoolUtil.spLog("Volume freeze failed with error=%s", resSnapshot.getError().getDescr()); + logger.debug(String.format("Could not snapshot volume with ID={}", snapshot.getId())); + StorPoolUtil.spLog("VolumeSnapshot failed with error=%s", resSnapshot.getError().getDescr()); err = resSnapshot.getError().getDescr(); - StorPoolUtil.volumeDelete(volumeName, conn); } else { + String templPath = StorPoolUtil.devPath( + StorPoolUtil.getSnapshotNameFromResponse(resSnapshot, false, StorPoolUtil.GLOBAL_ID)); StorPoolHelper.updateVmStoreTemplate(template.getId(), template.getDataStore().getRole(), - StorPoolUtil.devPath(StorPoolUtil.getNameFromResponse(res, false)), _templStoreDao); + templPath, _templStoreDao); } - } else { - err = "Could not copy template to secondary " + answer.getResult(); - StorPoolUtil.volumeDelete(StorPoolUtil.getNameFromResponse(res, true), conn); } } } catch (CloudRuntimeException e) { err = e.getMessage(); } + StorPoolUtil.volumeDelete(volumeName, conn); } _vmTemplateDetailsDao.persist(new VMTemplateDetailVO(template.getId(), StorPoolUtil.SP_STORAGE_POOL_ID, String.valueOf(vInfo.getDataStore().getId()), false)); @@ -296,7 +296,7 @@ public class StorPoolDataMotionStrategy implements DataMotionStrategy { for (Map.Entry entry : volumeDataStoreMap.entrySet()) { VolumeInfo srcVolumeInfo = entry.getKey(); if (srcVolumeInfo.getPassphraseId() != null) { - throw new CloudRuntimeException(String.format("Cannot live migrate encrypted volume [%s] to StorPool", srcVolumeInfo.getName())); + throw new CloudRuntimeException(String.format("Cannot live migrate encrypted volume [%s] to StorPool", srcVolumeInfo.getVolume())); } DataStore destDataStore = entry.getValue(); @@ -387,8 +387,8 @@ public class StorPoolDataMotionStrategy implements DataMotionStrategy { errMsg = String.format( "Copy volume(s) of VM [%s] to storage(s) [%s] and VM to host [%s] failed in StorPoolDataMotionStrategy.copyAsync. Error message: [%s].", - vmTO.getId(), srcHost.getId(), destHost.getId(), ex.getMessage()); - log.error(errMsg, ex); + vmTO, srcHost, destHost, ex.getMessage()); + logger.error(errMsg, ex); throw new CloudRuntimeException(errMsg); } finally { @@ -444,7 +444,7 @@ public class StorPoolDataMotionStrategy implements DataMotionStrategy { throw new AgentUnavailableException(msg, destHost.getId()); } } catch (Exception e) { - log.debug("Failed to disconnect one or more (original) dest volumes", e); + logger.debug("Failed to disconnect one or more (original) dest volumes", e); } } @@ -472,10 +472,10 @@ public class StorPoolDataMotionStrategy implements DataMotionStrategy { AsyncCallFuture destroyFuture = _volumeService.expungeVolumeAsync(srcVolumeInfo); if (destroyFuture.get().isFailed()) { - log.debug("Failed to clean up source volume on storage"); + logger.debug("Failed to clean up source volume on storage"); } } catch (Exception e) { - log.debug("Failed to clean up source volume on storage", e); + logger.debug("Failed to clean up source volume on storage", e); } // Update the volume ID for snapshots on secondary storage @@ -487,13 +487,13 @@ public class StorPoolDataMotionStrategy implements DataMotionStrategy { try { disconnectHostFromVolume(destHost, destVolumeInfo.getPoolId(), destVolumeInfo.getPath()); } catch (Exception e) { - log.debug("Failed to disconnect (new) dest volume", e); + logger.debug("Failed to disconnect (new) dest volume", e); } try { _volumeService.revokeAccess(destVolumeInfo, destHost, destVolumeInfo.getDataStore()); } catch (Exception e) { - log.debug("Failed to revoke access from dest volume", e); + logger.debug("Failed to revoke access from dest volume", e); } destVolumeInfo.processEvent(Event.OperationFailed); @@ -507,10 +507,10 @@ public class StorPoolDataMotionStrategy implements DataMotionStrategy { AsyncCallFuture destroyFuture = _volumeService.expungeVolumeAsync(destVolumeInfo); if (destroyFuture.get().isFailed()) { - log.debug("Failed to clean up dest volume on storage"); + logger.debug("Failed to clean up dest volume on storage"); } } catch (Exception e) { - log.debug("Failed to clean up dest volume on storage", e); + logger.debug("Failed to clean up dest volume on storage", e); } } } @@ -523,13 +523,13 @@ public class StorPoolDataMotionStrategy implements DataMotionStrategy { private String connectHostToVolume(Host host, long storagePoolId, String iqn) { ModifyTargetsCommand modifyTargetsCommand = getModifyTargetsCommand(storagePoolId, iqn, true); - return sendModifyTargetsCommand(modifyTargetsCommand, host.getId()).get(0); + return sendModifyTargetsCommand(modifyTargetsCommand, host).get(0); } private void disconnectHostFromVolume(Host host, long storagePoolId, String iqn) { ModifyTargetsCommand modifyTargetsCommand = getModifyTargetsCommand(storagePoolId, iqn, false); - sendModifyTargetsCommand(modifyTargetsCommand, host.getId()); + sendModifyTargetsCommand(modifyTargetsCommand, host); } private ModifyTargetsCommand getModifyTargetsCommand(long storagePoolId, String iqn, boolean add) { @@ -557,15 +557,15 @@ public class StorPoolDataMotionStrategy implements DataMotionStrategy { return cmd; } - private List sendModifyTargetsCommand(ModifyTargetsCommand cmd, long hostId) { - ModifyTargetsAnswer modifyTargetsAnswer = (ModifyTargetsAnswer) _agentManager.easySend(hostId, cmd); + private List sendModifyTargetsCommand(ModifyTargetsCommand cmd, Host host) { + ModifyTargetsAnswer modifyTargetsAnswer = (ModifyTargetsAnswer) _agentManager.easySend(host.getId(), cmd); if (modifyTargetsAnswer == null) { throw new CloudRuntimeException("Unable to get an answer to the modify targets command"); } if (!modifyTargetsAnswer.getResult()) { - String msg = "Unable to modify targets on the following host: " + hostId; + String msg = String.format("Unable to modify targets on the following host: %s", host); throw new CloudRuntimeException(msg); } diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/snapshot/StorPoolSnapshotStrategy.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/snapshot/StorPoolSnapshotStrategy.java index 23361bd1e5e..5ec86df91e1 100644 --- a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/snapshot/StorPoolSnapshotStrategy.java +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/snapshot/StorPoolSnapshotStrategy.java @@ -16,10 +16,19 @@ // under the License. package org.apache.cloudstack.storage.snapshot; -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.hypervisor.kvm.storage.StorPoolStorageAdaptor; +import com.cloud.storage.DataStoreRole; +import com.cloud.storage.Snapshot; +import com.cloud.storage.SnapshotVO; +import com.cloud.storage.VolumeVO; +import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotDetailsDao; +import com.cloud.storage.dao.SnapshotDetailsVO; +import com.cloud.storage.dao.SnapshotZoneDao; +import com.cloud.storage.dao.VolumeDao; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.fsm.NoTransitionException; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; @@ -40,27 +49,18 @@ import org.apache.cloudstack.storage.datastore.util.StorPoolUtil; import org.apache.cloudstack.storage.datastore.util.StorPoolUtil.SpApiResponse; import org.apache.cloudstack.storage.datastore.util.StorPoolUtil.SpConnectionDesc; import org.apache.commons.collections.CollectionUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.hypervisor.kvm.storage.StorPoolStorageAdaptor; -import com.cloud.storage.DataStoreRole; -import com.cloud.storage.Snapshot; -import com.cloud.storage.SnapshotVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.SnapshotDetailsDao; -import com.cloud.storage.dao.SnapshotDetailsVO; -import com.cloud.storage.dao.SnapshotZoneDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.fsm.NoTransitionException; +import javax.inject.Inject; +import java.util.ArrayList; +import java.util.List; @Component public class StorPoolSnapshotStrategy implements SnapshotStrategy { - private static final Logger log = Logger.getLogger(StorPoolSnapshotStrategy.class); + protected Logger logger = LogManager.getLogger(getClass()); @Inject private SnapshotDao _snapshotDao; @@ -90,11 +90,11 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { snapshotObj.processEvent(Snapshot.Event.BackupToSecondary); snapshotObj.processEvent(Snapshot.Event.OperationSucceeded); } catch (NoTransitionException ex) { - log.debug("Failed to change state: " + ex.toString()); + logger.debug("Failed to change state: " + ex.toString()); try { snapshotObj.processEvent(Snapshot.Event.OperationFailed); } catch (NoTransitionException ex2) { - log.debug("Failed to change state: " + ex2.toString()); + logger.debug("Failed to change state: " + ex2.toString()); } } return snapshotInfo; @@ -116,11 +116,12 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { if (resp.getError() != null) { final String err = String.format("Failed to clean-up Storpool snapshot %s. Error: %s", name, resp.getError()); StorPoolUtil.spLog(err); - markSnapshotAsDestroyedIfAlreadyRemoved(snapshotId, resp); + markSnapshotAsDestroyedIfAlreadyRemoved(snapshotId, resp.getError().getName().equals(StorPoolUtil.OBJECT_DOES_NOT_EXIST)); throw new CloudRuntimeException(err); } else { res = deleteSnapshotFromDbIfNeeded(snapshotVO, zoneId); - StorPoolUtil.spLog("StorpoolSnapshotStrategy.deleteSnapshot: executed successfully=%s, snapshot uuid=%s, name=%s", res, snapshotVO.getUuid(), name); + markSnapshotAsDestroyedIfAlreadyRemoved(snapshotId,true); + StorPoolUtil.spLog("StorpoolSnapshotStrategy.deleteSnapshot: executed successfully=%s, snapshot %s, name=%s", res, snapshotVO, name); } } catch (Exception e) { String errMsg = String.format("Cannot delete snapshot due to %s", e.getMessage()); @@ -128,22 +129,30 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { } } + List snapshots = _snapshotStoreDao.listBySnapshotIdAndState(snapshotId, State.Ready); + if (res || CollectionUtils.isEmpty(snapshots)) { + updateSnapshotToDestroyed(snapshotVO); + return true; + } return res; } - private void markSnapshotAsDestroyedIfAlreadyRemoved(Long snapshotId, SpApiResponse resp) { - if (resp.getError().getName().equals("objectDoesNotExist")) { - SnapshotDataStoreVO snapshotOnPrimary = _snapshotStoreDao.findBySourceSnapshot(snapshotId, DataStoreRole.Primary); - if (snapshotOnPrimary != null) { - snapshotOnPrimary.setState(State.Destroyed); - _snapshotStoreDao.update(snapshotOnPrimary.getId(), snapshotOnPrimary); + private void markSnapshotAsDestroyedIfAlreadyRemoved(Long snapshotId, boolean isSnapshotDeleted) { + if (!isSnapshotDeleted) { + return; + } + List snapshotsOnStore = _snapshotStoreDao.listBySnapshotIdAndState(snapshotId, State.Ready); + for (SnapshotDataStoreVO snapshot : snapshotsOnStore) { + if (snapshot.getInstallPath() != null && snapshot.getInstallPath().contains(StorPoolUtil.SP_DEV_PATH)) { + snapshot.setState(State.Destroyed); + _snapshotStoreDao.update(snapshot.getId(), snapshot); } } } @Override public StrategyPriority canHandle(Snapshot snapshot, Long zoneId, SnapshotOperation op) { - log.debug(String.format("StorpoolSnapshotStrategy.canHandle: snapshot=%s, uuid=%s, op=%s", snapshot.getName(), snapshot.getUuid(), op)); + logger.debug("StorpoolSnapshotStrategy.canHandle: snapshot {}, op={}", snapshot, op); if (op != SnapshotOperation.DELETE) { return StrategyPriority.CANT_HANDLE; @@ -172,7 +181,7 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { } private boolean deleteSnapshotChain(SnapshotInfo snapshot) { - log.debug("delete snapshot chain for snapshot: " + snapshot.getId()); + logger.debug("delete snapshot chain for snapshot: {}", snapshot); final SnapshotInfo snapOnImage = snapshot; boolean result = false; boolean resultIsSet = false; @@ -182,15 +191,15 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { SnapshotInfo child = snapshot.getChild(); if (child != null) { - log.debug("the snapshot has child, can't delete it on the storage"); + logger.debug("the snapshot has child, can't delete it on the storage"); break; } - log.debug("Snapshot: " + snapshot.getId() + " doesn't have children, so it's ok to delete it and its parents"); + logger.debug("Snapshot: {} doesn't have children, so it's ok to delete it and its parents", snapshot); SnapshotInfo parent = snapshot.getParent(); boolean deleted = false; if (parent != null) { if (parent.getPath() != null && parent.getPath().equalsIgnoreCase(snapshot.getPath())) { - log.debug("for empty delta snapshot, only mark it as destroyed in db"); + logger.debug("for empty delta snapshot, only mark it as destroyed in db"); snapshot.processEvent(Event.DestroyRequested); snapshot.processEvent(Event.OperationSuccessed); deleted = true; @@ -207,7 +216,7 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { if (r) { List cacheSnaps = snapshotDataFactory.listSnapshotOnCache(snapshot.getId()); for (SnapshotInfo cacheSnap : cacheSnaps) { - log.debug("Delete snapshot " + snapshot.getId() + " from image cache store: " + cacheSnap.getDataStore().getName()); + logger.debug("Delete snapshot {} from image cache store: {}", snapshot, cacheSnap.getDataStore()); cacheSnap.delete(); } } @@ -216,7 +225,7 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { resultIsSet = true; } } catch (Exception e) { - log.debug("Failed to delete snapshot on storage. ", e); + logger.debug("Failed to delete snapshot on storage. ", e); } } } else { @@ -225,7 +234,7 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { snapshot = parent; } } catch (Exception e) { - log.debug("delete snapshot failed: ", e); + logger.debug("delete snapshot failed: ", e); } return result; } @@ -247,7 +256,7 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { obj.processEvent(Snapshot.Event.DestroyRequested); } } catch (NoTransitionException e) { - log.debug("Failed to set the state to destroying: ", e); + logger.debug("Failed to set the state to destroying: ", e); return false; } @@ -265,13 +274,13 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { } } } catch (Exception e) { - log.debug("Failed to delete snapshot: ", e); + logger.debug("Failed to delete snapshot: ", e); try { if (areLastSnapshotRef) { obj.processEvent(Snapshot.Event.OperationFailed); } } catch (NoTransitionException e1) { - log.debug("Failed to change snapshot state: " + e.toString()); + logger.debug("Failed to change snapshot state: " + e.toString()); } return false; } @@ -326,7 +335,7 @@ public class StorPoolSnapshotStrategy implements SnapshotStrategy { if (!Snapshot.State.BackedUp.equals(snapshotVO.getState()) && !Snapshot.State.Error.equals(snapshotVO.getState()) && !Snapshot.State.Destroying.equals(snapshotVO.getState())) { - throw new InvalidParameterValueException("Can't delete snapshot " + snapshotId + " due to it is in " + snapshotVO.getState() + " Status"); + throw new InvalidParameterValueException(String.format("Can't delete snapshot %s due to it is in %s Status", snapshotVO, snapshotVO.getState())); } List storeRefs = _snapshotStoreDao.listReadyBySnapshot(snapshotId, DataStoreRole.Image); if (zoneId != null) { diff --git a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/snapshot/StorPoolVMSnapshotStrategy.java b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/snapshot/StorPoolVMSnapshotStrategy.java index 489f64f9025..e5b24a3f98c 100644 --- a/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/snapshot/StorPoolVMSnapshotStrategy.java +++ b/plugins/storage/volume/storpool/src/main/java/org/apache/cloudstack/storage/snapshot/StorPoolVMSnapshotStrategy.java @@ -36,7 +36,6 @@ import org.apache.cloudstack.storage.datastore.util.StorPoolUtil.SpConnectionDes import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.storage.vmsnapshot.DefaultVMSnapshotStrategy; import org.apache.cloudstack.storage.vmsnapshot.VMSnapshotHelper; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.agent.api.VMSnapshotTO; @@ -66,7 +65,6 @@ import com.google.gson.JsonObject; @Component public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { - private static final Logger log = Logger.getLogger(StorPoolVMSnapshotStrategy.class); @Inject private VMSnapshotHelper vmSnapshotHelper; @@ -94,7 +92,7 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { @Override public VMSnapshot takeVMSnapshot(VMSnapshot vmSnapshot) { - log.info("KVMVMSnapshotStrategy take snapshot"); + logger.info("KVMVMSnapshotStrategy take snapshot"); UserVm userVm = userVmDao.findById(vmSnapshot.getVmId()); VMSnapshotVO vmSnapshotVO = (VMSnapshotVO) vmSnapshot; @@ -150,7 +148,7 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { vmSnapshot.getId(), StorPoolUtil.SP_STORAGE_POOL_ID, String.valueOf(poolId), false); vmSnapshotDetailsDao.persist(vmSnapshotDetailStoragePoolId); } - StorPoolUtil.spLog("Snapshot=%s of volume=%s for a group snapshot=%s.", snapshot, vol.getUuid(), vmSnapshot.getUuid()); + StorPoolUtil.spLog("Snapshot=%s of volume=%s for a group snapshot=%s.", snapshot, vol, vmSnapshot); } } } @@ -163,7 +161,7 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { for (VolumeObjectTO volumeObjectTO : volumeTOs) { publishUsageEvents(EventTypes.EVENT_VM_SNAPSHOT_CREATE, vmSnapshot, userVm, volumeObjectTO); new_chain_size += volumeObjectTO.getSize(); - log.info("EventTypes.EVENT_VM_SNAPSHOT_CREATE publishUsageEvent" + volumeObjectTO); + logger.info("EventTypes.EVENT_VM_SNAPSHOT_CREATE publishUsageEvent" + volumeObjectTO); } publishUsageEvents(EventTypes.EVENT_VM_SNAPSHOT_ON_PRIMARY, vmSnapshot, userVm, new_chain_size - prev_chain_size, virtual_size); } else { @@ -171,15 +169,15 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { } return vmSnapshot; } catch (Exception e) { - log.debug("Could not create VM snapshot:" + e.getMessage()); + logger.debug("Could not create VM snapshot:" + e.getMessage()); throw new CloudRuntimeException("Could not create VM snapshot:" + e.getMessage()); } finally { if (!result) { try { vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationFailed); - log.info(String.format("VMSnapshot.Event.OperationFailed vmSnapshot=%s", vmSnapshot)); + logger.info(String.format("VMSnapshot.Event.OperationFailed vmSnapshot=%s", vmSnapshot)); } catch (NoTransitionException nte) { - log.error("Cannot set vm state:" + nte.getMessage()); + logger.error("Cannot set vm state:" + nte.getMessage()); } } } @@ -219,7 +217,7 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { try { vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.ExpungeRequested); } catch (NoTransitionException e) { - log.debug("Failed to change vm snapshot state with event ExpungeRequested"); + logger.debug("Failed to change vm snapshot state with event ExpungeRequested"); throw new CloudRuntimeException( "Failed to change vm snapshot state with event ExpungeRequested: " + e.getMessage()); } @@ -239,15 +237,15 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { VMSnapshotDetailsVO snapshotDetailsVO = vmSnapshotDetailsDao.findDetail(vmSnapshot.getId(), volumeObjectTO.getUuid()); String snapshotName = StorPoolStorageAdaptor.getVolumeNameFromPath(snapshotDetailsVO.getValue(), true); if (snapshotName == null) { - err = String.format("Could not find StorPool's snapshot vm snapshot uuid=%s and volume uui=%s", - vmSnapshot.getUuid(), volumeObjectTO.getUuid()); - log.error("Could not delete snapshot for vm:" + err); + err = String.format("Could not find StorPool's snapshot vm snapshot %s and volume [id: %s, uuid: %s, name: %s]", + vmSnapshot, volumeObjectTO.getId(), volumeObjectTO.getUuid(), volumeObjectTO.getName()); + logger.error("Could not delete snapshot for vm:" + err); } StorPoolUtil.spLog("StorpoolVMSnapshotStrategy.deleteVMSnapshot snapshotName=%s", snapshotName); resp = StorPoolUtil.snapshotDelete(snapshotName, conn); if (resp.getError() != null) { err = String.format("Could not delete storpool vm error=%s", resp.getError()); - log.error("Could not delete snapshot for vm:" + err); + logger.error("Could not delete snapshot for vm:" + err); } else { // do we need to clean database? if (snapshotDetailsVO != null) { @@ -256,10 +254,9 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { } if (err != null) { StorPoolUtil.spLog( - "StorpoolVMSnapshotStrategy.deleteVMSnapshot delete snapshot=%s of gropusnapshot=%s failed due to %s", - snapshotName, userVm.getInstanceName(), err); - throw new CloudRuntimeException("Delete vm snapshot " + vmSnapshot.getName() + " of vm " - + userVm.getInstanceName() + " failed due to " + err); + "StorpoolVMSnapshotStrategy.deleteVMSnapshot delete snapshot=%s of group snapshot=%s failed due to %s", + snapshotName, userVm, err); + throw new CloudRuntimeException(String.format("Delete vm snapshot %s of vm %s failed due to %s", vmSnapshot, userVm, err)); } } vmSnapshotDetailsDao.removeDetails(vmSnapshot.getId()); @@ -278,7 +275,7 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { @Override public boolean revertVMSnapshot(VMSnapshot vmSnapshot) { - log.debug("Revert vm snapshot"); + logger.debug("Revert vm snapshot"); VMSnapshotVO vmSnapshotVO = (VMSnapshotVO) vmSnapshot; UserVmVO userVm = userVmDao.findById(vmSnapshot.getVmId()); @@ -306,7 +303,7 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { if (snapshotName == null) { err = String.format("Could not find StorPool's snapshot vm snapshot uuid=%s and volume uui=%s", vmSnapshot.getUuid(), volumeObjectTO.getUuid()); - log.error("Could not delete snapshot for vm:" + err); + logger.error("Could not delete snapshot for vm:" + err); } String volumeName = StorPoolStorageAdaptor.getVolumeNameFromPath(volumeObjectTO.getPath(), true); VolumeDetailVO detail = volumeDetailsDao.findDetail(volumeObjectTO.getId(), StorPoolUtil.SP_PROVIDER_NAME); @@ -346,15 +343,15 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { finalizeRevert(vmSnapshotVO, volumeTOs); result = vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded); } catch (CloudRuntimeException | NoTransitionException e) { - String errMsg = String.format("Error while finalize create vm snapshot [%s] due to %s", vmSnapshot.getName(), e.getMessage()); - log.error(errMsg, e); + String errMsg = String.format("Error while finalize create vm snapshot [%s] due to %s", vmSnapshot, e.getMessage()); + logger.error(errMsg, e); throw new CloudRuntimeException(errMsg); } finally { if (!result) { try { vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationFailed); } catch (NoTransitionException e1) { - log.error("Cannot set vm snapshot state due to: " + e1.getMessage()); + logger.error("Cannot set vm snapshot state due to: " + e1.getMessage()); } } } @@ -381,7 +378,7 @@ public class StorPoolVMSnapshotStrategy extends DefaultVMSnapshotStrategy { vmSnapshot.getName(), 0L, 0L, vmSnapSize, virtualSize, VMSnapshot.class.getName(), vmSnapshot.getUuid()); } catch (Exception e) { - log.error("Failed to publis usage event " + type, e); + logger.error("Failed to publis usage event " + type, e); } } } diff --git a/plugins/storage/volume/storpool/src/main/resources/META-INF/cloudstack/storage-volume-storpool/spring-storage-volume-storpool-context.xml b/plugins/storage/volume/storpool/src/main/resources/META-INF/cloudstack/storage-volume-storpool/spring-storage-volume-storpool-context.xml index 6451fc8fd39..b4e81f166f0 100644 --- a/plugins/storage/volume/storpool/src/main/resources/META-INF/cloudstack/storage-volume-storpool/spring-storage-volume-storpool-context.xml +++ b/plugins/storage/volume/storpool/src/main/resources/META-INF/cloudstack/storage-volume-storpool/spring-storage-volume-storpool-context.xml @@ -1,12 +1,12 @@ - org.apache.cloudstack cloudstack-plugins - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT ../../pom.xml 2.0.0.AM25 - 1.5 1.3.2 1.1.3 1.1-groovy-2.4 @@ -41,18 +40,21 @@ - org.codehaus.gmaven - gmaven-plugin - ${gmaven.version} - - 1.7 - - + org.codehaus.gmavenplus + gmavenplus-plugin + ${cs.gmavenplus.version} + + + org.codehaus.groovy + groovy-all + ${cs.groovy.version} + + compile - testCompile + compileTests @@ -66,29 +68,12 @@ - - - org.codehaus.gmaven.runtime - gmaven-runtime-1.7 - ${gmaven.version} - - - org.codehaus.groovy - groovy-all - - - - - org.codehaus.groovy - groovy-all - ${cs.groovy.version} - - org.apache.maven.plugins maven-surefire-plugin + @{argLine} --add-exports=java.naming/com.sun.jndi.ldap=ALL-UNNAMED **/*Spec.groovy **/*Test.java @@ -162,7 +147,7 @@ net.bytebuddy byte-buddy - 1.10.5 + 1.14.5 junit diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LDAPConfigCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LDAPConfigCmd.java index 2a643dda76f..f738a870053 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LDAPConfigCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LDAPConfigCmd.java @@ -22,7 +22,6 @@ import java.util.List; import javax.inject.Inject; import org.apache.commons.lang.StringEscapeUtils; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -53,7 +52,6 @@ import com.cloud.utils.Pair; requestHasSensitiveInfo = true, responseHasSensitiveInfo = false) public class LDAPConfigCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(LDAPConfigCmd.class.getName()); @Inject diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LDAPRemoveCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LDAPRemoveCmd.java index b915f97fe08..c70f84ffd69 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LDAPRemoveCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LDAPRemoveCmd.java @@ -26,7 +26,6 @@ import org.apache.cloudstack.api.response.LDAPConfigResponse; import org.apache.cloudstack.api.response.LDAPRemoveResponse; import org.apache.cloudstack.ldap.LdapConfigurationVO; import org.apache.cloudstack.ldap.LdapManager; -import org.apache.log4j.Logger; import com.cloud.user.Account; import com.cloud.utils.Pair; @@ -38,7 +37,6 @@ import com.cloud.utils.Pair; @APICommand(name = "ldapRemove", description = "(Deprecated , use deleteLdapConfiguration) Remove the LDAP context for this site.", responseObject = LDAPConfigResponse.class, since = "3.0.1", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class LDAPRemoveCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(LDAPRemoveCmd.class.getName()); @Inject private LdapManager _ldapManager; diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapAddConfigurationCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapAddConfigurationCmd.java index 7c592888364..1131667d98a 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapAddConfigurationCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapAddConfigurationCmd.java @@ -20,7 +20,6 @@ import javax.inject.Inject; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.response.DomainResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiErrorCode; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "addLdapConfiguration", description = "Add a new Ldap Configuration", responseObject = LdapConfigurationResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class LdapAddConfigurationCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(LdapAddConfigurationCmd.class.getName()); private static final String s_name = "ldapconfigurationresponse"; @Inject diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapCreateAccountCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapCreateAccountCmd.java index 2196aa8d4f5..880ecea4d13 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapCreateAccountCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapCreateAccountCmd.java @@ -36,7 +36,6 @@ import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.ldap.LdapManager; import org.apache.cloudstack.ldap.LdapUser; import org.apache.cloudstack.ldap.NoLdapUserMatchingQueryException; -import org.apache.log4j.Logger; import org.bouncycastle.util.encoders.Base64; import javax.inject.Inject; @@ -47,7 +46,6 @@ import java.util.Map; @APICommand(name = "ldapCreateAccount", description = "Creates an account from an LDAP user", responseObject = AccountResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class LdapCreateAccountCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(LdapCreateAccountCmd.class.getName()); private static final String s_name = "createaccountresponse"; @Inject diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapDeleteConfigurationCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapDeleteConfigurationCmd.java index 3ffebecfb95..15e6c836d0d 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapDeleteConfigurationCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapDeleteConfigurationCmd.java @@ -20,7 +20,6 @@ import javax.inject.Inject; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.response.DomainResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiErrorCode; @@ -36,7 +35,6 @@ import com.cloud.user.Account; @APICommand(name = "deleteLdapConfiguration", description = "Remove an Ldap Configuration", responseObject = LdapConfigurationResponse.class, since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class LdapDeleteConfigurationCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(LdapDeleteConfigurationCmd.class.getName()); private static final String s_name = "ldapconfigurationresponse"; @Inject diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapImportUsersCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapImportUsersCmd.java index 96696d561cd..eada5f6df39 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapImportUsersCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapImportUsersCmd.java @@ -42,7 +42,6 @@ import org.apache.cloudstack.ldap.LdapManager; import org.apache.cloudstack.ldap.LdapUser; import org.apache.cloudstack.ldap.NoLdapUserMatchingQueryException; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.bouncycastle.util.encoders.Base64; import com.cloud.domain.Domain; @@ -61,7 +60,6 @@ import com.cloud.user.UserAccount; @APICommand(name = "importLdapUsers", description = "Import LDAP users", responseObject = LdapUserResponse.class, since = "4.3.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class LdapImportUsersCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(LdapImportUsersCmd.class.getName()); private static final String s_name = "ldapuserresponse"; @@ -108,18 +106,18 @@ public class LdapImportUsersCmd extends BaseListCmd { private void createCloudstackUserAccount(LdapUser user, String accountName, Domain domain) { Account account = _accountService.getActiveAccountByName(accountName, domain.getId()); if (account == null) { - s_logger.debug("No account exists with name: " + accountName + " creating the account and an user with name: " + user.getUsername() + " in the account"); + logger.debug("No account exists with name: " + accountName + " creating the account and an user with name: " + user.getUsername() + " in the account"); _accountService.createUserAccount(user.getUsername(), generatePassword(), user.getFirstname(), user.getLastname(), user.getEmail(), timezone, accountName, getAccountType(), getRoleId(), domain.getId(), domain.getNetworkDomain(), details, UUID.randomUUID().toString(), UUID.randomUUID().toString(), User.Source.LDAP); } else { // check if the user exists. if yes, call update UserAccount csuser = _accountService.getActiveUserAccount(user.getUsername(), domain.getId()); if (csuser == null) { - s_logger.debug("No user exists with name: " + user.getUsername() + " creating a user in the account: " + accountName); + logger.debug("No user exists with name: " + user.getUsername() + " creating a user in the account: " + accountName); _accountService.createUser(user.getUsername(), generatePassword(), user.getFirstname(), user.getLastname(), user.getEmail(), timezone, accountName, domain.getId(), UUID.randomUUID().toString(), User.Source.LDAP); } else { - s_logger.debug("Account [name=%s] and user [name=%s] already exist in CloudStack. Executing the user update."); + logger.debug("Account [name={}] and user [name={}] already exist in CloudStack. Executing the user update.", account, csuser); UpdateUserCmd updateUserCmd = new UpdateUserCmd(); updateUserCmd.setId(csuser.getId()); @@ -148,7 +146,7 @@ public class LdapImportUsersCmd extends BaseListCmd { } } catch (NoLdapUserMatchingQueryException ex) { users = new ArrayList(); - s_logger.info("No Ldap user matching query. " + " ::: " + ex.getMessage()); + logger.info("No Ldap user matching query. " + " ::: " + ex.getMessage()); } List addedUsers = new ArrayList(); @@ -158,7 +156,7 @@ public class LdapImportUsersCmd extends BaseListCmd { createCloudstackUserAccount(user, getAccountName(user), domain); addedUsers.add(user); } catch (InvalidParameterValueException ex) { - s_logger.error("Failed to create user with username: " + user.getUsername() + " ::: " + ex.getMessage()); + logger.error("Failed to create user with username: " + user.getUsername() + " ::: " + ex.getMessage()); } } ListResponse response = new ListResponse(); diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapListConfigurationCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapListConfigurationCmd.java index d12ca4ab6c1..c34d026f89b 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapListConfigurationCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapListConfigurationCmd.java @@ -23,7 +23,6 @@ import javax.inject.Inject; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.response.DomainResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseListCmd; @@ -39,7 +38,6 @@ import com.cloud.utils.Pair; @APICommand(name = "listLdapConfigurations", responseObject = LdapConfigurationResponse.class, description = "Lists all LDAP configurations", since = "4.2.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class LdapListConfigurationCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(LdapListConfigurationCmd.class.getName()); private static final String s_name = "ldapconfigurationresponse"; diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapListUsersCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapListUsersCmd.java index 0c70c4d5b30..6bfc70ea139 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapListUsersCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapListUsersCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseListCmd; @@ -79,7 +78,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin,RoleType.DomainAdmin}) public class LdapListUsersCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(LdapListUsersCmd.class.getName()); private static final String s_name = "ldapuserresponse"; @Inject private LdapManager _ldapManager; @@ -142,10 +140,11 @@ public class LdapListUsersCmd extends BaseListCmd { try { final List users = _ldapManager.getUsers(domainId); ldapResponses = createLdapUserResponse(users); -// now filter and annotate + // now filter and annotate ldapResponses = applyUserFilter(ldapResponses); } catch (final NoLdapUserMatchingQueryException ex) { - // ok, we'll make do with the empty list ldapResponses = new ArrayList(); + logger.debug(ex.getMessage()); + // ok, we'll make do with the empty list } finally { response.setResponses(ldapResponses); response.setResponseName(getCommandName()); @@ -169,7 +168,7 @@ public class LdapListUsersCmd extends BaseListCmd { } private void traceUserList() { - if(s_logger.isTraceEnabled()) { + if(logger.isTraceEnabled()) { StringBuilder users = new StringBuilder(); for (UserResponse user : cloudstackUsers) { if (users.length()> 0) { @@ -178,13 +177,13 @@ public class LdapListUsersCmd extends BaseListCmd { users.append(user.getUsername()); } - s_logger.trace(String.format("checking against %d cloudstackusers: %s.", this.cloudstackUsers.size(), users.toString())); + logger.trace(String.format("checking against %d cloudstackusers: %s.", this.cloudstackUsers.size(), users.toString())); } } private List applyUserFilter(List ldapResponses) { - if(s_logger.isTraceEnabled()) { - s_logger.trace(String.format("applying filter: %s or %s.", this.getListTypeString(), this.getUserFilter())); + if(logger.isTraceEnabled()) { + logger.trace(String.format("applying filter: %s or %s.", this.getListTypeString(), this.getUserFilter())); } List responseList = getUserFilter().filter(this,ldapResponses); return responseList; @@ -218,14 +217,14 @@ public class LdapListUsersCmd extends BaseListCmd { if (cloudstackUsers != null) { for (final UserResponse cloudstackUser : cloudstackUsers) { if (ldapUser.getUsername().equals(cloudstackUser.getUsername())) { - if(s_logger.isTraceEnabled()) { - s_logger.trace(String.format("found user %s in cloudstack", ldapUser.getUsername())); + if(logger.isTraceEnabled()) { + logger.trace(String.format("found user %s in cloudstack", ldapUser.getUsername())); } rc = true; } else { - if(s_logger.isTraceEnabled()) { - s_logger.trace(String.format("ldap user %s does not match cloudstack user %s", ldapUser.getUsername(), cloudstackUser.getUsername())); + if(logger.isTraceEnabled()) { + logger.trace(String.format("ldap user %s does not match cloudstack user %s", ldapUser.getUsername(), cloudstackUser.getUsername())); } } } @@ -234,20 +233,20 @@ public class LdapListUsersCmd extends BaseListCmd { } boolean isACloudstackUser(final LdapUserResponse ldapUser) { - if(s_logger.isTraceEnabled()) { - s_logger.trace("checking response : " + ldapUser.toString()); + if(logger.isTraceEnabled()) { + logger.trace("checking response : " + ldapUser.toString()); } final List cloudstackUsers = getCloudstackUsers(); if (cloudstackUsers != null && cloudstackUsers.size() != 0) { for (final UserResponse cloudstackUser : cloudstackUsers) { if (ldapUser.getUsername().equals(cloudstackUser.getUsername())) { - if(s_logger.isTraceEnabled()) { - s_logger.trace(String.format("found user %s in cloudstack user %s", ldapUser.getUsername(), cloudstackUser.getUsername())); + if(logger.isTraceEnabled()) { + logger.trace(String.format("found user %s in cloudstack user %s", ldapUser.getUsername(), cloudstackUser.getUsername())); } return true; } else { - if(s_logger.isTraceEnabled()) { - s_logger.trace(String.format("ldap user %s does not match cloudstack user %s", ldapUser.getUsername(), cloudstackUser.getUsername())); + if(logger.isTraceEnabled()) { + logger.trace(String.format("ldap user %s does not match cloudstack user %s", ldapUser.getUsername(), cloudstackUser.getUsername())); } } } @@ -348,8 +347,8 @@ public class LdapListUsersCmd extends BaseListCmd { * @return unfiltered list of the input list of ldap users */ public List filterNoFilter(List input) { - if(s_logger.isTraceEnabled()) { - s_logger.trace("returning unfiltered list of ldap users"); + if(logger.isTraceEnabled()) { + logger.trace("returning unfiltered list of ldap users"); } annotateUserListWithSources(input); return input; @@ -361,8 +360,8 @@ public class LdapListUsersCmd extends BaseListCmd { * @return a list of ldap users not already in ACS */ public List filterAnyDomain(List input) { - if(s_logger.isTraceEnabled()) { - s_logger.trace("filtering existing users"); + if(logger.isTraceEnabled()) { + logger.trace("filtering existing users"); } final List ldapResponses = new ArrayList(); for (final LdapUserResponse user : input) { @@ -394,8 +393,8 @@ public class LdapListUsersCmd extends BaseListCmd { * @return a list of ldap users not already in ACS */ public List filterLocalDomain(List input) { - if(s_logger.isTraceEnabled()) { - s_logger.trace("filtering local domain users"); + if(logger.isTraceEnabled()) { + logger.trace("filtering local domain users"); } final List ldapResponses = new ArrayList(); String domainId = getCurrentDomainId(); @@ -430,8 +429,8 @@ public class LdapListUsersCmd extends BaseListCmd { * @return annotated list of the users of the input list, that will be automatically imported or synchronised */ public List filterPotentialImport(List input) { - if(s_logger.isTraceEnabled()) { - s_logger.trace("should be filtering potential imports!!!"); + if(logger.isTraceEnabled()) { + logger.trace("should be filtering potential imports!!!"); } // functional possibility do not add only users not yet in cloudstack but include users that would be moved if they are so in ldap? // this means if they are part of a account linked to an ldap group/ou diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapUserSearchCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapUserSearchCmd.java index a3c7d4f6406..b702beda170 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapUserSearchCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapUserSearchCmd.java @@ -21,7 +21,6 @@ import java.util.List; import javax.inject.Inject; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.BaseListCmd; @@ -38,7 +37,6 @@ import com.cloud.user.Account; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class LdapUserSearchCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(LdapUserSearchCmd.class.getName()); private static final String s_name = "ldapuserresponse"; @Inject private LdapManager _ldapManager; @@ -75,7 +73,7 @@ public class LdapUserSearchCmd extends BaseListCmd { try { users = _ldapManager.searchUsers(query); } catch (final NoLdapUserMatchingQueryException e) { - s_logger.debug(e.getMessage()); + logger.debug(e.getMessage()); } final List ldapUserResponses = createLdapUserResponse(users); diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LinkAccountToLdapCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LinkAccountToLdapCmd.java index 16f68b01468..52ece5c44f4 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LinkAccountToLdapCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LinkAccountToLdapCmd.java @@ -37,7 +37,6 @@ import org.apache.cloudstack.api.response.RoleResponse; import org.apache.cloudstack.ldap.LdapManager; import org.apache.cloudstack.ldap.LdapUser; import org.apache.cloudstack.ldap.NoLdapUserMatchingQueryException; -import org.apache.log4j.Logger; import com.cloud.exception.InvalidParameterValueException; import com.cloud.user.Account; @@ -47,7 +46,6 @@ import com.cloud.user.UserAccount; @APICommand(name = "linkAccountToLdap", description = "link a cloudstack account to a group or OU in ldap", responseObject = LinkDomainToLdapResponse.class, since = "4.11.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin,RoleType.DomainAdmin}) public class LinkAccountToLdapCmd extends BaseCmd { - public static final Logger LOGGER = Logger.getLogger(LinkAccountToLdapCmd.class.getName()); @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, required = true, entityType = DomainResponse.class, description = "The id of the domain that is to contain the linked account.") private Long domainId; @@ -83,7 +81,7 @@ public class LinkAccountToLdapCmd extends BaseCmd { try { ldapUser = _ldapManager.getUser(admin, type, ldapDomain, domainId); } catch (NoLdapUserMatchingQueryException e) { - LOGGER.debug("no ldap user matching username " + admin + " in the given group/ou", e); + logger.debug("no ldap user matching username " + admin + " in the given group/ou", e); } if (ldapUser != null && !ldapUser.isDisabled()) { Account account = _accountService.getActiveAccountByName(admin, domainId); @@ -93,15 +91,15 @@ public class LinkAccountToLdapCmd extends BaseCmd { .createUserAccount(admin, "", ldapUser.getFirstname(), ldapUser.getLastname(), ldapUser.getEmail(), null, admin, Account.Type.DOMAIN_ADMIN, RoleType.DomainAdmin.getId(), domainId, null, null, UUID.randomUUID().toString(), UUID.randomUUID().toString(), User.Source.LDAP); response.setAdminId(String.valueOf(userAccount.getAccountId())); - LOGGER.info("created an account with name " + admin + " in the given domain " + domainId); + logger.info("created an account with name {} in the given domain {} with id {}", admin, _domainService.getDomain(domainId), domainId); } catch (Exception e) { - LOGGER.info("an exception occurred while creating account with name " + admin + " in domain " + domainId, e); + logger.info("an exception occurred while creating account with name {} in domain {} with id {}", admin, _domainService.getDomain(domainId), domainId, e); } } else { - LOGGER.debug("an account with name " + admin + " already exists in the domain " + domainId); + logger.debug("an account with name {} already exists in the domain {} with id {}", admin, _domainService.getDomain(domainId), domainId); } } else { - LOGGER.debug("ldap user with username " + admin + " is disabled in the given group/ou"); + logger.debug("ldap user with username " + admin + " is disabled in the given group/ou"); } } response.setObjectName(this.getActualCommandName()); diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LinkDomainToLdapCmd.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LinkDomainToLdapCmd.java index db80ff345f5..c351924de6d 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LinkDomainToLdapCmd.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LinkDomainToLdapCmd.java @@ -35,7 +35,6 @@ import org.apache.cloudstack.api.response.LinkDomainToLdapResponse; import org.apache.cloudstack.ldap.LdapManager; import org.apache.cloudstack.ldap.LdapUser; import org.apache.cloudstack.ldap.NoLdapUserMatchingQueryException; -import org.apache.log4j.Logger; import com.cloud.user.Account; @@ -44,7 +43,6 @@ import java.util.UUID; @APICommand(name = "linkDomainToLdap", description = "link an existing cloudstack domain to group or OU in ldap", responseObject = LinkDomainToLdapResponse.class, since = "4.6.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class LinkDomainToLdapCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(LinkDomainToLdapCmd.class.getName()); @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, required = true, entityType = DomainResponse.class, description = "The id of the domain which has to be " + "linked to LDAP.") @@ -100,7 +98,7 @@ public class LinkDomainToLdapCmd extends BaseCmd { try { ldapUser = _ldapManager.getUser(admin, type, getLdapDomain(), domainId); } catch (NoLdapUserMatchingQueryException e) { - s_logger.debug("no ldap user matching username " + admin + " in the given group/ou", e); + logger.debug("no ldap user matching username " + admin + " in the given group/ou", e); } if (ldapUser != null && !ldapUser.isDisabled()) { Account account = _accountService.getActiveAccountByName(admin, domainId); @@ -109,15 +107,15 @@ public class LinkDomainToLdapCmd extends BaseCmd { UserAccount userAccount = _accountService.createUserAccount(admin, "", ldapUser.getFirstname(), ldapUser.getLastname(), ldapUser.getEmail(), null, admin, Account.Type.DOMAIN_ADMIN, RoleType.DomainAdmin.getId(), domainId, null, null, UUID.randomUUID().toString(), UUID.randomUUID().toString(), User.Source.LDAP); response.setAdminId(String.valueOf(userAccount.getAccountId())); - s_logger.info("created an account with name " + admin + " in the given domain " + domainId); + logger.info("created an account with name {} in the given domain {} with id {}", admin, _domainService.getDomain(domainId), domainId); } catch (Exception e) { - s_logger.info("an exception occurred while creating account with name " + admin +" in domain " + domainId, e); + logger.info("an exception occurred while creating account with name {} in domain {} with id {}", admin, _domainService.getDomain(domainId), domainId, e); } } else { - s_logger.debug("an account with name " + admin + " already exists in the domain " + domainId); + logger.debug("an account with name {} already exists in the domain {} with id {}", admin, _domainService.getDomain(domainId), domainId); } } else { - s_logger.debug("ldap user with username "+admin+" is disabled in the given group/ou"); + logger.debug("ldap user with username "+admin+" is disabled in the given group/ou"); } } response.setObjectName("LinkDomainToLdap"); diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/ADLdapUserManagerImpl.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/ADLdapUserManagerImpl.java index 2413d718b62..e96606dca2f 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/ADLdapUserManagerImpl.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/ADLdapUserManagerImpl.java @@ -28,10 +28,8 @@ import javax.naming.directory.SearchResult; import javax.naming.ldap.LdapContext; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; public class ADLdapUserManagerImpl extends OpenLdapUserManagerImpl implements LdapUserManager { - public static final Logger s_logger = Logger.getLogger(ADLdapUserManagerImpl.class.getName()); private static final String MICROSOFT_AD_NESTED_MEMBERS_FILTER = "memberOf:1.2.840.113556.1.4.1941:"; private static final String MICROSOFT_AD_MEMBERS_FILTER = "memberOf"; @@ -77,7 +75,7 @@ public class ADLdapUserManagerImpl extends OpenLdapUserManagerImpl implements Ld result.append(memberOfFilter); result.append(")"); - s_logger.debug("group search filter = " + result); + logger.debug("group search filter = " + result); return result.toString(); } @@ -95,10 +93,14 @@ public class ADLdapUserManagerImpl extends OpenLdapUserManagerImpl implements Ld } protected String getMemberOfAttribute(final Long domainId) { + String rc; if(_ldapConfiguration.isNestedGroupsEnabled(domainId)) { - return MICROSOFT_AD_NESTED_MEMBERS_FILTER; + rc = MICROSOFT_AD_NESTED_MEMBERS_FILTER; } else { - return MICROSOFT_AD_MEMBERS_FILTER; + rc = MICROSOFT_AD_MEMBERS_FILTER; } + logger.trace("using memberOf filter = {} for domain with id {}", rc, domainId); + + return rc; } } diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapAuthenticator.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapAuthenticator.java index 41ef9573bb2..36c663566cb 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapAuthenticator.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapAuthenticator.java @@ -26,7 +26,6 @@ import javax.inject.Inject; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.auth.UserAuthenticator; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.user.Account; import com.cloud.user.AccountManager; @@ -38,7 +37,6 @@ import com.cloud.utils.component.AdapterBase; import com.cloud.utils.exception.CloudRuntimeException; public class LdapAuthenticator extends AdapterBase implements UserAuthenticator { - private static final Logger LOGGER = Logger.getLogger(LdapAuthenticator.class.getName()); @Inject private LdapManager _ldapManager; @@ -47,6 +45,8 @@ public class LdapAuthenticator extends AdapterBase implements UserAuthenticator @Inject private AccountManager _accountManager; + private static final String LDAP_READ_TIMED_OUT_MESSAGE = "LDAP response read timed out"; + public LdapAuthenticator() { super(); } @@ -61,42 +61,42 @@ public class LdapAuthenticator extends AdapterBase implements UserAuthenticator public Pair authenticate(final String username, final String password, final Long domainId, final Map requestParameters) { Pair rc = new Pair(false, null); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Retrieving ldap user: " + username); + if (logger.isDebugEnabled()) { + logger.debug("Retrieving ldap user: " + username); } // TODO not allowing an empty password is a policy we shouldn't decide on. A private cloud may well want to allow this. if (StringUtils.isNoneEmpty(username, password)) { if (_ldapManager.isLdapEnabled(domainId) || _ldapManager.isLdapEnabled()) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("LDAP is enabled in the ldapManager"); + if (logger.isTraceEnabled()) { + logger.trace("LDAP is enabled in the ldapManager"); } final UserAccount user = _userAccountDao.getUserAccount(username, domainId); if (user != null && ! User.Source.LDAP.equals(user.getSource())) { return rc; } List ldapTrustMapVOs = getLdapTrustMapVOS(domainId); - if(ldapTrustMapVOs != null && ldapTrustMapVOs.size() > 0) { - if(ldapTrustMapVOs.size() == 1 && ldapTrustMapVOs.get(0).getAccountId() == 0) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("We have a single mapping of a domain to an ldap group or ou"); + if (ldapTrustMapVOs != null && ldapTrustMapVOs.size() > 0) { + if (ldapTrustMapVOs.size() == 1 && ldapTrustMapVOs.get(0).getAccountId() == 0) { + if (logger.isTraceEnabled()) { + logger.trace("We have a single mapping of a domain to an ldap group or ou"); } rc = authenticate(username, password, domainId, user, ldapTrustMapVOs.get(0)); } else { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("we are dealing with mapping of accounts in a domain to ldap groups"); + if (logger.isTraceEnabled()) { + logger.trace("we are dealing with mapping of accounts in a domain to ldap groups"); } rc = authenticate(username, password, domainId, user, ldapTrustMapVOs); } } else { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace(String.format("'this' domain (%d) is not linked to ldap follow normal authentication", domainId)); + if (logger.isTraceEnabled()) { + logger.trace(String.format("'this' domain (%d) is not linked to ldap follow normal authentication", domainId)); } rc = authenticate(username, password, domainId, user); } } } else { - LOGGER.debug("Username or Password cannot be empty"); + logger.debug("Username or Password cannot be empty"); } return rc; @@ -127,11 +127,11 @@ public class LdapAuthenticator extends AdapterBase implements UserAuthenticator mappedGroups.retainAll(memberships); tracelist("actual groups for " + username, mappedGroups); // check membership, there must be only one match in this domain - if(ldapUser.isDisabled()) { + if (ldapUser.isDisabled()) { logAndDisable(userAccount, "attempt to log on using disabled ldap user " + userAccount.getUsername(), false); - } else if(mappedGroups.size() > 1) { + } else if (mappedGroups.size() > 1) { logAndDisable(userAccount, "user '" + username + "' is mapped to more then one account in domain and will be disabled.", false); - } else if(mappedGroups.size() < 1) { + } else if (mappedGroups.size() < 1) { logAndDisable(userAccount, "user '" + username + "' is not mapped to an account in domain and will be removed.", true); } else { // a valid ldap configured user exists @@ -139,12 +139,12 @@ public class LdapAuthenticator extends AdapterBase implements UserAuthenticator // we could now assert that ldapTrustMapVOs.contains(mapping); // createUser in Account can only be done by account name not by account id; Account account = _accountManager.getAccount(mapping.getAccountId()); - if(null == account) { + if (null == account) { throw new CloudRuntimeException(String.format("account for user (%s) not found by id %d", username, mapping.getAccountId())); } String accountName = account.getAccountName(); rc.first(_ldapManager.canAuthenticate(ldapUser.getPrincipal(), password, domainId)); - if (! rc.first()) { + if (!rc.first()) { rc.second(ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); } // for security reasons we keep processing on faulty login attempt to not give a way information on userid existence @@ -164,7 +164,7 @@ public class LdapAuthenticator extends AdapterBase implements UserAuthenticator userAccount = _accountManager.getUserAccountById(user.getId()); } else { // not a new user, check if mapped group has changed - if(userAccount.getAccountId() != mapping.getAccountId()) { + if (userAccount.getAccountId() != mapping.getAccountId()) { final Account mappedAccount = _accountManager.getAccount(mapping.getAccountId()); if (mappedAccount == null || mappedAccount.getRemoved() != null) { throw new CloudRuntimeException("Mapped account for users does not exist. Please contact your administrator."); @@ -175,15 +175,24 @@ public class LdapAuthenticator extends AdapterBase implements UserAuthenticator } } } catch (NoLdapUserMatchingQueryException e) { - LOGGER.debug(e.getMessage()); - disableUserInCloudStack(userAccount); + logger.debug(e.getMessage()); + processLdapUserErrorMessage(userAccount, e.getMessage(), rc); } return rc; } + private void processLdapUserErrorMessage(UserAccount user, String errorMessage, Pair rc) { + if (StringUtils.isNotEmpty(errorMessage) && errorMessage.contains(LDAP_READ_TIMED_OUT_MESSAGE) && !rc.first()) { + rc.second(ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); + } else { + // no user in ldap ==>> disable user in cloudstack + disableUserInCloudStack(user); + } + } + private void tracelist(String msg, List listToTrace) { - if (LOGGER.isTraceEnabled()) { + if (logger.isTraceEnabled()) { StringBuilder logMsg = new StringBuilder(); logMsg.append(msg); logMsg.append(':'); @@ -191,15 +200,15 @@ public class LdapAuthenticator extends AdapterBase implements UserAuthenticator logMsg.append(' '); logMsg.append(listMember); } - LOGGER.trace(logMsg.toString()); + logger.trace(logMsg.toString()); } } private void logAndDisable(UserAccount userAccount, String msg, boolean remove) { - if (LOGGER.isInfoEnabled()) { - LOGGER.info(msg); + if (logger.isInfoEnabled()) { + logger.info(msg); } - if(remove) { + if (remove) { removeUserInCloudStack(userAccount); } else { disableUserInCloudStack(userAccount); @@ -230,24 +239,23 @@ public class LdapAuthenticator extends AdapterBase implements UserAuthenticator final Account.Type accountType = ldapTrustMapVO.getAccountType(); processLdapUser(password, domainId, user, rc, ldapUser, accountType); } catch (NoLdapUserMatchingQueryException e) { - LOGGER.debug(e.getMessage()); - // no user in ldap ==>> disable user in cloudstack - disableUserInCloudStack(user); + logger.debug(e.getMessage()); + processLdapUserErrorMessage(user, e.getMessage(), rc); } return rc; } private void processLdapUser(String password, Long domainId, UserAccount user, Pair rc, LdapUser ldapUser, Account.Type accountType) { - if(!ldapUser.isDisabled()) { + if (!ldapUser.isDisabled()) { rc.first(_ldapManager.canAuthenticate(ldapUser.getPrincipal(), password, domainId)); - if(rc.first()) { - if(user == null) { + if (rc.first()) { + if (user == null) { // import user to cloudstack createCloudStackUserAccount(ldapUser, domainId, accountType); } else { enableUserInCloudStack(user); } - } else if(user != null) { + } else if (user != null) { rc.second(ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); } } else { @@ -266,30 +274,34 @@ public class LdapAuthenticator extends AdapterBase implements UserAuthenticator */ Pair authenticate(String username, String password, Long domainId, UserAccount user) { boolean result = false; + boolean timedOut = false; - if(user != null ) { + if (user != null ) { try { LdapUser ldapUser = _ldapManager.getUser(username, domainId); - if(!ldapUser.isDisabled()) { + if (!ldapUser.isDisabled()) { result = _ldapManager.canAuthenticate(ldapUser.getPrincipal(), password, domainId); } else { - LOGGER.debug("user with principal "+ ldapUser.getPrincipal() + " is disabled in ldap"); + logger.debug("user with principal "+ ldapUser.getPrincipal() + " is disabled in ldap"); } } catch (NoLdapUserMatchingQueryException e) { - LOGGER.debug(e.getMessage()); + logger.debug(e.getMessage()); + if (e.getMessage().contains(LDAP_READ_TIMED_OUT_MESSAGE)) { + timedOut = true; + } } } - return processResultAndAction(user, result); + return processResultAndAction(user, result, timedOut); } - private Pair processResultAndAction(UserAccount user, boolean result) { - return (!result && user != null) ? + private Pair processResultAndAction(UserAccount user, boolean result, boolean timedOut) { + return (!result && (user != null || timedOut)) ? new Pair(result, ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT): new Pair(result, null); } private void enableUserInCloudStack(UserAccount user) { - if(user != null && (user.getState().equalsIgnoreCase(Account.State.DISABLED.toString()))) { + if (user != null && (user.getState().equalsIgnoreCase(Account.State.DISABLED.toString()))) { _accountManager.enableUser(user.getId()); } } diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapConfiguration.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapConfiguration.java index 6a62ad8d99d..87ff2d0a2ac 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapConfiguration.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapConfiguration.java @@ -27,9 +27,12 @@ import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import com.cloud.utils.Pair; import org.apache.cloudstack.ldap.dao.LdapConfigurationDao; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class LdapConfiguration implements Configurable{ private final static String factory = "com.sun.jndi.ldap.LdapCtxFactory"; + protected Logger logger = LogManager.getLogger(getClass()); private static final ConfigKey ldapReadTimeout = new ConfigKey( Long.class, @@ -325,7 +328,7 @@ public class LdapConfiguration implements Configurable{ try { provider = LdapUserManager.Provider.valueOf(ldapProvider.valueIn(domainId).toUpperCase()); } catch (IllegalArgumentException ex) { - //openldap is the default + logger.warn("no LDAP provider found for domain {}, using openldap as default", domainId); provider = LdapUserManager.Provider.OPENLDAP; } return provider; diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapContextFactory.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapContextFactory.java index ee48e8cc027..1c759c6a45e 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapContextFactory.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapContextFactory.java @@ -28,10 +28,11 @@ import javax.naming.ldap.LdapContext; import java.security.KeyStore; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; public class LdapContextFactory { - private static final Logger s_logger = Logger.getLogger(LdapContextFactory.class.getName()); + protected Logger logger = LogManager.getLogger(getClass()); @Inject private LdapConfiguration _ldapConfiguration; @@ -53,14 +54,14 @@ public class LdapContextFactory { return createInitialDirContext(bindPrincipal, bindPassword, providerUrl, true, domainId); } - private LdapContext createInitialDirContext(final String principal, final String password, final boolean isSystemContext, Long domainId) throws NamingException, IOException { + private LdapContext createInitialDirContext(final String principal, final String password, final boolean isSystemContext, Long domainId) throws NamingException { return createInitialDirContext(principal, password, null, isSystemContext, domainId); } private LdapContext createInitialDirContext(final String principal, final String password, final String providerUrl, final boolean isSystemContext, Long domainId) - throws NamingException, IOException { + throws NamingException { Hashtable environment = getEnvironment(principal, password, providerUrl, isSystemContext, domainId); - s_logger.debug("initializing ldap with provider url: " + environment.get(Context.PROVIDER_URL)); + logger.debug("initializing ldap with provider url: {}", environment.get(Context.PROVIDER_URL)); return new InitialLdapContext(environment, null); } @@ -72,7 +73,7 @@ public class LdapContextFactory { final boolean sslStatus = _ldapConfiguration.getSSLStatus(domainId); if (sslStatus) { - s_logger.info("LDAP SSL enabled."); + logger.info("LDAP SSL enabled."); environment.put(Context.SECURITY_PROTOCOL, "ssl"); String trustStore = _ldapConfiguration.getTrustStore(domainId); String trustStorePassword = _ldapConfiguration.getTrustStorePassword(domainId); @@ -102,7 +103,7 @@ public class LdapContextFactory { ); return true; } catch (Exception e) { - s_logger.warn("Failed to validate truststore: " + e.getMessage()); + logger.warn("Failed to validate truststore: {}", e.getMessage()); return false; } } diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapManagerImpl.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapManagerImpl.java index 352e439b50c..05b8578bb42 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapManagerImpl.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapManagerImpl.java @@ -52,7 +52,6 @@ import org.apache.cloudstack.framework.messagebus.MessageSubscriber; import org.apache.cloudstack.ldap.dao.LdapConfigurationDao; import org.apache.cloudstack.ldap.dao.LdapTrustMapDao; import org.apache.commons.lang.Validate; -import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.domain.DomainVO; @@ -65,7 +64,6 @@ import com.cloud.utils.Pair; @Component public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManager, LdapValidator { - private static final Logger LOGGER = Logger.getLogger(LdapManagerImpl.class.getName()); @Inject private LdapConfigurationDao _ldapConfigurationDao; @@ -106,7 +104,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); - LOGGER.debug("Configuring LDAP Manager"); + logger.debug("Configuring LDAP Manager"); addAccountRemovalListener(); addDomainRemovalListener(); @@ -126,7 +124,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag removeTrustmap(ldapTrustMapVO); } } catch (final Exception e) { - LOGGER.error("Caught exception while removing account linked to LDAP", e); + logger.error("Caught exception while removing account linked to LDAP", e); } } }); @@ -143,7 +141,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag removeTrustmap(ldapTrustMapVO); } } catch (final Exception e) { - LOGGER.error("Caught exception while removing trust-map for domain linked to LDAP", e); + logger.error("Caught exception while removing trust-map for domain linked to LDAP", e); } } }); @@ -152,7 +150,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag private void removeTrustmap(LdapTrustMapVO ldapTrustMapVO) { String msg = String.format("Removing link between LDAP: %s - type: %s and account: %s on domain: %s", ldapTrustMapVO.getName(), ldapTrustMapVO.getType().name(), ldapTrustMapVO.getAccountId(), ldapTrustMapVO.getDomainId()); - LOGGER.debug(msg); + logger.debug(msg); _ldapTrustMapDao.remove(ldapTrustMapVO.getId()); } @@ -168,7 +166,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag private LdapConfigurationResponse addConfigurationInternal(final String hostname, int port, final Long domainId) throws InvalidParameterValueException { // TODO evaluate what the right default should be - if(port <= 0) { + if (port <= 0) { port = 389; } @@ -181,10 +179,10 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag context = _ldapContextFactory.createBindContext(providerUrl,domainId); configuration = new LdapConfigurationVO(hostname, port, domainId); _ldapConfigurationDao.persist(configuration); - LOGGER.info("Added new ldap server with url: " + providerUrl + (domainId == null ? "": " for domain " + domainId)); + logger.info("Added new ldap server with url: " + providerUrl + (domainId == null ? "": " for domain " + domainId)); return createLdapConfigurationResponse(configuration); } catch (NamingException | IOException e) { - LOGGER.debug("NamingException while doing an LDAP bind", e); + logger.debug("NamingException while doing an LDAP bind", e); throw new InvalidParameterValueException("Unable to bind to the given LDAP server"); } catch (RuntimeException e) { if (e.getMessage().contains("Invalid truststore")) { @@ -212,13 +210,13 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag // TODO return the right account for this user final LdapContext context = _ldapContextFactory.createUserContext(principal, password, domainId); closeContext(context); - if(LOGGER.isTraceEnabled()) { - LOGGER.trace(String.format("User(%s) authenticated for domain(%s)", principal, domainId)); + if (logger.isTraceEnabled()) { + logger.trace(String.format("User(%s) authenticated for domain(%s)", principal, domainId)); } return true; } catch (NamingException | IOException e) {/* AuthenticationException is caught as NamingException */ - LOGGER.debug("Exception while doing an LDAP bind for user "+" "+principal, e); - LOGGER.info("Failed to authenticate user: " + principal + ". incorrect password."); + logger.debug("Exception while doing an LDAP bind for user "+" "+principal, e); + logger.info("Failed to authenticate user: " + principal + ". incorrect password."); return false; } } @@ -229,14 +227,14 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag context.close(); } } catch (final NamingException e) { - LOGGER.warn(e.getMessage(), e); + logger.warn(e.getMessage(), e); } } @Override public LdapConfigurationResponse createLdapConfigurationResponse(final LdapConfigurationVO configuration) { String domainUuid = null; - if(configuration.getDomainId() != null) { + if (configuration.getDomainId() != null) { DomainVO domain = domainDao.findById(configuration.getDomainId()); if (domain != null) { domainUuid = domain.getUuid(); @@ -273,7 +271,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag throw new InvalidParameterValueException("Cannot find configuration with hostname " + hostname); } else { _ldapConfigurationDao.remove(configuration.getId()); - LOGGER.info("Removed ldap server with url: " + hostname + ':' + port + (domainId == null ? "" : " for domain id " + domainId)); + logger.info("Removed ldap server with url: " + hostname + ':' + port + (domainId == null ? "" : " for domain id " + domainId)); return createLdapConfigurationResponse(configuration); } } @@ -305,8 +303,8 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag return _ldapUserManagerFactory.getInstance(_ldapConfiguration.getLdapProvider(null)).getUser(escapedUsername, context, domainId); } catch (NamingException | IOException e) { - LOGGER.debug("ldap Exception: ",e); - throw new NoLdapUserMatchingQueryException("No Ldap User found for username: "+username); + logger.debug("LDAP Exception: ", e); + throw new NoLdapUserMatchingQueryException("Unable to find LDAP User for username: " + username + ", due to " + e.getMessage()); } finally { closeContext(context); } @@ -326,8 +324,8 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag LdapUserManager userManagerFactory = _ldapUserManagerFactory.getInstance(ldapProvider); return userManagerFactory.getUser(escapedUsername, type, name, context, domainId); } catch (NamingException | IOException e) { - LOGGER.debug("ldap Exception: ",e); - throw new NoLdapUserMatchingQueryException("No Ldap User found for username: "+username + " in group: " + name + " of type: " + type); + logger.debug("LDAP Exception: ", e); + throw new NoLdapUserMatchingQueryException("Unable to find LDAP User for username: " + username + " in group: " + name + " of type: " + type + ", due to " + e.getMessage()); } finally { closeContext(context); } @@ -340,7 +338,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag context = _ldapContextFactory.createBindContext(domainId); return _ldapUserManagerFactory.getInstance(_ldapConfiguration.getLdapProvider(domainId)).getUsers(context, domainId); } catch (NamingException | IOException e) { - LOGGER.debug("ldap Exception: ",e); + logger.debug("LDAP Exception: ", e); throw new NoLdapUserMatchingQueryException("*"); } finally { closeContext(context); @@ -354,7 +352,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag context = _ldapContextFactory.createBindContext(domainId); return _ldapUserManagerFactory.getInstance(_ldapConfiguration.getLdapProvider(domainId)).getUsersInGroup(groupName, context, domainId); } catch (NamingException | IOException e) { - LOGGER.debug("ldap NamingException: ",e); + logger.debug("LDAP Exception: ", e); throw new NoLdapUserMatchingQueryException("groupName=" + groupName); } finally { closeContext(context); @@ -392,7 +390,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag final String escapedUsername = LdapUtils.escapeLDAPSearchFilter(username); return _ldapUserManagerFactory.getInstance(_ldapConfiguration.getLdapProvider(null)).getUsers("*" + escapedUsername + "*", context, null); } catch (NamingException | IOException e) { - LOGGER.debug("ldap Exception: ",e); + logger.debug("LDAP Exception: ",e); throw new NoLdapUserMatchingQueryException(username); } finally { closeContext(context); @@ -421,7 +419,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag DomainVO domain = domainDao.findById(vo.getDomainId()); String domainUuid = ""; if (domain == null) { - LOGGER.error("no domain in database for id " + vo.getDomainId()); + logger.error("no domain in database for id " + vo.getDomainId()); } else { domainUuid = domain.getUuid(); } @@ -471,7 +469,7 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag DomainVO domain = domainDao.findById(vo.getDomainId()); String domainUuid = ""; if (domain == null) { - LOGGER.error("no domain in database for id " + vo.getDomainId()); + logger.error("no domain in database for id " + vo.getDomainId()); } else { domainUuid = domain.getUuid(); } @@ -483,23 +481,23 @@ public class LdapManagerImpl extends ComponentLifecycleBase implements LdapManag private void clearOldAccountMapping(LinkAccountToLdapCmd cmd) { // first find if exists log warning and update LdapTrustMapVO oldVo = _ldapTrustMapDao.findGroupInDomain(cmd.getDomainId(), cmd.getLdapDomain()); - if(oldVo != null) { + if (oldVo != null) { // deal with edge cases, i.e. check if the old account is indeed deleted etc. if (oldVo.getAccountId() != 0l) { AccountVO oldAcount = accountDao.findByIdIncludingRemoved(oldVo.getAccountId()); String msg = String.format("group %s is mapped to account %d in the current domain (%s)", cmd.getLdapDomain(), oldVo.getAccountId(), cmd.getDomainId()); if (null == oldAcount.getRemoved()) { msg += ", delete the old map before mapping a new account to the same group."; - LOGGER.error(msg); + logger.error(msg); throw new CloudRuntimeException(msg); } else { msg += ", the old map is deleted."; - LOGGER.warn(msg); + logger.warn(msg); _ldapTrustMapDao.expunge(oldVo.getId()); } } else { String msg = String.format("group %s is mapped to the current domain (%s) for autoimport and can not be used for autosync", cmd.getLdapDomain(), cmd.getDomainId()); - LOGGER.error(msg); + logger.error(msg); throw new CloudRuntimeException(msg); } } diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapUserManagerFactory.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapUserManagerFactory.java index a6217dcb5cb..55d482a29b1 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapUserManagerFactory.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/LdapUserManagerFactory.java @@ -18,7 +18,8 @@ */ package org.apache.cloudstack.ldap; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; @@ -30,7 +31,7 @@ import java.util.Map; public class LdapUserManagerFactory implements ApplicationContextAware { - public static final Logger s_logger = Logger.getLogger(LdapUserManagerFactory.class.getName()); + protected Logger logger = LogManager.getLogger(getClass()); static Map ldapUserManagerMap = new HashMap<>(); diff --git a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/OpenLdapUserManagerImpl.java b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/OpenLdapUserManagerImpl.java index 12bda947f36..d0b6bc4bd34 100644 --- a/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/OpenLdapUserManagerImpl.java +++ b/plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/OpenLdapUserManagerImpl.java @@ -36,10 +36,11 @@ import javax.naming.ldap.PagedResultsResponseControl; import org.apache.cloudstack.ldap.dao.LdapTrustMapDao; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; public class OpenLdapUserManagerImpl implements LdapUserManager { - private static final Logger LOGGER = Logger.getLogger(OpenLdapUserManagerImpl.class.getName()); + protected Logger logger = LogManager.getLogger(getClass()); @Inject protected LdapConfiguration _ldapConfiguration; @@ -62,7 +63,7 @@ public class OpenLdapUserManagerImpl implements LdapUserManager { final String firstname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getFirstnameAttribute(domainId)); final String lastname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getLastnameAttribute(domainId)); final String principal = result.getNameInNamespace(); - final List memberships = LdapUtils.getAttributeValues(attributes, _ldapConfiguration.getUserMemberOfAttribute(domainId)); + final List memberships = LdapUtils.getAttributeValues(attributes, getMemberOfAttribute(domainId)); String domain = principal.replace("cn=" + LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getCommonNameAttribute()) + ",", ""); domain = domain.replace("," + _ldapConfiguration.getBaseDn(domainId), ""); @@ -86,7 +87,7 @@ public class OpenLdapUserManagerImpl implements LdapUserManager { usernameFilter.append((username == null ? "*" : LdapUtils.escapeLDAPSearchFilter(username))); usernameFilter.append(")"); - String memberOfAttribute = _ldapConfiguration.getUserMemberOfAttribute(domainId); + String memberOfAttribute = getMemberOfAttribute(domainId); StringBuilder ldapGroupsFilter = new StringBuilder(); // this should get the trustmaps for this domain List ldapGroups = getMappedLdapGroups(domainId); @@ -112,8 +113,8 @@ public class OpenLdapUserManagerImpl implements LdapUserManager { result.append(")"); String returnString = result.toString(); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("constructed ldap query: " + returnString); + if (logger.isTraceEnabled()) { + logger.trace("constructed ldap query: " + returnString); } return returnString; } @@ -133,8 +134,8 @@ public class OpenLdapUserManagerImpl implements LdapUserManager { private String getMemberOfGroupString(String group, String memberOfAttribute) { final StringBuilder memberOfFilter = new StringBuilder(); if (null != group) { - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("adding search filter for '" + group + + if(logger.isDebugEnabled()) { + logger.debug("adding search filter for '" + group + "', using '" + memberOfAttribute + "'"); } memberOfFilter.append("(" + memberOfAttribute + "="); @@ -253,7 +254,7 @@ public class OpenLdapUserManagerImpl implements LdapUserManager { try{ users.add(getUserForDn(userdn, context, domainId)); } catch (NamingException e){ - LOGGER.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage()); + logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage()); } } } @@ -292,8 +293,8 @@ public class OpenLdapUserManagerImpl implements LdapUserManager { searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes(domainId)); NamingEnumeration results = context.search(basedn, searchString, searchControls); - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("searching user(s) with filter: \"" + searchString + "\""); + if(logger.isDebugEnabled()) { + logger.debug("searching user(s) with filter: \"" + searchString + "\""); } final List users = new ArrayList(); while (results.hasMoreElements()) { @@ -342,7 +343,7 @@ public class OpenLdapUserManagerImpl implements LdapUserManager { } } } else { - LOGGER.info("No controls were sent from the ldap server"); + logger.info("No controls were sent from the ldap server"); } context.setRequestControls(new Control[] {new PagedResultsControl(pageSize, cookie, Control.CRITICAL)}); } while (cookie != null); diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LdapImportUsersCmdTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LdapImportUsersCmdTest.java index 594c23fb786..3dc9d4054b9 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LdapImportUsersCmdTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LdapImportUsersCmdTest.java @@ -37,9 +37,9 @@ import java.util.List; import java.util.UUID; import static junit.framework.TestCase.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LdapListUsersCmdTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LdapListUsersCmdTest.java index 11d99f58858..bd55926e8e0 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LdapListUsersCmdTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LdapListUsersCmdTest.java @@ -49,7 +49,7 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LinkAccountToLdapCmdTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LinkAccountToLdapCmdTest.java index e355d77c343..adf0f98f294 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LinkAccountToLdapCmdTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LinkAccountToLdapCmdTest.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.command; import com.cloud.user.Account; import com.cloud.user.AccountService; +import com.cloud.user.DomainService; import com.cloud.user.User; import com.cloud.user.UserAccountVO; import org.apache.cloudstack.acl.RoleType; @@ -30,12 +31,12 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isNull; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -45,6 +46,8 @@ public class LinkAccountToLdapCmdTest implements LdapConfigurationChanger { LdapManager ldapManager; @Mock AccountService accountService; + @Mock + DomainService domainService; LinkAccountToLdapCmd linkAccountToLdapCmd; @@ -53,6 +56,7 @@ public class LinkAccountToLdapCmdTest implements LdapConfigurationChanger { linkAccountToLdapCmd = new LinkAccountToLdapCmd(); setHiddenField(linkAccountToLdapCmd, "_ldapManager", ldapManager); setHiddenField(linkAccountToLdapCmd, "_accountService", accountService); + setHiddenField(linkAccountToLdapCmd, "_domainService", domainService); } @Test diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LinkDomainToLdapCmdTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LinkDomainToLdapCmdTest.java index 204e9853ffe..080347fefd3 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LinkDomainToLdapCmdTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/api/command/LinkDomainToLdapCmdTest.java @@ -18,6 +18,7 @@ package org.apache.cloudstack.api.command; import com.cloud.user.Account; import com.cloud.user.AccountService; +import com.cloud.user.DomainService; import com.cloud.user.User; import com.cloud.user.UserAccountVO; import org.apache.cloudstack.acl.RoleType; @@ -29,12 +30,12 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isNull; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -44,6 +45,8 @@ public class LinkDomainToLdapCmdTest implements LdapConfigurationChanger LdapManager ldapManager; @Mock AccountService accountService; + @Mock + DomainService domainService; LinkDomainToLdapCmd linkDomainToLdapCmd; @@ -52,6 +55,7 @@ public class LinkDomainToLdapCmdTest implements LdapConfigurationChanger linkDomainToLdapCmd = new LinkDomainToLdapCmd(); setHiddenField(linkDomainToLdapCmd, "_ldapManager", ldapManager); setHiddenField(linkDomainToLdapCmd, "_accountService", accountService); + setHiddenField(linkDomainToLdapCmd, "_domainService", domainService); } @After diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/ADLdapUserManagerImplTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/ADLdapUserManagerImplTest.java index bf9d7437446..58b14ec3684 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/ADLdapUserManagerImplTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/ADLdapUserManagerImplTest.java @@ -26,7 +26,7 @@ import javax.naming.directory.SearchControls; import javax.naming.ldap.LdapContext; import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapAuthenticatorTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapAuthenticatorTest.java index a3b2311e2ce..0d1d840ce22 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapAuthenticatorTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapAuthenticatorTest.java @@ -41,7 +41,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyLong; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapConfigurationTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapConfigurationTest.java index 58024b752ab..5defce948b2 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapConfigurationTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapConfigurationTest.java @@ -21,7 +21,7 @@ import org.apache.cloudstack.ldap.dao.LdapConfigurationDaoImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapDirectoryServerConnectionTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapDirectoryServerConnectionTest.java index 2d2690f8e3a..a216084aa3a 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapDirectoryServerConnectionTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapDirectoryServerConnectionTest.java @@ -88,7 +88,7 @@ public class LdapDirectoryServerConnectionTest { ldapTestConfigTool.overrideConfigValue(configuration, "ldapBindPrincipal", "uid=admin,ou=system"); ldapTestConfigTool.overrideConfigValue(configuration, "ldapMemberOfAttribute", "memberOf"); lenient().when(userManagerFactory.getInstance(LdapUserManager.Provider.OPENLDAP)).thenReturn(new OpenLdapUserManagerImpl(configuration)); - // construct an ellaborate structure around a single object + // construct an elaborate structure around a single object Pair, Integer> vos = new Pair, Integer>( Collections.singletonList(configurationVO),1); lenient().when(configurationDao.searchConfigurations(null, 0, 1L)).thenReturn(vos); @@ -149,7 +149,7 @@ public class LdapDirectoryServerConnectionTest { public void testSchemaLoading() { try { assertTrue("standard not loaded", embeddedLdapServer.addSchemaFromClasspath("other")); -// we need member of in ACS nowadays (backwards comptability broken): +// we need member of in ACS nowadays (backwards compatibility broken): // assertTrue("memberOf schema not loaded", embeddedLdapServer.addSchemaFromPath(new File("src/test/resources/memberOf"), "microsoft")); } catch (LdapException | IOException e) { fail(e.getLocalizedMessage()); diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapTestConfigTool.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapTestConfigTool.java index 47f201de479..4197bad4f2d 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapTestConfigTool.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapTestConfigTool.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.ldap; import org.apache.cloudstack.framework.config.ConfigKey; import java.lang.reflect.Field; -import java.lang.reflect.Modifier; public class LdapTestConfigTool { public LdapTestConfigTool() { @@ -31,18 +30,12 @@ public class LdapTestConfigTool { ConfigKey key = (ConfigKey)configKey.get(ldapConfiguration); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(configKey, configKey.getModifiers() & ~Modifier.FINAL); - Field f = ConfigKey.class.getDeclaredField("_value"); f.setAccessible(true); - modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL); f.set(key, o); Field dynamic = ConfigKey.class.getDeclaredField("_isDynamic"); dynamic.setAccessible(true); - modifiersField.setInt(dynamic, dynamic.getModifiers() & ~Modifier.FINAL); dynamic.setBoolean(key, false); } } diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUnboundidZapdotConnectionTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUnboundidZapdotConnectionTest.java index 7e2c89e5556..85267dcbeca 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUnboundidZapdotConnectionTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUnboundidZapdotConnectionTest.java @@ -24,7 +24,7 @@ import com.unboundid.ldap.sdk.SearchScope; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.zapodot.junit.ldap.EmbeddedLdapRule; import org.zapodot.junit.ldap.EmbeddedLdapRuleBuilder; diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUnitConnectionTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUnitConnectionTest.java index 1bdfa9a91aa..a1923947e94 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUnitConnectionTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUnitConnectionTest.java @@ -21,7 +21,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.btmatthews.ldapunit.DirectoryTester; import com.btmatthews.ldapunit.DirectoryServerConfiguration; diff --git a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUserManagerFactoryTest.java b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUserManagerFactoryTest.java index 206526b61a0..8d647039144 100644 --- a/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUserManagerFactoryTest.java +++ b/plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/LdapUserManagerFactoryTest.java @@ -23,7 +23,7 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; diff --git a/plugins/user-authenticators/ldap/src/test/resources/log4j.xml b/plugins/user-authenticators/ldap/src/test/resources/log4j.xml index 031d2283580..6c0ffa264e1 100755 --- a/plugins/user-authenticators/ldap/src/test/resources/log4j.xml +++ b/plugins/user-authenticators/ldap/src/test/resources/log4j.xml @@ -19,60 +19,46 @@ under the License. --> - + + - + + net.sf.cglib.proxy + - - - - + + + - - - + + + + + - - - - - - - + - - - + + + - - - - - - - - + - - - + - - - + - - - + + - - - + + + - - - - + + + - + + diff --git a/plugins/user-authenticators/ldap/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/plugins/user-authenticators/ldap/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker deleted file mode 100644 index 1f0955d450f..00000000000 --- a/plugins/user-authenticators/ldap/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker +++ /dev/null @@ -1 +0,0 @@ -mock-maker-inline diff --git a/plugins/user-authenticators/md5/pom.xml b/plugins/user-authenticators/md5/pom.xml index ad10b0e7478..c73e9f68830 100644 --- a/plugins/user-authenticators/md5/pom.xml +++ b/plugins/user-authenticators/md5/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT ../../pom.xml diff --git a/plugins/user-authenticators/md5/src/main/java/org/apache/cloudstack/auth/MD5UserAuthenticator.java b/plugins/user-authenticators/md5/src/main/java/org/apache/cloudstack/auth/MD5UserAuthenticator.java index 3f3898f6464..7286f57d048 100644 --- a/plugins/user-authenticators/md5/src/main/java/org/apache/cloudstack/auth/MD5UserAuthenticator.java +++ b/plugins/user-authenticators/md5/src/main/java/org/apache/cloudstack/auth/MD5UserAuthenticator.java @@ -23,7 +23,6 @@ import java.util.Map; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; @@ -37,30 +36,29 @@ import com.cloud.utils.exception.CloudRuntimeException; * */ public class MD5UserAuthenticator extends AdapterBase implements UserAuthenticator { - public static final Logger s_logger = Logger.getLogger(MD5UserAuthenticator.class); @Inject private UserAccountDao _userAccountDao; @Override public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Retrieving user: " + username); + if (logger.isDebugEnabled()) { + logger.debug("Retrieving user: " + username); } if (StringUtils.isAnyEmpty(username, password)) { - s_logger.debug("Username or Password cannot be empty"); + logger.debug("Username or Password cannot be empty"); return new Pair<>(false, null); } UserAccount user = _userAccountDao.getUserAccount(username, domainId); if (user == null) { - s_logger.debug("Unable to find user with " + username + " in domain " + domainId); + logger.debug("Unable to find user with " + username + " in domain " + domainId); return new Pair<>(false, null); } if (!user.getPassword().equals(encode(password))) { - s_logger.debug("Password does not match"); + logger.debug("Password does not match"); return new Pair<>(false, ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); } return new Pair<>(true, null); diff --git a/plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/spring-md5-context.xml b/plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/spring-md5-context.xml index 132f1481bb6..a447e731743 100644 --- a/plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/spring-md5-context.xml +++ b/plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/spring-md5-context.xml @@ -30,5 +30,5 @@ - + diff --git a/plugins/user-authenticators/md5/src/test/java/org/apache/cloudstack/auth/MD5UserAuthenticatorTest.java b/plugins/user-authenticators/md5/src/test/java/org/apache/cloudstack/auth/MD5UserAuthenticatorTest.java index 78af8e532f0..ad86b16f39e 100644 --- a/plugins/user-authenticators/md5/src/test/java/org/apache/cloudstack/auth/MD5UserAuthenticatorTest.java +++ b/plugins/user-authenticators/md5/src/test/java/org/apache/cloudstack/auth/MD5UserAuthenticatorTest.java @@ -26,7 +26,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.cloud.user.UserAccountVO; import com.cloud.user.dao.UserAccountDao; diff --git a/plugins/user-authenticators/oauth2/pom.xml b/plugins/user-authenticators/oauth2/pom.xml index c8bf9348560..65e7d1ff65a 100644 --- a/plugins/user-authenticators/oauth2/pom.xml +++ b/plugins/user-authenticators/oauth2/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT ../../pom.xml diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImpl.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImpl.java index b0596f0c386..b65027d6a24 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImpl.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImpl.java @@ -34,7 +34,6 @@ import org.apache.cloudstack.oauth2.api.command.VerifyOAuthCodeAndGetUserCmd; import org.apache.cloudstack.oauth2.dao.OauthProviderDao; import org.apache.cloudstack.oauth2.vo.OauthProviderVO; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import javax.inject.Inject; import java.util.ArrayList; @@ -44,7 +43,6 @@ import java.util.List; import java.util.Map; public class OAuth2AuthManagerImpl extends ManagerBase implements OAuth2AuthManager, Manager, Configurable { - private static final Logger s_logger = Logger.getLogger(OAuth2AuthManagerImpl.class); @Inject private UserDao _userDao; @@ -67,10 +65,10 @@ public class OAuth2AuthManagerImpl extends ManagerBase implements OAuth2AuthMana @Override public boolean start() { if (isOAuthPluginEnabled()) { - s_logger.info("OAUTH plugin loaded"); + logger.info("OAUTH plugin loaded"); initializeUserOAuth2AuthenticationProvidersMap(); } else { - s_logger.info("OAUTH plugin not enabled so not loading"); + logger.info("OAUTH plugin not enabled so not loading"); } return true; } diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticator.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticator.java index 5d721e7e0d6..dde50c8bb34 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticator.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticator.java @@ -27,7 +27,6 @@ import com.cloud.utils.component.AdapterBase; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.auth.UserAuthenticator; import org.apache.cloudstack.auth.UserOAuth2Authenticator; -import org.apache.log4j.Logger; import javax.inject.Inject; import java.util.Map; @@ -35,7 +34,6 @@ import java.util.Map; import static org.apache.cloudstack.oauth2.OAuth2AuthManager.OAuth2IsPluginEnabled; public class OAuth2UserAuthenticator extends AdapterBase implements UserAuthenticator { - public static final Logger s_logger = Logger.getLogger(OAuth2UserAuthenticator.class); @Inject private UserAccountDao userAccountDao; @@ -47,21 +45,21 @@ public class OAuth2UserAuthenticator extends AdapterBase implements UserAuthenti @Override public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Trying OAuth2 auth for user: " + username); + if (logger.isDebugEnabled()) { + logger.debug("Trying OAuth2 auth for user: " + username); } if (!isOAuthPluginEnabled()) { - s_logger.debug("OAuth2 plugin is disabled"); + logger.debug("OAuth2 plugin is disabled"); return new Pair(false, null); } else if (requestParameters == null) { - s_logger.debug("Request parameters are null"); + logger.debug("Request parameters are null"); return new Pair(false, null); } final UserAccount userAccount = userAccountDao.getUserAccount(username, domainId); if (userAccount == null) { - s_logger.debug("Unable to find user with " + username + " in domain " + domainId + ", or user source is not OAUTH2"); + logger.debug("Unable to find user with " + username + " in domain " + domainId + ", or user source is not OAUTH2"); return new Pair(false, null); } else { User user = userDao.getUser(userAccount.getId()); diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/DeleteOAuthProviderCmd.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/DeleteOAuthProviderCmd.java index 6cd3156f68a..28f2a636273 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/DeleteOAuthProviderCmd.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/DeleteOAuthProviderCmd.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.oauth2.api.command; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.oauth2.OAuth2AuthManager; import org.apache.cloudstack.oauth2.api.response.OauthProviderResponse; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -35,7 +34,6 @@ import javax.inject.Inject; @APICommand(name = "deleteOauthProvider", description = "Deletes the registered OAuth provider", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.19.0") public class DeleteOAuthProviderCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteOAuthProviderCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/ListOAuthProvidersCmd.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/ListOAuthProvidersCmd.java index 597283ae33e..abdbf65dbb4 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/ListOAuthProvidersCmd.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/ListOAuthProvidersCmd.java @@ -39,7 +39,6 @@ import org.apache.cloudstack.oauth2.OAuth2AuthManager; import org.apache.cloudstack.oauth2.api.response.OauthProviderResponse; import org.apache.cloudstack.oauth2.vo.OauthProviderVO; import org.apache.commons.lang.ArrayUtils; -import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -49,7 +48,6 @@ import javax.servlet.http.HttpSession; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}, since = "4.19.0") public class ListOAuthProvidersCmd extends BaseListCmd implements APIAuthenticator { - public static final Logger s_logger = Logger.getLogger(ListOAuthProvidersCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -141,7 +139,7 @@ public class ListOAuthProvidersCmd extends BaseListCmd implements APIAuthenticat } } if (_oauth2mgr == null) { - s_logger.error("No suitable Pluggable Authentication Manager found for listing OAuth providers"); + logger.error("No suitable Pluggable Authentication Manager found for listing OAuth providers"); } } } diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmd.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmd.java index 928fa76780a..f9a1d10d352 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmd.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmd.java @@ -36,7 +36,6 @@ import org.apache.cloudstack.api.auth.PluggableAPIAuthenticator; import org.apache.cloudstack.api.response.LoginCmdResponse; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.jetbrains.annotations.Nullable; import javax.inject.Inject; @@ -54,8 +53,6 @@ import static org.apache.cloudstack.oauth2.OAuth2AuthManager.OAuth2IsPluginEnabl requestHasSensitiveInfo = true, responseObject = LoginCmdResponse.class, entityType = {}, since = "4.19.0") public class OauthLoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthenticator { - public static final Logger s_logger = Logger.getLogger(OauthLoginAPIAuthenticatorCmd.class.getName()); - ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -169,8 +166,8 @@ public class OauthLoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent "failed to authenticate user, check if username/password are correct"); auditTrailSb.append(" " + ApiErrorCode.ACCOUNT_ERROR + " " + msg); serializedResponse = _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), msg, params, responseType); - if (s_logger.isTraceEnabled()) { - s_logger.trace(msg); + if (logger.isTraceEnabled()) { + logger.trace(msg); } } @@ -194,7 +191,7 @@ public class OauthLoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent } auditTrailSb.append(" domainid=" + domainId);// building the params for POST call } catch (final NumberFormatException e) { - s_logger.warn("Invalid domain id entered by user"); + logger.warn("Invalid domain id entered by user"); auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "Invalid domain id entered, please enter a valid one"); throw new ServerApiException(ApiErrorCode.UNAUTHORIZED, _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid domain id entered, please enter a valid one", params, diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/UpdateOAuthProviderCmd.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/UpdateOAuthProviderCmd.java index b38423ffd48..1c79b7b144c 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/UpdateOAuthProviderCmd.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/UpdateOAuthProviderCmd.java @@ -21,7 +21,6 @@ import org.apache.cloudstack.auth.UserOAuth2Authenticator; import org.apache.cloudstack.oauth2.OAuth2AuthManager; import org.apache.cloudstack.oauth2.api.response.OauthProviderResponse; import org.apache.cloudstack.oauth2.vo.OauthProviderVO; -import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; @@ -38,7 +37,6 @@ import java.util.List; @APICommand(name = "updateOauthProvider", description = "Updates the registered OAuth provider details", responseObject = OauthProviderResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, since = "4.19.0") public final class UpdateOAuthProviderCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpdateOAuthProviderCmd.class.getName()); ///////////////////////////////////////////////////// diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/VerifyOAuthCodeAndGetUserCmd.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/VerifyOAuthCodeAndGetUserCmd.java index 5dbeef10dcb..bd49f87d627 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/VerifyOAuthCodeAndGetUserCmd.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/VerifyOAuthCodeAndGetUserCmd.java @@ -36,7 +36,6 @@ import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.oauth2.OAuth2AuthManager; import org.apache.cloudstack.oauth2.api.response.OauthProviderResponse; import org.apache.commons.lang.ArrayUtils; -import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -46,7 +45,6 @@ import javax.servlet.http.HttpSession; requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}, since = "4.19.0") public class VerifyOAuthCodeAndGetUserCmd extends BaseListCmd implements APIAuthenticator { - public static final Logger s_logger = Logger.getLogger(VerifyOAuthCodeAndGetUserCmd.class.getName()); ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -124,7 +122,7 @@ public class VerifyOAuthCodeAndGetUserCmd extends BaseListCmd implements APIAuth } } if (_oauth2mgr == null) { - s_logger.error("No suitable Pluggable Authentication Manager found for listing OAuth providers"); + logger.error("No suitable Pluggable Authentication Manager found for listing OAuth providers"); } } } diff --git a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/google/GoogleOAuth2Provider.java b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/google/GoogleOAuth2Provider.java index aa0fc93776d..42ed1451ccd 100644 --- a/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/google/GoogleOAuth2Provider.java +++ b/plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/google/GoogleOAuth2Provider.java @@ -32,7 +32,6 @@ import org.apache.cloudstack.auth.UserOAuth2Authenticator; import org.apache.cloudstack.oauth2.dao.OauthProviderDao; import org.apache.cloudstack.oauth2.vo.OauthProviderVO; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import javax.inject.Inject; import java.io.IOException; @@ -40,7 +39,6 @@ import java.util.Arrays; import java.util.List; public class GoogleOAuth2Provider extends AdapterBase implements UserOAuth2Authenticator { - private static final Logger s_logger = Logger.getLogger(GoogleOAuth2Provider.class); protected String accessToken = null; protected String refreshToken = null; diff --git a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticatorTest.java b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticatorTest.java index 9a6e8812679..d1c1889ba99 100644 --- a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticatorTest.java +++ b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/OAuth2UserAuthenticatorTest.java @@ -43,11 +43,11 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.doReturn; @RunWith(MockitoJUnitRunner.class) public class OAuth2UserAuthenticatorTest { diff --git a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/DeleteOAuthProviderCmdTest.java b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/DeleteOAuthProviderCmdTest.java index be8670c1af9..cb99fde2410 100644 --- a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/DeleteOAuthProviderCmdTest.java +++ b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/DeleteOAuthProviderCmdTest.java @@ -24,13 +24,14 @@ import static org.mockito.Mockito.when; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.oauth2.OAuth2AuthManager; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class DeleteOAuthProviderCmdTest { @@ -41,9 +42,16 @@ public class DeleteOAuthProviderCmdTest { @InjectMocks private DeleteOAuthProviderCmd cmd; + private AutoCloseable closeable; + @Before public void setUp() { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); + } + + @After + public void tearDown() throws Exception { + closeable.close(); } @Test(expected = ServerApiException.class) diff --git a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmdTest.java b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmdTest.java index 07df66f2026..ccbb53cfc80 100644 --- a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmdTest.java +++ b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/OauthLoginAPIAuthenticatorCmdTest.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.oauth2.api.command; import com.cloud.api.ApiServer; import org.apache.cloudstack.api.ApiConstants; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -36,10 +37,18 @@ public class OauthLoginAPIAuthenticatorCmdTest { @InjectMocks private OauthLoginAPIAuthenticatorCmd cmd; + private AutoCloseable closeable; + @Before public void setUp() { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); } + + @After + public void tearDown() throws Exception { + closeable.close(); + } + @Test public void testGetDomainNameWhenDomainNameIsNull() { StringBuilder auditTrailSb = new StringBuilder(); diff --git a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmdTest.java b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmdTest.java index 987c7a5d01e..c61edd4610c 100644 --- a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmdTest.java +++ b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/api/command/RegisterOAuthProviderCmdTest.java @@ -28,13 +28,14 @@ import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.oauth2.OAuth2AuthManager; import org.apache.cloudstack.oauth2.api.response.OauthProviderResponse; import org.apache.cloudstack.oauth2.vo.OauthProviderVO; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class RegisterOAuthProviderCmdTest { @@ -45,9 +46,16 @@ public class RegisterOAuthProviderCmdTest { @InjectMocks private RegisterOAuthProviderCmd _cmd; + private AutoCloseable closeable; + @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); + } + + @After + public void tearDown() throws Exception { + closeable.close(); } @Test diff --git a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/google/GoogleOAuth2ProviderTest.java b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/google/GoogleOAuth2ProviderTest.java index b8b1abcc4be..fa8a5a7c03c 100644 --- a/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/google/GoogleOAuth2ProviderTest.java +++ b/plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/google/GoogleOAuth2ProviderTest.java @@ -23,6 +23,7 @@ import com.google.api.services.oauth2.Oauth2; import com.google.api.services.oauth2.model.Userinfo; import org.apache.cloudstack.oauth2.dao.OauthProviderDao; import org.apache.cloudstack.oauth2.vo.OauthProviderVO; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -49,9 +50,16 @@ public class GoogleOAuth2ProviderTest { @InjectMocks private GoogleOAuth2Provider _googleOAuth2Provider; + private AutoCloseable closeable; + @Before public void setUp() { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); + } + + @After + public void tearDown() throws Exception { + closeable.close(); } @Test(expected = CloudAuthenticationException.class) diff --git a/plugins/user-authenticators/pbkdf2/pom.xml b/plugins/user-authenticators/pbkdf2/pom.xml index ebb204dab24..90d9401f88f 100644 --- a/plugins/user-authenticators/pbkdf2/pom.xml +++ b/plugins/user-authenticators/pbkdf2/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT ../../pom.xml diff --git a/plugins/user-authenticators/pbkdf2/src/main/java/org/apache/cloudstack/server/auth/PBKDF2UserAuthenticator.java b/plugins/user-authenticators/pbkdf2/src/main/java/org/apache/cloudstack/server/auth/PBKDF2UserAuthenticator.java index 3c2521f3430..edb7d338db9 100644 --- a/plugins/user-authenticators/pbkdf2/src/main/java/org/apache/cloudstack/server/auth/PBKDF2UserAuthenticator.java +++ b/plugins/user-authenticators/pbkdf2/src/main/java/org/apache/cloudstack/server/auth/PBKDF2UserAuthenticator.java @@ -27,7 +27,6 @@ import javax.inject.Inject; import org.apache.cloudstack.auth.UserAuthenticator; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.bouncycastle.crypto.PBEParametersGenerator; import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; import org.bouncycastle.crypto.params.KeyParameter; @@ -41,7 +40,6 @@ import com.cloud.utils.component.AdapterBase; import com.cloud.utils.exception.CloudRuntimeException; public class PBKDF2UserAuthenticator extends AdapterBase implements UserAuthenticator { - public static final Logger s_logger = Logger.getLogger(PBKDF2UserAuthenticator.class); private static final int s_saltlen = 64; private static final int s_rounds = 100000; private static final int s_keylen = 512; @@ -51,12 +49,12 @@ public class PBKDF2UserAuthenticator extends AdapterBase implements UserAuthenti @Override public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Retrieving user: " + username); + if (logger.isDebugEnabled()) { + logger.debug("Retrieving user: " + username); } if (StringUtils.isAnyEmpty(username, password)) { - s_logger.debug("Username or Password cannot be empty"); + logger.debug("Username or Password cannot be empty"); return new Pair(false, null); } @@ -65,7 +63,7 @@ public class PBKDF2UserAuthenticator extends AdapterBase implements UserAuthenti if (user != null) { isValidUser = true; } else { - s_logger.debug("Unable to find user with " + username + " in domain " + domainId); + logger.debug("Unable to find user with " + username + " in domain " + domainId); } byte[] salt = new byte[0]; @@ -74,7 +72,7 @@ public class PBKDF2UserAuthenticator extends AdapterBase implements UserAuthenti if (isValidUser) { String[] storedPassword = user.getPassword().split(":"); if ((storedPassword.length != 3) || (!StringUtils.isNumeric(storedPassword[2]))) { - s_logger.warn("The stored password for " + username + " isn't in the right format for this authenticator"); + logger.warn("The stored password for " + username + " isn't in the right format for this authenticator"); isValidUser = false; } else { // Encoding format = :: @@ -114,7 +112,7 @@ public class PBKDF2UserAuthenticator extends AdapterBase implements UserAuthenti } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable to hash password", e); } catch (InvalidKeySpecException e) { - s_logger.error("Exception in EncryptUtil.createKey ", e); + logger.error("Exception in EncryptUtil.createKey ", e); throw new CloudRuntimeException("Unable to hash password", e); } } diff --git a/plugins/user-authenticators/pbkdf2/src/test/java/org/apache/cloudstack/server/auth/PBKD2UserAuthenticatorTest.java b/plugins/user-authenticators/pbkdf2/src/test/java/org/apache/cloudstack/server/auth/PBKD2UserAuthenticatorTest.java index 3440f26c905..6498608ed98 100644 --- a/plugins/user-authenticators/pbkdf2/src/test/java/org/apache/cloudstack/server/auth/PBKD2UserAuthenticatorTest.java +++ b/plugins/user-authenticators/pbkdf2/src/test/java/org/apache/cloudstack/server/auth/PBKD2UserAuthenticatorTest.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import java.lang.reflect.Field; import java.security.NoSuchAlgorithmException; diff --git a/plugins/user-authenticators/plain-text/pom.xml b/plugins/user-authenticators/plain-text/pom.xml index b6699d08e81..997b1bf8367 100644 --- a/plugins/user-authenticators/plain-text/pom.xml +++ b/plugins/user-authenticators/plain-text/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT ../../pom.xml diff --git a/plugins/user-authenticators/plain-text/src/main/java/org/apache/cloudstack/auth/PlainTextUserAuthenticator.java b/plugins/user-authenticators/plain-text/src/main/java/org/apache/cloudstack/auth/PlainTextUserAuthenticator.java index f38e88b76db..4e3d402222e 100644 --- a/plugins/user-authenticators/plain-text/src/main/java/org/apache/cloudstack/auth/PlainTextUserAuthenticator.java +++ b/plugins/user-authenticators/plain-text/src/main/java/org/apache/cloudstack/auth/PlainTextUserAuthenticator.java @@ -20,7 +20,6 @@ import java.util.Map; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; @@ -28,30 +27,29 @@ import com.cloud.utils.Pair; import com.cloud.utils.component.AdapterBase; public class PlainTextUserAuthenticator extends AdapterBase implements UserAuthenticator { - public static final Logger s_logger = Logger.getLogger(PlainTextUserAuthenticator.class); @Inject private UserAccountDao _userAccountDao; @Override public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Retrieving user: " + username); + if (logger.isDebugEnabled()) { + logger.debug("Retrieving user: " + username); } if (StringUtils.isAnyEmpty(username, password)) { - s_logger.debug("Username or Password cannot be empty"); + logger.debug("Username or Password cannot be empty"); return new Pair<>(false, null); } UserAccount user = _userAccountDao.getUserAccount(username, domainId); if (user == null) { - s_logger.debug("Unable to find user with " + username + " in domain " + domainId); + logger.debug("Unable to find user with " + username + " in domain " + domainId); return new Pair<>(false, null); } if (!user.getPassword().equals(password)) { - s_logger.debug("Password does not match"); + logger.debug("Password does not match"); return new Pair<>(false, ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); } return new Pair<>(true, null); diff --git a/plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/spring-plaintext-context.xml b/plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/spring-plaintext-context.xml index fccff88c4cb..0b22b010e19 100644 --- a/plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/spring-plaintext-context.xml +++ b/plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/spring-plaintext-context.xml @@ -31,5 +31,5 @@ - + diff --git a/plugins/user-authenticators/saml2/pom.xml b/plugins/user-authenticators/saml2/pom.xml index 6d2cd89c137..5f5d6b14253 100644 --- a/plugins/user-authenticators/saml2/pom.xml +++ b/plugins/user-authenticators/saml2/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT ../../pom.xml diff --git a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/AuthorizeSAMLSSOCmd.java b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/AuthorizeSAMLSSOCmd.java index 9a7dadcdb8a..c5f48d61c6f 100644 --- a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/AuthorizeSAMLSSOCmd.java +++ b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/AuthorizeSAMLSSOCmd.java @@ -31,13 +31,11 @@ import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.saml.SAML2AuthManager; -import org.apache.log4j.Logger; import javax.inject.Inject; @APICommand(name = "authorizeSamlSso", description = "Allow or disallow a user to use SAML SSO", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AuthorizeSAMLSSOCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AuthorizeSAMLSSOCmd.class.getName()); @Inject diff --git a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmd.java b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmd.java index e462e33cbfe..50b075b4448 100644 --- a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmd.java +++ b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmd.java @@ -48,7 +48,6 @@ import org.apache.cloudstack.api.response.SAMLMetaDataResponse; import org.apache.cloudstack.saml.SAML2AuthManager; import org.apache.cloudstack.saml.SAMLProviderMetadata; import org.apache.cloudstack.utils.security.ParserUtils; -import org.apache.log4j.Logger; import org.opensaml.Configuration; import org.opensaml.DefaultBootstrap; import org.opensaml.common.xml.SAMLConstants; @@ -95,7 +94,6 @@ import com.cloud.utils.HttpUtils; @APICommand(name = "getSPMetadata", description = "Returns SAML2 CloudStack Service Provider MetaData", responseObject = SAMLMetaDataResponse.class, entityType = {}) public class GetServiceProviderMetaDataCmd extends BaseCmd implements APIAuthenticator { - public static final Logger s_logger = Logger.getLogger(GetServiceProviderMetaDataCmd.class.getName()); private static final String s_name = "spmetadataresponse"; @Inject @@ -130,7 +128,7 @@ public class GetServiceProviderMetaDataCmd extends BaseCmd implements APIAuthent try { DefaultBootstrap.bootstrap(); } catch (ConfigurationException | FactoryConfigurationError e) { - s_logger.error("OpenSAML Bootstrapping error: " + e.getMessage()); + logger.error("OpenSAML Bootstrapping error: " + e.getMessage()); throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "OpenSAML Bootstrapping error while creating SP MetaData", params, responseType)); @@ -167,7 +165,7 @@ public class GetServiceProviderMetaDataCmd extends BaseCmd implements APIAuthent spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); spSSODescriptor.getKeyDescriptors().add(encKeyDescriptor); } catch (SecurityException e) { - s_logger.warn("Unable to add SP X509 descriptors:" + e.getMessage()); + logger.warn("Unable to add SP X509 descriptors:" + e.getMessage()); } NameIDFormat nameIDFormat = new NameIDFormatBuilder().buildObject(); @@ -281,7 +279,7 @@ public class GetServiceProviderMetaDataCmd extends BaseCmd implements APIAuthent } } if (_samlAuthManager == null) { - s_logger.error("No suitable Pluggable Authentication Manager found for SAML2 getSPMetadata Cmd"); + logger.error("No suitable Pluggable Authentication Manager found for SAML2 getSPMetadata Cmd"); } } } diff --git a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListAndSwitchSAMLAccountCmd.java b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListAndSwitchSAMLAccountCmd.java index 040d5414f26..5263ade6b37 100644 --- a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListAndSwitchSAMLAccountCmd.java +++ b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListAndSwitchSAMLAccountCmd.java @@ -46,7 +46,6 @@ import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.saml.SAML2AuthManager; import org.apache.cloudstack.saml.SAMLUtils; -import org.apache.log4j.Logger; import com.cloud.api.ApiServer; import com.cloud.api.response.ApiResponseSerializer; @@ -65,7 +64,6 @@ import org.apache.commons.lang3.EnumUtils; @APICommand(name = "listAndSwitchSamlAccount", description = "Lists and switches to other SAML accounts owned by the SAML user", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListAndSwitchSAMLAccountCmd extends BaseCmd implements APIAuthenticator { - public static final Logger s_logger = Logger.getLogger(ListAndSwitchSAMLAccountCmd.class.getName()); @Inject ApiServerService _apiServer; @@ -83,10 +81,10 @@ public class ListAndSwitchSAMLAccountCmd extends BaseCmd implements APIAuthentic //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name = ApiConstants.USER_ID, type = CommandType.UUID, entityType = UserResponse.class, required = false, description = "User uuid") + @Parameter(name = ApiConstants.USER_ID, type = CommandType.UUID, entityType = UserResponse.class, description = "User uuid") private Long userId; - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, required = false, description = "Domain uuid") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "Domain uuid") private Long domainId; @Override @@ -133,12 +131,12 @@ public class ListAndSwitchSAMLAccountCmd extends BaseCmd implements APIAuthentic } if (userUuid != null && domainUuid != null) { - s_logger.debug("User [" + currentUserAccount.getUsername() + "] is requesting to switch from user profile [" + currentUserAccount.getId() + "] to useraccount [" + userUuid + "] in domain [" + domainUuid + "]"); + logger.debug("User [" + currentUserAccount.getUsername() + "] is requesting to switch from user profile [" + currentUserAccount.getId() + "] to useraccount [" + userUuid + "] in domain [" + domainUuid + "]"); final User user = _userDao.findByUuid(userUuid); final Domain domain = _domainDao.findByUuid(domainUuid); final UserAccount nextUserAccount = _accountService.getUserAccountById(user.getId()); if (nextUserAccount != null && !nextUserAccount.getAccountState().equals(Account.State.ENABLED.toString())) { - s_logger.warn("User [" + currentUserAccount.getUsername() + "] is requesting to switch from user profile [" + currentUserId + "] to user profile [" + userUuid + "] in domain [" + domainUuid + "] but the associated target account [" + nextUserAccount.getAccountName() + "] is not enabled"); + logger.warn("User [" + currentUserAccount.getUsername() + "] is requesting to switch from user profile [" + currentUserId + "] to user profile [" + userUuid + "] in domain [" + domainUuid + "] but the associated target account [" + nextUserAccount.getAccountName() + "] is not enabled"); throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "The requested user account is locked and cannot be switched to, please contact your administrator.", params, responseType)); @@ -149,31 +147,31 @@ public class ListAndSwitchSAMLAccountCmd extends BaseCmd implements APIAuthentic || !nextUserAccount.getExternalEntity().equals(currentUserAccount.getExternalEntity()) || (nextUserAccount.getDomainId() != domain.getId()) || (nextUserAccount.getSource() != User.Source.SAML2)) { - s_logger.warn("User [" + currentUserAccount.getUsername() + "] is requesting to switch from user profile [" + currentUserId + "] to user profile [" + userUuid + "] in domain [" + domainUuid + "] but the associated target account is not found or invalid"); + logger.warn("User [" + currentUserAccount.getUsername() + "] is requesting to switch from user profile [" + currentUserId + "] to user profile [" + userUuid + "] in domain [" + domainUuid + "] but the associated target account is not found or invalid"); throw new ServerApiException(ApiErrorCode.PARAM_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "User account is not allowed to switch to the requested account", params, responseType)); } try { if (_apiServer.verifyUser(nextUserAccount.getId())) { - s_logger.info("User [" + currentUserAccount.getUsername() + "] user profile switch is accepted: from [" + currentUserId + "] to user profile [" + userUuid + "] in domain [" + domainUuid + "] with account [" + nextUserAccount.getAccountName() + "]"); + logger.info("User [" + currentUserAccount.getUsername() + "] user profile switch is accepted: from [" + currentUserId + "] to user profile [" + userUuid + "] in domain [" + domainUuid + "] with account [" + nextUserAccount.getAccountName() + "]"); // need to set a sessoin variable to inform the login function of the specific user to login as, rather than using email only (which could have multiple matches) session.setAttribute("nextUserId", user.getId()); final LoginCmdResponse loginResponse = (LoginCmdResponse) _apiServer.loginUser(session, nextUserAccount.getUsername(), nextUserAccount.getUsername() + nextUserAccount.getSource().toString(), nextUserAccount.getDomainId(), null, remoteAddress, params); SAMLUtils.setupSamlUserCookies(loginResponse, resp); session.removeAttribute("nextUserId"); - s_logger.debug("User [" + currentUserAccount.getUsername() + "] user profile switch cookies set: from [" + currentUserId + "] to user profile [" + userUuid + "] in domain [" + domainUuid + "] with account [" + nextUserAccount.getAccountName() + "]"); + logger.debug("User [" + currentUserAccount.getUsername() + "] user profile switch cookies set: from [" + currentUserId + "] to user profile [" + userUuid + "] in domain [" + domainUuid + "] with account [" + nextUserAccount.getAccountName() + "]"); //resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value()); return ApiResponseSerializer.toSerializedString(loginResponse, responseType); } } catch (CloudAuthenticationException | IOException exception) { - s_logger.debug("User [" + currentUserAccount.getUsername() + "] user profile switch cookies set FAILED: from [" + currentUserId + "] to user profile [" + userUuid + "] in domain [" + domainUuid + "] with account [" + nextUserAccount.getAccountName() + "]", exception); + logger.debug("User [{}] user profile switch cookies set FAILED: from [{}] to user profile [{}] in domain [{}] with account [{}]", currentUserAccount.getUsername(), currentUserId, userUuid, domainUuid, nextUserAccount.getAccountName(), exception); } } else { List switchableAccounts = _userAccountDao.getAllUsersByNameAndEntity(currentUserAccount.getUsername(), currentUserAccount.getExternalEntity()); - if (switchableAccounts != null && switchableAccounts.size() > 0 && currentUserId != User.UID_SYSTEM) { - List accountResponses = new ArrayList(); + if (switchableAccounts != null && !switchableAccounts.isEmpty() && currentUserId != User.UID_SYSTEM) { + List accountResponses = new ArrayList<>(); for (UserAccountVO userAccount: switchableAccounts) { User user = _userDao.getUser(userAccount.getId()); Domain domain = _domainService.getDomain(userAccount.getDomainId()); @@ -186,11 +184,9 @@ public class ListAndSwitchSAMLAccountCmd extends BaseCmd implements APIAuthentic accountResponse.setAccountName(userAccount.getAccountName()); accountResponse.setIdpId(user.getExternalEntity()); accountResponses.add(accountResponse); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Returning available useraccount for [" + currentUserAccount.getUsername() + "]: UserUUID: [" + user.getUuid() + "], DomainUUID: [" + domain.getUuid() + "], Account: [" + userAccount.getAccountName() + "]"); - } + logger.debug("Returning available useraccount for [{}]: UserUUID: [{}], DomainUUID: [{}], Account: [{}]", currentUserAccount.getUsername(), user.getUuid(), domain.getUuid(), userAccount.getAccountName()); } - ListResponse response = new ListResponse(); + ListResponse response = new ListResponse<>(); response.setResponses(accountResponses); response.setResponseName(getCommandName()); return ApiResponseSerializer.toSerializedString(response, responseType); @@ -209,12 +205,12 @@ public class ListAndSwitchSAMLAccountCmd extends BaseCmd implements APIAuthentic @Override public void setAuthenticators(List authenticators) { for (PluggableAPIAuthenticator authManager: authenticators) { - if (authManager != null && authManager instanceof SAML2AuthManager) { + if (authManager instanceof SAML2AuthManager) { _samlAuthManager = (SAML2AuthManager) authManager; } } if (_samlAuthManager == null) { - s_logger.error("No suitable Pluggable Authentication Manager found for SAML2 listAndSwitchSamlAccount Cmd"); + logger.error("No suitable Pluggable Authentication Manager found for SAML2 listAndSwitchSamlAccount Cmd"); } } diff --git a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListIdpsCmd.java b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListIdpsCmd.java index b61eae4382a..09e5f1b6557 100644 --- a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListIdpsCmd.java +++ b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListIdpsCmd.java @@ -30,7 +30,6 @@ import org.apache.cloudstack.api.response.IdpResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.saml.SAML2AuthManager; import org.apache.cloudstack.saml.SAMLProviderMetadata; -import org.apache.log4j.Logger; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; @@ -43,7 +42,6 @@ import java.util.Map; @APICommand(name = "listIdps", description = "Returns list of discovered SAML Identity Providers", responseObject = IdpResponse.class, entityType = {}) public class ListIdpsCmd extends BaseCmd implements APIAuthenticator { - public static final Logger s_logger = Logger.getLogger(ListIdpsCmd.class.getName()); @Inject ApiServerService _apiServer; @@ -102,7 +100,7 @@ public class ListIdpsCmd extends BaseCmd implements APIAuthenticator { } } if (_samlAuthManager == null) { - s_logger.error("No suitable Pluggable Authentication Manager found for SAML2 Login Cmd"); + logger.error("No suitable Pluggable Authentication Manager found for SAML2 Login Cmd"); } } } diff --git a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListSamlAuthorizationCmd.java b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListSamlAuthorizationCmd.java index db08ae0cce8..d400fadf261 100644 --- a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListSamlAuthorizationCmd.java +++ b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/ListSamlAuthorizationCmd.java @@ -29,7 +29,6 @@ import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.SamlAuthorizationResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; -import org.apache.log4j.Logger; import javax.inject.Inject; import java.util.ArrayList; @@ -37,7 +36,6 @@ import java.util.List; @APICommand(name = "listSamlAuthorization", description = "Lists authorized users who can used SAML SSO", responseObject = SamlAuthorizationResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListSamlAuthorizationCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListSamlAuthorizationCmd.class.getName()); private static final String s_name = "listsamlauthorizationsresponse"; @Inject diff --git a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java index 0f25123ff88..bfd47922142 100644 --- a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java +++ b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java @@ -47,7 +47,6 @@ import org.apache.cloudstack.saml.SAMLProviderMetadata; import org.apache.cloudstack.saml.SAMLTokenVO; import org.apache.cloudstack.saml.SAMLUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.opensaml.DefaultBootstrap; import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.EncryptedAssertion; @@ -79,9 +78,8 @@ import com.cloud.user.UserAccountVO; import com.cloud.user.dao.UserAccountDao; import com.cloud.utils.db.EntityManager; -@APICommand(name = "samlSso", description = "SP initiated SAML Single Sign On", requestHasSensitiveInfo = true, responseObject = LoginCmdResponse.class, entityType = {}) +@APICommand(name = "samlSso", description = "SP initiated SAML Single Sign On", responseObject = LoginCmdResponse.class) public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthenticator, Configurable { - public static final Logger s_logger = Logger.getLogger(SAML2LoginAPIAuthenticatorCmd.class.getName()); private static final String s_name = "loginresponse"; ///////////////////////////////////////////////////// @@ -99,7 +97,7 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent @Inject private UserAccountDao userAccountDao; - protected static ConfigKey saml2FailedLoginRedirectUrl = new ConfigKey("Advanced", String.class, "saml2.failed.login.redirect.url", "", + protected static ConfigKey saml2FailedLoginRedirectUrl = new ConfigKey<>("Advanced", String.class, "saml2.failed.login.redirect.url", "", "The URL to redirect the SAML2 login failed message (the default vaulue is empty).", true); SAML2AuthManager samlAuthManager; @@ -139,14 +137,14 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent responseObject = SAMLUtils.decodeSAMLResponse(responseMessage); } catch (ConfigurationException | FactoryConfigurationError | ParserConfigurationException | SAXException | IOException | UnmarshallingException e) { - s_logger.error("SAMLResponse processing error: " + e.getMessage()); + logger.error("SAMLResponse processing error: " + e.getMessage()); } return responseObject; } protected void checkAndFailOnMissingSAMLSignature(Signature signature) { if (signature == null && SAML2AuthManager.SAMLCheckSignature.value()) { - s_logger.error("Failing SAML login due to missing signature in the SAML response and signature check is enforced. " + + logger.error("Failing SAML login due to missing signature in the SAML response and signature check is enforced. " + "Please check and ensure the IDP configuration has signing certificate or relax the saml2.check.signature setting."); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Signature is missing from the SAML Response. Please contact the Administrator"); } @@ -191,7 +189,7 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent } String authnId = SAMLUtils.generateSecureRandomId(); samlAuthManager.saveToken(authnId, domainPath, idpMetadata.getEntityId()); - s_logger.debug("Sending SAMLRequest id=" + authnId); + logger.debug("Sending SAMLRequest id=" + authnId); String redirectUrl = SAMLUtils.buildAuthnRequestUrl(authnId, spMetadata, idpMetadata, SAML2AuthManager.SAMLSignatureAlgorithm.value(), SAML2AuthManager.SAMLRequirePasswordLogin.value()); resp.sendRedirect(redirectUrl); return ""; @@ -209,13 +207,13 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent params, responseType)); } - String username = null; + String username; Issuer issuer = processedSAMLResponse.getIssuer(); SAMLProviderMetadata spMetadata = samlAuthManager.getSPMetadata(); SAMLProviderMetadata idpMetadata = samlAuthManager.getIdPMetadata(issuer.getValue()); String responseToId = processedSAMLResponse.getInResponseTo(); - s_logger.debug("Received SAMLResponse in response to id=" + responseToId); + logger.debug("Received SAMLResponse in response to id=" + responseToId); SAMLTokenVO token = samlAuthManager.getToken(responseToId); if (token != null) { if (!(token.getEntity().equalsIgnoreCase(issuer.getValue()))) { @@ -242,7 +240,7 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent try { validator.validate(sig); } catch (ValidationException e) { - s_logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage()); + logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage()); throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Response's signature failed to be validated by IDP signing key", params, responseType)); @@ -275,7 +273,7 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { - s_logger.warn("SAML EncryptedAssertion error: " + e.toString()); + logger.warn("SAML EncryptedAssertion error: " + e); } if (assertion == null) { continue; @@ -289,7 +287,7 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent try { validator.validate(encSig); } catch (ValidationException e) { - s_logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage()); + logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage()); throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Response's signature failed to be validated by IDP signing key", params, responseType)); @@ -312,7 +310,7 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent UserAccount userAccount = null; List possibleUserAccounts = userAccountDao.getAllUsersByNameAndEntity(username, issuer.getValue()); - if (possibleUserAccounts != null && possibleUserAccounts.size() > 0) { + if (possibleUserAccounts != null && !possibleUserAccounts.isEmpty()) { // Log into the first enabled user account // Users can switch to other allowed accounts later for (UserAccountVO possibleUserAccount : possibleUserAccounts) { @@ -334,7 +332,7 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent return ApiResponseSerializer.toSerializedString(loginResponse, responseType); } } catch (CloudAuthenticationException | IOException exception) { - s_logger.debug("SAML Login failed to log in the user due to: " + exception.getMessage()); + logger.debug("SAML Login failed to log in the user due to: " + exception.getMessage()); } } } catch (IOException e) { @@ -372,12 +370,12 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent @Override public void setAuthenticators(List authenticators) { for (PluggableAPIAuthenticator authManager: authenticators) { - if (authManager != null && authManager instanceof SAML2AuthManager) { + if (authManager instanceof SAML2AuthManager) { samlAuthManager = (SAML2AuthManager) authManager; } } if (samlAuthManager == null) { - s_logger.error("No suitable Pluggable Authentication Manager found for SAML2 Login Cmd"); + logger.error("No suitable Pluggable Authentication Manager found for SAML2 Login Cmd"); } } diff --git a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmd.java b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmd.java index ccdc4b6bd5d..ca46bef4b5a 100644 --- a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmd.java +++ b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmd.java @@ -31,7 +31,6 @@ import org.apache.cloudstack.saml.SAML2AuthManager; import org.apache.cloudstack.saml.SAMLPluginConstants; import org.apache.cloudstack.saml.SAMLProviderMetadata; import org.apache.cloudstack.saml.SAMLUtils; -import org.apache.log4j.Logger; import org.opensaml.DefaultBootstrap; import org.opensaml.saml2.core.LogoutRequest; import org.opensaml.saml2.core.Response; @@ -54,7 +53,6 @@ import java.net.InetAddress; @APICommand(name = "samlSlo", description = "SAML Global Log Out API", responseObject = LogoutCmdResponse.class, entityType = {}) public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthenticator { - public static final Logger s_logger = Logger.getLogger(SAML2LogoutAPIAuthenticatorCmd.class.getName()); private static final String s_name = "logoutresponse"; @Inject @@ -94,7 +92,7 @@ public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthen try { resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value()); } catch (IOException ignored) { - s_logger.info("[ignored] sending redirected failed.", ignored); + logger.info("[ignored] sending redirected failed.", ignored); } return responseString; } @@ -102,7 +100,7 @@ public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthen try { DefaultBootstrap.bootstrap(); } catch (ConfigurationException | FactoryConfigurationError e) { - s_logger.error("OpenSAML Bootstrapping error: " + e.getMessage()); + logger.error("OpenSAML Bootstrapping error: " + e.getMessage()); throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "OpenSAML Bootstrapping error while creating SP MetaData", params, responseType)); @@ -119,12 +117,12 @@ public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthen params, responseType)); } } catch (ConfigurationException | FactoryConfigurationError | ParserConfigurationException | SAXException | IOException | UnmarshallingException e) { - s_logger.error("SAMLResponse processing error: " + e.getMessage()); + logger.error("SAMLResponse processing error: " + e.getMessage()); } try { resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value()); } catch (IOException ignored) { - s_logger.info("[ignored] second redirected sending failed.", ignored); + logger.info("[ignored] second redirected sending failed.", ignored); } return responseString; } @@ -136,7 +134,7 @@ public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthen try { resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value()); } catch (IOException ignored) { - s_logger.info("[ignored] final redirected failed.", ignored); + logger.info("[ignored] final redirected failed.", ignored); } return responseString; } @@ -146,7 +144,7 @@ public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthen String redirectUrl = idpMetadata.getSloUrl() + "?SAMLRequest=" + SAMLUtils.encodeSAMLRequest(logoutRequest); resp.sendRedirect(redirectUrl); } catch (MarshallingException | IOException e) { - s_logger.error("SAML SLO error: " + e.getMessage()); + logger.error("SAML SLO error: " + e.getMessage()); throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Single Logout Error", params, responseType)); @@ -167,7 +165,7 @@ public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthen } } if (_samlAuthManager == null) { - s_logger.error("No suitable Pluggable Authentication Manager found for SAML2 Login Cmd"); + logger.error("No suitable Pluggable Authentication Manager found for SAML2 Login Cmd"); } } } diff --git a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAML2AuthManagerImpl.java b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAML2AuthManagerImpl.java index 92408141ef2..93b7bc5be93 100644 --- a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAML2AuthManagerImpl.java +++ b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAML2AuthManagerImpl.java @@ -57,7 +57,6 @@ import org.apache.cloudstack.framework.security.keystore.KeystoreVO; import org.apache.cloudstack.utils.security.CertUtils; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.HttpClient; -import org.apache.log4j.Logger; import org.bouncycastle.operator.OperatorCreationException; import org.opensaml.DefaultBootstrap; import org.opensaml.common.xml.SAMLConstants; @@ -92,7 +91,6 @@ import com.cloud.utils.component.AdapterBase; @Component public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManager, Configurable { - private static final Logger s_logger = Logger.getLogger(SAML2AuthManagerImpl.class); private SAMLProviderMetadata _spMetadata = new SAMLProviderMetadata(); private Map _idpMetadataMap = new HashMap(); @@ -123,10 +121,10 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage @Override public boolean start() { if (isSAMLPluginEnabled()) { - s_logger.info("SAML auth plugin loaded"); + logger.info("SAML auth plugin loaded"); return setup(); } else { - s_logger.info("SAML auth plugin not enabled so not loading"); + logger.info("SAML auth plugin not enabled so not loading"); return super.start(); } } @@ -148,9 +146,9 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage SAMLUtils.encodePrivateKey(keyPair.getPrivate()), SAMLUtils.encodePublicKey(keyPair.getPublic()), "samlsp-keypair"); keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR); - s_logger.info("No SAML keystore found, created and saved a new Service Provider keypair"); + logger.info("No SAML keystore found, created and saved a new Service Provider keypair"); } catch (final NoSuchProviderException | NoSuchAlgorithmException e) { - s_logger.error("Unable to create and save SAML keypair, due to: ", e); + logger.error("Unable to create and save SAML keypair, due to: ", e); } } @@ -179,7 +177,7 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage _ksDao.save(SAMLPluginConstants.SAMLSP_X509CERT, Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert"); bos.close(); } catch (final NoSuchAlgorithmException | NoSuchProviderException | CertificateException | SignatureException | InvalidKeyException | IOException | OperatorCreationException e) { - s_logger.error("SAML plugin won't be able to use X509 signed authentication", e); + logger.error("SAML plugin won't be able to use X509 signed authentication", e); } } else { try { @@ -188,7 +186,7 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage spX509Key = (X509Certificate) si.readObject(); bi.close(); } catch (IOException | ClassNotFoundException ignored) { - s_logger.error("SAML Plugin won't be able to use X509 signed authentication. Failed to load X509 Certificate from Database."); + logger.error("SAML Plugin won't be able to use X509 signed authentication. Failed to load X509 Certificate from Database."); } } } @@ -215,7 +213,7 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage private void addIdpToMap(EntityDescriptor descriptor, Map idpMap) { SAMLProviderMetadata idpMetadata = new SAMLProviderMetadata(); idpMetadata.setEntityId(descriptor.getEntityID()); - s_logger.debug("Adding IdP to the list of discovered IdPs: " + descriptor.getEntityID()); + logger.debug("Adding IdP to the list of discovered IdPs: " + descriptor.getEntityID()); if (descriptor.getOrganization() != null) { if (descriptor.getOrganization().getDisplayNames() != null) { for (OrganizationDisplayName orgName : descriptor.getOrganization().getDisplayNames()) { @@ -289,21 +287,21 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage try { idpMetadata.setSigningCertificate(KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0)); } catch (CertificateException ignored) { - s_logger.info("[ignored] encountered invalid certificate signing.", ignored); + logger.info("[ignored] encountered invalid certificate signing.", ignored); } } if (kd.getUse() == UsageType.ENCRYPTION) { try { idpMetadata.setEncryptionCertificate(KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0)); } catch (CertificateException ignored) { - s_logger.info("[ignored] encountered invalid certificate encryption.", ignored); + logger.info("[ignored] encountered invalid certificate encryption.", ignored); } } if (kd.getUse() == UsageType.UNSPECIFIED) { try { unspecifiedKey = KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0); } catch (CertificateException ignored) { - s_logger.info("[ignored] encountered invalid certificate.", ignored); + logger.info("[ignored] encountered invalid certificate.", ignored); } } } @@ -315,7 +313,7 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage idpMetadata.setEncryptionCertificate(unspecifiedKey); } if (idpMap.containsKey(idpMetadata.getEntityId())) { - s_logger.warn("Duplicate IdP metadata found with entity Id: " + idpMetadata.getEntityId()); + logger.warn("Duplicate IdP metadata found with entity Id: " + idpMetadata.getEntityId()); } idpMap.put(idpMetadata.getEntityId(), idpMetadata); } @@ -346,16 +344,16 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage if (_idpMetaDataProvider == null) { return; } - s_logger.debug("Starting SAML IDP Metadata Refresh Task"); + logger.debug("Starting SAML IDP Metadata Refresh Task"); Map metadataMap = new HashMap(); try { discoverAndAddIdp(_idpMetaDataProvider.getMetadata(), metadataMap); _idpMetadataMap = metadataMap; expireTokens(); - s_logger.debug("Finished refreshing SAML Metadata and expiring old auth tokens"); + logger.debug("Finished refreshing SAML Metadata and expiring old auth tokens"); } catch (MetadataProviderException e) { - s_logger.warn("SAML Metadata Refresh task failed with exception: " + e.getMessage()); + logger.warn("SAML Metadata Refresh task failed with exception: " + e.getMessage()); } } @@ -363,7 +361,7 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage private boolean setup() { if (!initSP()) { - s_logger.error("SAML Plugin failed to initialize, please fix the configuration and restart management server"); + logger.error("SAML Plugin failed to initialize, please fix the configuration and restart management server"); return false; } _timer = new Timer(); @@ -379,11 +377,11 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage } else { File metadataFile = PropertiesUtil.findConfigFile(idpMetaDataUrl); if (metadataFile == null) { - s_logger.error("Provided Metadata is not a URL, Unable to locate metadata file from local path: " + idpMetaDataUrl); + logger.error("Provided Metadata is not a URL, Unable to locate metadata file from local path: " + idpMetaDataUrl); return false; } else{ - s_logger.debug("Provided Metadata is not a URL, trying to read metadata file from local path: " + metadataFile.getAbsolutePath()); + logger.debug("Provided Metadata is not a URL, trying to read metadata file from local path: " + metadataFile.getAbsolutePath()); _idpMetaDataProvider = new FilesystemMetadataProvider(_timer, metadataFile); } } @@ -393,14 +391,14 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage _timer.scheduleAtFixedRate(new MetadataRefreshTask(), 0, _refreshInterval * 1000); } catch (MetadataProviderException e) { - s_logger.error("Unable to read SAML2 IDP MetaData URL, error:" + e.getMessage()); - s_logger.error("SAML2 Authentication may be unavailable"); + logger.error("Unable to read SAML2 IDP MetaData URL, error:" + e.getMessage()); + logger.error("SAML2 Authentication may be unavailable"); return false; } catch (ConfigurationException | FactoryConfigurationError e) { - s_logger.error("OpenSAML bootstrapping failed: error: " + e.getMessage()); + logger.error("OpenSAML bootstrapping failed: error: " + e.getMessage()); return false; } catch (NullPointerException e) { - s_logger.error("Unable to setup SAML Auth Plugin due to NullPointerException" + + logger.error("Unable to setup SAML Auth Plugin due to NullPointerException" + " please check the SAML global settings: " + e.getMessage()); return false; } @@ -478,7 +476,7 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage if (_samlTokenDao.findByUuid(authnId) == null) { _samlTokenDao.persist(token); } else { - s_logger.warn("Duplicate SAML token for entity=" + entity + " token id=" + authnId + " domain=" + domainPath); + logger.warn("Duplicate SAML token for entity=" + entity + " token id=" + authnId + " domain=" + domainPath); } } diff --git a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAML2UserAuthenticator.java b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAML2UserAuthenticator.java index 0a33bc111d5..6f9854ad17d 100644 --- a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAML2UserAuthenticator.java +++ b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAML2UserAuthenticator.java @@ -20,7 +20,6 @@ import javax.inject.Inject; import org.apache.cloudstack.auth.UserAuthenticator; import org.apache.cxf.common.util.StringUtils; -import org.apache.log4j.Logger; import com.cloud.user.User; import com.cloud.user.UserAccount; @@ -30,7 +29,6 @@ import com.cloud.utils.Pair; import com.cloud.utils.component.AdapterBase; public class SAML2UserAuthenticator extends AdapterBase implements UserAuthenticator { - public static final Logger s_logger = Logger.getLogger(SAML2UserAuthenticator.class); @Inject private UserAccountDao _userAccountDao; @@ -39,18 +37,18 @@ public class SAML2UserAuthenticator extends AdapterBase implements UserAuthentic @Override public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Trying SAML2 auth for user: " + username); + if (logger.isDebugEnabled()) { + logger.debug("Trying SAML2 auth for user: " + username); } if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { - s_logger.debug("Username or Password cannot be empty"); + logger.debug("Username or Password cannot be empty"); return new Pair(false, null); } final UserAccount userAccount = _userAccountDao.getUserAccount(username, domainId); if (userAccount == null || userAccount.getSource() != User.Source.SAML2) { - s_logger.debug("Unable to find user with " + username + " in domain " + domainId + ", or user source is not SAML2"); + logger.debug("Unable to find user with " + username + " in domain " + domainId + ", or user source is not SAML2"); return new Pair(false, null); } else { User user = _userDao.getUser(userAccount.getId()); diff --git a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAMLUtils.java b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAMLUtils.java index 2460e3826c6..1a9d677d43a 100644 --- a/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAMLUtils.java +++ b/plugins/user-authenticators/saml2/src/main/java/org/apache/cloudstack/saml/SAMLUtils.java @@ -63,7 +63,8 @@ import org.apache.cloudstack.api.response.LoginCmdResponse; import org.apache.cloudstack.utils.security.CertUtils; import org.apache.cloudstack.utils.security.ParserUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; import org.bouncycastle.operator.OperatorCreationException; import org.joda.time.DateTime; import org.opensaml.Configuration; @@ -108,7 +109,7 @@ import com.cloud.utils.HttpUtils; import com.cloud.utils.exception.CloudRuntimeException; public class SAMLUtils { - public static final Logger s_logger = Logger.getLogger(SAMLUtils.class); + protected static Logger LOGGER = LogManager.getLogger(SAMLUtils.class); static final String charset = "abcdefghijklmnopqrstuvwxyz"; @@ -128,7 +129,7 @@ public class SAMLUtils { for (Attribute attribute : attributeStatement.getAttributes()) { if (attribute.getAttributeValues() != null && attribute.getAttributeValues().size() > 0) { String value = attribute.getAttributeValues().get(0).getDOM().getTextContent(); - s_logger.debug("SAML attribute name: " + attribute.getName() + " friendly-name:" + attribute.getFriendlyName() + " value:" + value); + LOGGER.debug("SAML attribute name: " + attribute.getName() + " friendly-name:" + attribute.getFriendlyName() + " value:" + value); if (attributeKey.equals(attribute.getName()) || attributeKey.equals(attribute.getFriendlyName())) { return value; } @@ -163,7 +164,7 @@ public class SAMLUtils { String appendOperator = idpMetadata.getSsoUrl().contains("?") ? "&" : "?"; redirectUrl = idpMetadata.getSsoUrl() + appendOperator + SAMLUtils.generateSAMLRequestSignature("SAMLRequest=" + SAMLUtils.encodeSAMLRequest(authnRequest), privateKey, signatureAlgorithm); } catch (ConfigurationException | FactoryConfigurationError | MarshallingException | IOException | NoSuchAlgorithmException | InvalidKeyException | java.security.SignatureException e) { - s_logger.error("SAML AuthnRequest message building error: " + e.getMessage()); + LOGGER.error("SAML AuthnRequest message building error: " + e.getMessage()); } return redirectUrl; } @@ -320,7 +321,7 @@ public class SAMLUtils { String sameSite = ApiServlet.getApiSessionKeySameSite(); String sessionKeyCookie = String.format("%s=%s;Domain=%s;Path=%s;%s", ApiConstants.SESSIONKEY, loginResponse.getSessionKey(), domain, path, sameSite); - s_logger.debug("Adding sessionkey cookie to response: " + sessionKeyCookie); + LOGGER.debug("Adding sessionkey cookie to response: " + sessionKeyCookie); resp.addHeader("SET-COOKIE", sessionKeyCookie); resp.addHeader("SET-COOKIE", String.format("%s=%s;HttpOnly;Path=/client/api;%s", ApiConstants.SESSIONKEY, loginResponse.getSessionKey(), sameSite)); } @@ -355,7 +356,7 @@ public class SAMLUtils { X509EncodedKeySpec spec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class); return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()), Charset.forName("UTF-8")); } catch (InvalidKeySpecException e) { - s_logger.error("Unable to get KeyFactory:" + e.getMessage()); + LOGGER.error("Unable to get KeyFactory:" + e.getMessage()); } return null; } @@ -373,7 +374,7 @@ public class SAMLUtils { PKCS8EncodedKeySpec.class); return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()), Charset.forName("UTF-8")); } catch (InvalidKeySpecException e) { - s_logger.error("Unable to get KeyFactory:" + e.getMessage()); + LOGGER.error("Unable to get KeyFactory:" + e.getMessage()); } return null; } @@ -392,7 +393,7 @@ public class SAMLUtils { try { return keyFactory.generatePublic(x509KeySpec); } catch (InvalidKeySpecException e) { - s_logger.error("Unable to create PublicKey from PublicKey string:" + e.getMessage()); + LOGGER.error("Unable to create PublicKey from PublicKey string:" + e.getMessage()); } return null; } @@ -411,7 +412,7 @@ public class SAMLUtils { try { return keyFactory.generatePrivate(pkscs8KeySpec); } catch (InvalidKeySpecException e) { - s_logger.error("Unable to create PrivateKey from privateKey string:" + e.getMessage()); + LOGGER.error("Unable to create PrivateKey from privateKey string:" + e.getMessage()); } return null; } diff --git a/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/GetServiceProviderMetaDataCmdTest.java b/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/GetServiceProviderMetaDataCmdTest.java index 3df0fccadfa..2cddb126b1b 100644 --- a/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/GetServiceProviderMetaDataCmdTest.java +++ b/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/GetServiceProviderMetaDataCmdTest.java @@ -40,7 +40,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.cloud.utils.HttpUtils; diff --git a/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/SAML2AuthManagerImplTest.java b/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/SAML2AuthManagerImplTest.java index 94bf3f06696..81594db1009 100644 --- a/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/SAML2AuthManagerImplTest.java +++ b/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/SAML2AuthManagerImplTest.java @@ -30,7 +30,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.cloud.user.DomainManager; import com.cloud.user.User; diff --git a/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/api/command/ListAndSwitchSAMLAccountCmdTest.java b/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/api/command/ListAndSwitchSAMLAccountCmdTest.java index bfee28a7e3b..afc2f82b206 100644 --- a/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/api/command/ListAndSwitchSAMLAccountCmdTest.java +++ b/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/api/command/ListAndSwitchSAMLAccountCmdTest.java @@ -45,7 +45,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; diff --git a/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmdTest.java b/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmdTest.java index 09391c5d7d2..2060d0baf31 100644 --- a/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmdTest.java +++ b/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmdTest.java @@ -37,7 +37,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.cloud.utils.HttpUtils; diff --git a/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/saml/SAML2AuthManagerImplTest.java b/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/saml/SAML2AuthManagerImplTest.java index 073face6e2e..0a2955be04d 100755 --- a/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/saml/SAML2AuthManagerImplTest.java +++ b/plugins/user-authenticators/saml2/src/test/java/org/apache/cloudstack/saml/SAML2AuthManagerImplTest.java @@ -25,7 +25,7 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.doReturn; diff --git a/plugins/user-authenticators/sha256salted/pom.xml b/plugins/user-authenticators/sha256salted/pom.xml index cc83cfb6ae2..3717cd1482a 100644 --- a/plugins/user-authenticators/sha256salted/pom.xml +++ b/plugins/user-authenticators/sha256salted/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT ../../pom.xml diff --git a/plugins/user-authenticators/sha256salted/src/main/java/org/apache/cloudstack/auth/SHA256SaltedUserAuthenticator.java b/plugins/user-authenticators/sha256salted/src/main/java/org/apache/cloudstack/auth/SHA256SaltedUserAuthenticator.java index c6bdbe672fa..0dbdf26f438 100644 --- a/plugins/user-authenticators/sha256salted/src/main/java/org/apache/cloudstack/auth/SHA256SaltedUserAuthenticator.java +++ b/plugins/user-authenticators/sha256salted/src/main/java/org/apache/cloudstack/auth/SHA256SaltedUserAuthenticator.java @@ -25,7 +25,6 @@ import java.util.Map; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import org.bouncycastle.util.encoders.Base64; import com.cloud.user.UserAccount; @@ -35,7 +34,6 @@ import com.cloud.utils.component.AdapterBase; import com.cloud.utils.exception.CloudRuntimeException; public class SHA256SaltedUserAuthenticator extends AdapterBase implements UserAuthenticator { - public static final Logger s_logger = Logger.getLogger(SHA256SaltedUserAuthenticator.class); private static final String s_defaultPassword = "000000000000000000000000000="; private static final String s_defaultSalt = "0000000000000000000000000000000="; @Inject @@ -47,19 +45,19 @@ public class SHA256SaltedUserAuthenticator extends AdapterBase implements UserAu */ @Override public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Retrieving user: " + username); + if (logger.isDebugEnabled()) { + logger.debug("Retrieving user: " + username); } if (StringUtils.isAnyEmpty(username, password)) { - s_logger.debug("Username or Password cannot be empty"); + logger.debug("Username or Password cannot be empty"); return new Pair<>(false, null); } boolean realUser = true; UserAccount user = _userAccountDao.getUserAccount(username, domainId); if (user == null) { - s_logger.debug("Unable to find user with " + username + " in domain " + domainId); + logger.debug("Unable to find user with " + username + " in domain " + domainId); realUser = false; } /* Fake Data */ @@ -68,7 +66,7 @@ public class SHA256SaltedUserAuthenticator extends AdapterBase implements UserAu if (realUser) { String[] storedPassword = user.getPassword().split(":"); if (storedPassword.length != 2) { - s_logger.warn("The stored password for " + username + " isn't in the right format for this authenticator"); + logger.warn("The stored password for " + username + " isn't in the right format for this authenticator"); realUser = false; } else { realPassword = storedPassword[1]; diff --git a/plugins/user-authenticators/sha256salted/src/main/resources/META-INF/cloudstack/sha256salted/spring-sha256salted-context.xml b/plugins/user-authenticators/sha256salted/src/main/resources/META-INF/cloudstack/sha256salted/spring-sha256salted-context.xml index 3e29fd9ddba..593c8282cb5 100644 --- a/plugins/user-authenticators/sha256salted/src/main/resources/META-INF/cloudstack/sha256salted/spring-sha256salted-context.xml +++ b/plugins/user-authenticators/sha256salted/src/main/resources/META-INF/cloudstack/sha256salted/spring-sha256salted-context.xml @@ -30,5 +30,5 @@ - + diff --git a/plugins/user-authenticators/sha256salted/src/test/java/org/apache/cloudstack/auth/test/AuthenticatorTest.java b/plugins/user-authenticators/sha256salted/src/test/java/org/apache/cloudstack/auth/test/AuthenticatorTest.java index 7a3af9d19d4..5f7d9105856 100644 --- a/plugins/user-authenticators/sha256salted/src/test/java/org/apache/cloudstack/auth/test/AuthenticatorTest.java +++ b/plugins/user-authenticators/sha256salted/src/test/java/org/apache/cloudstack/auth/test/AuthenticatorTest.java @@ -36,7 +36,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; diff --git a/plugins/user-two-factor-authenticators/static-pin/pom.xml b/plugins/user-two-factor-authenticators/static-pin/pom.xml index d6a1eeb7e3f..422eee6cda4 100644 --- a/plugins/user-two-factor-authenticators/static-pin/pom.xml +++ b/plugins/user-two-factor-authenticators/static-pin/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT ../../pom.xml diff --git a/plugins/user-two-factor-authenticators/static-pin/src/main/java/org/apache/cloudstack/auth/StaticPinUserTwoFactorAuthenticator.java b/plugins/user-two-factor-authenticators/static-pin/src/main/java/org/apache/cloudstack/auth/StaticPinUserTwoFactorAuthenticator.java index dd1b1580c35..b781f326520 100644 --- a/plugins/user-two-factor-authenticators/static-pin/src/main/java/org/apache/cloudstack/auth/StaticPinUserTwoFactorAuthenticator.java +++ b/plugins/user-two-factor-authenticators/static-pin/src/main/java/org/apache/cloudstack/auth/StaticPinUserTwoFactorAuthenticator.java @@ -21,7 +21,6 @@ import com.cloud.exception.CloudTwoFactorAuthenticationException; import com.cloud.user.UserAccount; import com.cloud.utils.exception.CloudRuntimeException; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.user.dao.UserAccountDao; import com.cloud.utils.component.AdapterBase; @@ -29,7 +28,6 @@ import com.cloud.utils.component.AdapterBase; import java.security.SecureRandom; public class StaticPinUserTwoFactorAuthenticator extends AdapterBase implements UserTwoFactorAuthenticator { - public static final Logger s_logger = Logger.getLogger(StaticPinUserTwoFactorAuthenticator.class); @Inject private UserAccountDao _userAccountDao; @@ -48,7 +46,7 @@ public class StaticPinUserTwoFactorAuthenticator extends AdapterBase implements public void check2FA(String code, UserAccount userAccount) throws CloudTwoFactorAuthenticationException { String expectedCode = getStaticPin(userAccount); if (expectedCode.equals(code)) { - s_logger.info("2FA matches user's input"); + logger.info("2FA matches user's input"); return; } throw new CloudTwoFactorAuthenticationException("two-factor authentication code provided is invalid"); diff --git a/plugins/user-two-factor-authenticators/static-pin/src/main/resources/META-INF/cloudstack/staticpin/spring-staticpin-context.xml b/plugins/user-two-factor-authenticators/static-pin/src/main/resources/META-INF/cloudstack/staticpin/spring-staticpin-context.xml index ac27ba527db..6b30a98ef07 100644 --- a/plugins/user-two-factor-authenticators/static-pin/src/main/resources/META-INF/cloudstack/staticpin/spring-staticpin-context.xml +++ b/plugins/user-two-factor-authenticators/static-pin/src/main/resources/META-INF/cloudstack/staticpin/spring-staticpin-context.xml @@ -31,5 +31,5 @@ - + diff --git a/plugins/user-two-factor-authenticators/totp/pom.xml b/plugins/user-two-factor-authenticators/totp/pom.xml index 96a93370a93..b4d5fd2c761 100644 --- a/plugins/user-two-factor-authenticators/totp/pom.xml +++ b/plugins/user-two-factor-authenticators/totp/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT ../../pom.xml diff --git a/plugins/user-two-factor-authenticators/totp/src/main/java/org/apache/cloudstack/auth/TotpUserTwoFactorAuthenticator.java b/plugins/user-two-factor-authenticators/totp/src/main/java/org/apache/cloudstack/auth/TotpUserTwoFactorAuthenticator.java index bb6939ad14f..b722bd14393 100644 --- a/plugins/user-two-factor-authenticators/totp/src/main/java/org/apache/cloudstack/auth/TotpUserTwoFactorAuthenticator.java +++ b/plugins/user-two-factor-authenticators/totp/src/main/java/org/apache/cloudstack/auth/TotpUserTwoFactorAuthenticator.java @@ -26,7 +26,6 @@ import com.cloud.user.UserAccount; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; import com.cloud.user.dao.UserAccountDao; import com.cloud.utils.component.AdapterBase; @@ -34,7 +33,6 @@ import com.cloud.utils.component.AdapterBase; import java.security.SecureRandom; public class TotpUserTwoFactorAuthenticator extends AdapterBase implements UserTwoFactorAuthenticator { - public static final Logger s_logger = Logger.getLogger(TotpUserTwoFactorAuthenticator.class); @Inject private UserAccountDao _userAccountDao; @@ -53,10 +51,12 @@ public class TotpUserTwoFactorAuthenticator extends AdapterBase implements UserT public void check2FA(String code, UserAccount userAccount) throws CloudTwoFactorAuthenticationException { String expectedCode = get2FACode(get2FAKey(userAccount)); if (expectedCode.equals(code)) { - s_logger.info("2FA matches user's input"); + logger.info("2FA matches user's input"); return; } - throw new CloudTwoFactorAuthenticationException("two-factor authentication code provided is invalid"); + String msg = "two-factor authentication code provided is invalid"; + logger.error(msg); + throw new CloudTwoFactorAuthenticationException(msg); } private String get2FAKey(UserAccount userAccount) { diff --git a/plugins/user-two-factor-authenticators/totp/src/main/resources/META-INF/cloudstack/totp/spring-google-context.xml b/plugins/user-two-factor-authenticators/totp/src/main/resources/META-INF/cloudstack/totp/spring-google-context.xml index 84a0b0cfcb7..73ab7b636d4 100644 --- a/plugins/user-two-factor-authenticators/totp/src/main/resources/META-INF/cloudstack/totp/spring-google-context.xml +++ b/plugins/user-two-factor-authenticators/totp/src/main/resources/META-INF/cloudstack/totp/spring-google-context.xml @@ -31,5 +31,5 @@ - + diff --git a/pom.xml b/pom.xml index 22741ca2fe5..b51ed12fded 100644 --- a/pom.xml +++ b/pom.xml @@ -29,7 +29,7 @@ org.apache.cloudstack cloudstack - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT pom Apache CloudStack Apache CloudStack is an IaaS ("Infrastructure as a Service") cloud orchestration platform. @@ -50,7 +50,7 @@ UTF-8 UTF-8 https://download.cloudstack.org/systemvm - 4.19.1.0 + 4.20.2.0 apache https://sonarcloud.io @@ -58,7 +58,7 @@ 11 target build/replace.properties - -Djava.security.egd=file:/dev/./urandom -noverify + -Djava.security.egd=file:/dev/./urandom -noverify --add-opens=java.base/java.lang=ALL-UNNAMED --add-exports=java.base/sun.security.x509=ALL-UNNAMED --add-opens=java.base/javax.net.ssl=ALL-UNNAMED 1.8 @@ -79,17 +79,18 @@ 3.8.2 2.22.2 4.4.1 + 3.2.0 + 2.19.0 1.2.25 1.2.17 - 1.1.1 1.15 1.5.0 4.4 - 1.21 + 1.26.0 1.3 1.4 3.1 @@ -101,6 +102,7 @@ 1.10 1.3.3 2.9.0 + 5.1.0 0.5 2.6 2.9.0 @@ -114,7 +116,7 @@ 1.13.1 5.9.1 18.0 - 3.12.4 + 4.11.0 1.0-20081010.060147 1.0.1 7.1.0 @@ -137,6 +139,7 @@ 3.2.14 2.6.11 0.0.27 + 3.0.2 1.42.3 2.4.17 1.7.2 @@ -151,9 +154,11 @@ 3.1.1 1.3.2 2.3.0 - 2.3.2-1 + 2.3.9 + 2.3.3 + 2.3.7 2.26 - 9.4.51.v20230217 + 9.4.58.v20250814 9.4.27.v20200227 5.5.0 2.12.5 @@ -164,6 +169,7 @@ 2.7.0 0.5.3 1.5.0-b01 + 0.9.14 8.0.33 2.0.4 10.1 @@ -178,12 +184,12 @@ build-217-jenkins-27 8.0 0.5.0 - 6.2.0-3.1 + 8.1.0 3.1.3 1.4.20 5.3.26 0.5.4 - 1.12.0 + 3.1.7 @@ -360,6 +366,7 @@ commons-daemon ${cs.daemon.version}
+ org.apache.commons commons-dbcp2 @@ -371,6 +378,11 @@ + + com.zaxxer + HikariCP + ${cs.hikaricp.version} + commons-discovery commons-discovery @@ -436,6 +448,27 @@ jstl ${cs.jstl.version} + + org.apache.logging.log4j + log4j-core + ${cs.log4j.version} + + + org.apache.logging.log4j + log4j-api + ${cs.log4j.version} + + + ch.qos.reload4j + reload4j + ${cs.reload4j.version} + + + mysql + mysql-connector-java + ${cs.mysql.version} + test + log4j apache-log4j-extras @@ -447,11 +480,6 @@ - - ch.qos.reload4j - reload4j - ${cs.reload4j.version} - com.mysql mysql-connector-j @@ -717,7 +745,7 @@ org.mockito - mockito-core + mockito-inline ${cs.mockito.version} test @@ -756,6 +784,11 @@ javax.inject 1 + + com.github.ben-manes.caffeine + caffeine + ${cs.caffeine.version} +
@@ -921,20 +954,6 @@ - - - org.codehaus.gmaven - gmaven-plugin - [1.3,) - - compile - testCompile - - - - - - org.apache.maven.plugins @@ -1001,6 +1020,7 @@ .idea/ .metadata/** .git/** + .github/linters/codespell.txt .gitignore CHANGES.md CONTRIBUTING.md @@ -1030,6 +1050,7 @@ systemvm/agent/js/jquery.js systemvm/agent/js/jquery.flot.navigate.js systemvm/agent/noVNC/** + systemvm/agent/packages/** systemvm/debian/** test/integration/component/test_host_ha.sh test/systemvm/README.md diff --git a/python/distro/centos/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in b/python/distro/centos/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in index 4944fc0218e..546ec1cff77 100755 --- a/python/distro/centos/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in +++ b/python/distro/centos/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in @@ -6,9 +6,9 @@ # to you 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 diff --git a/python/distro/fedora/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in b/python/distro/fedora/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in index 28d5a115914..6811c2191c7 100755 --- a/python/distro/fedora/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in +++ b/python/distro/fedora/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in @@ -6,9 +6,9 @@ # to you 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 diff --git a/python/distro/opensuse/SYSCONFDIR/init.d/cloud-ipallocator.in b/python/distro/opensuse/SYSCONFDIR/init.d/cloud-ipallocator.in index de68534f2e4..9d201a2a13e 100755 --- a/python/distro/opensuse/SYSCONFDIR/init.d/cloud-ipallocator.in +++ b/python/distro/opensuse/SYSCONFDIR/init.d/cloud-ipallocator.in @@ -6,9 +6,9 @@ # to you 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 diff --git a/python/distro/rhel/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in b/python/distro/rhel/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in index 28d5a115914..6811c2191c7 100644 --- a/python/distro/rhel/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in +++ b/python/distro/rhel/SYSCONFDIR/rc.d/init.d/cloud-ipallocator.in @@ -6,9 +6,9 @@ # to you 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 diff --git a/python/distro/sles/SYSCONFDIR/init.d/cloud-ipallocator.in b/python/distro/sles/SYSCONFDIR/init.d/cloud-ipallocator.in index de68534f2e4..9d201a2a13e 100755 --- a/python/distro/sles/SYSCONFDIR/init.d/cloud-ipallocator.in +++ b/python/distro/sles/SYSCONFDIR/init.d/cloud-ipallocator.in @@ -6,9 +6,9 @@ # to you 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 diff --git a/python/distro/ubuntu/SYSCONFDIR/init.d/cloud-ipallocator.in b/python/distro/ubuntu/SYSCONFDIR/init.d/cloud-ipallocator.in index 4acb11a1f4f..f9a855b26d1 100755 --- a/python/distro/ubuntu/SYSCONFDIR/init.d/cloud-ipallocator.in +++ b/python/distro/ubuntu/SYSCONFDIR/init.d/cloud-ipallocator.in @@ -6,9 +6,9 @@ # to you 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 @@ -52,7 +52,7 @@ start() { log_end_msg 1 exit 1 fi - + if start-stop-daemon --start --quiet \ --pidfile "$PIDFILE" \ --exec "$DAEMONIZE" -- -n "$SHORTNAME" -p "$PIDFILE" -l "$LOGFILE" "$PROG" $OPTIONS diff --git a/python/lib/cloud_utils.py b/python/lib/cloud_utils.py index d424bf1f023..16d9f17e8b4 100644 --- a/python/lib/cloud_utils.py +++ b/python/lib/cloud_utils.py @@ -375,7 +375,7 @@ def list_zonespods(host): x = [ (zonename,podname) for pod in dom.childNodes[0].childNodes for podname in [ x.childNodes[0].wholeText for x in pod.childNodes if x.tagName == "name" ] - for zonename in [ x.childNodes[0].wholeText for x in pod.childNodes if x.tagName == "zonename" ] + for zonename in [ x.childNodes[0].wholeText for x in pod.childNodes if x.tagName == "zonename" ] ] return x @@ -433,7 +433,7 @@ def setup_agent_config(configfile, host, zone, pod, cluster, guid, pubNic, prvNi if guid != None: confopts['guid'] = guid else: - if not "guid" in confopts: + if "guid" not in confopts: stderr("Generating GUID for this Agent") confopts['guid'] = uuidgen().stdout.strip() @@ -491,7 +491,7 @@ def setup_consoleproxy_config(configfile, host, zone, pod): confopts = dict([ m.split("=",1) for m in lines if "=" in m and not m.startswith("#") ]) confposes = dict([ (m.split("=",1)[0],n) for n,m in enumerate(lines) if "=" in m and not m.startswith("#") ]) - if not "guid" in confopts: + if "guid" not in confopts: stderr("Generating GUID for this Console Proxy") confopts['guid'] = uuidgen().stdout.strip() diff --git a/python/lib/cloudutils/configFileOps.py b/python/lib/cloudutils/configFileOps.py index 41e9c7a1e8e..f4d704af783 100644 --- a/python/lib/cloudutils/configFileOps.py +++ b/python/lib/cloudutils/configFileOps.py @@ -63,19 +63,19 @@ class configFileOps: newLines = [] if os.path.exists(self.fileName) and os.path.isfile(self.fileName): fp = open(self.fileName, "r") - for line in fp.readlines(): + for line in fp.readlines(): matched = False for entry in self.entries: if entry.op == "add": if entry.separator == "=": - matchString = "^\ *" + entry.name + ".*" + matchString = r"^\ *" + entry.name + ".*" elif entry.separator == " ": - matchString = "^\ *" + entry.name + "\ *" + entry.value + matchString = r"^\ *" + entry.name + r"\ *" + entry.value else: if entry.separator == "=": - matchString = "^\ *" + entry.name + "\ *=\ *" + entry.value + matchString = r"^\ *" + entry.name + r"\ *=\ *" + entry.value else: - matchString = "^\ *" + entry.name + "\ *" + entry.value + matchString = r"^\ *" + entry.name + r"\ *" + entry.value match = re.match(matchString, line) if match is not None: diff --git a/python/lib/cloudutils/networkConfig.py b/python/lib/cloudutils/networkConfig.py index ac51f92aa58..827664bbc73 100644 --- a/python/lib/cloudutils/networkConfig.py +++ b/python/lib/cloudutils/networkConfig.py @@ -45,8 +45,11 @@ class networkConfig: if not cmd.isSuccess(): logging.debug("Failed to get default route") raise CloudRuntimeException("Failed to get default route") - - result = cmd.getStdout().split(" ") + output = cmd.getStdout().strip() + result = output.split(" ") + if len(result) < 2: + logging.debug("Output for the default route incomplete: %s. It should have been ' '" % output) + raise CloudRuntimeException("Output for the default route incomplete") gateway = result[0] dev = result[1] @@ -150,10 +153,10 @@ class networkConfig: if line.find("HWaddr") != -1: macAddr = line.split("HWaddr ")[1].strip(" ") elif line.find("inet ") != -1: - m = re.search("addr:(.*)\ *Bcast:(.*)\ *Mask:(.*)", line) + m = re.search(r"addr:([^\s]+)\s*Bcast:([^\s]+)\s*Mask:([^\s]+)", line) if m is not None: - ipAddr = m.group(1).rstrip(" ") - netmask = m.group(3).rstrip(" ") + ipAddr = m.group(1).strip() + netmask = m.group(3).strip() if networkConfig.isBridgePort(dev): type = "brport" diff --git a/python/lib/cloudutils/syscfg.py b/python/lib/cloudutils/syscfg.py index 19032ce4aff..78cd58bfbd4 100755 --- a/python/lib/cloudutils/syscfg.py +++ b/python/lib/cloudutils/syscfg.py @@ -39,11 +39,11 @@ class sysConfigAgentFactory: return sysConfigAgentUbuntu(glbEnv) elif distribution == "CentOS" or distribution == "RHEL5": return sysConfigEL5(glbEnv) - elif distribution == "Fedora" or distribution == "RHEL6": + elif distribution == "RHEL6": return sysConfigEL6(glbEnv) elif distribution == "RHEL7": return sysConfigEL7(glbEnv) - elif distribution in ["RHEL8", "RHEL9"]: + elif distribution in ["Fedora", "RHEL8", "RHEL9", "RHEL10"]: return sysConfigEL(glbEnv) elif distribution == "SUSE": return sysConfigSUSE(glbEnv) @@ -114,7 +114,7 @@ class sysConfigAgent(sysConfig): pass if size != -1 and size < (30 * 1024 * 1024): - raise CloudRuntimeException("Need at least 30G free disk space under /var/lib/libvirt/images") + raise CloudRuntimeException("Need at least 30G free disk space under /var/lib/libvirt/images") #check memory mem = -1 @@ -124,7 +124,7 @@ class sysConfigAgent(sysConfig): pass if mem != -1 and mem < 1: - raise CloudRuntimeException("Need at least 1G memory") + raise CloudRuntimeException("Need at least 1G memory") if os.geteuid() != 0: @@ -183,9 +183,10 @@ class sysConfigEL5(sysConfigAgentRedhatBase): networkConfigRedhat(self), libvirtConfigRedhat(self), firewallConfigAgent(self), + nfsConfig(self), cloudAgentConfig(self)] -#it covers RHEL6/Fedora13/Fedora14 +#it covers RHEL6 class sysConfigEL6(sysConfigAgentRedhatBase): def __init__(self, glbEnv): super(sysConfigEL6, self).__init__(glbEnv) diff --git a/python/lib/cloudutils/utilities.py b/python/lib/cloudutils/utilities.py index 5a6114f1011..95044de5558 100755 --- a/python/lib/cloudutils/utilities.py +++ b/python/lib/cloudutils/utilities.py @@ -47,11 +47,11 @@ class bash: alarm(0) except Alarm: os.kill(self.process.pid, SIGKILL) - raise CloudRuntimeException("Timeout during command execution") + raise CloudRuntimeException("Timeout during command execution") self.success = self.process.returncode == 0 except: - raise CloudRuntimeException(formatExceptionInfo()) + raise CloudRuntimeException(formatExceptionInfo()) if not self.success: logging.debug("Failed to execute:" + self.getErrMsg()) @@ -63,7 +63,7 @@ class bash: return self.stdout.decode('utf-8').strip('\n') def getLines(self): - return self.stdout.decode('utf-8').strip('\n') + return self.stdout.decode('utf-8').strip('\n').split('\n') def getStderr(self): return self.stderr.decode('utf-8').strip('\n') @@ -124,6 +124,10 @@ class Distribution: version.find("Red Hat Enterprise Linux release 9") != -1 or version.find("Linux release 9.") != -1 or version.find("Linux release 9") != -1): self.distro = "RHEL9" + elif (version.find("Red Hat Enterprise Linux Server release 10") != -1 or version.find("Scientific Linux release 10") != -1 or + version.find("Red Hat Enterprise Linux release 10") != -1 or version.find("Linux release 10.") != -1 or + version.find("Linux release 10") != -1): + self.distro = "RHEL10" elif version.find("CentOS") != -1: self.distro = "CentOS" else: diff --git a/quickcloud/pom.xml b/quickcloud/pom.xml index 6909656a6e3..218621ebb86 100644 --- a/quickcloud/pom.xml +++ b/quickcloud/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack - 4.19.4.0-SNAPSHOT + 4.20.3.0-SNAPSHOT ../pom.xml diff --git a/quickcloud/src/main/resources/META-INF/cloudstack/core/spring-quickcloud-core-context-override.xml b/quickcloud/src/main/resources/META-INF/cloudstack/core/spring-quickcloud-core-context-override.xml index 6074ea1ceb2..a434bbe2412 100644 --- a/quickcloud/src/main/resources/META-INF/cloudstack/core/spring-quickcloud-core-context-override.xml +++ b/quickcloud/src/main/resources/META-INF/cloudstack/core/spring-quickcloud-core-context-override.xml @@ -25,7 +25,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" - > + > diff --git a/scripts/installer/cloudstack-help-text b/scripts/installer/cloudstack-help-text index 1231464aa56..fbb2f0f0a7e 100755 --- a/scripts/installer/cloudstack-help-text +++ b/scripts/installer/cloudstack-help-text @@ -40,4 +40,10 @@ printf " * Release notes: https://docs.cloudstack.apache.org/en/${ACL_MINO printf " * Join mailing lists: https://cloudstack.apache.org/mailing-lists.html\n" printf " * Take the survey: https://cloudstack.apache.org/survey.html\n" printf " * Report issues: https://github.com/apache/cloudstack/issues/new\n" + +if [ "$1" = "management" ];then + printf "\nSince Apache CloudStack 4.20.0.0, the System VMs and virtual routers require at least 512 MiB memory, please check the System Offerings." + printf "\nMore information can be found at https://docs.cloudstack.apache.org/en/${ACL_MINOR_VERSION:-latest}/upgrading/upgrade/_sysvm_restart.html\n" +fi + printf "\n" diff --git a/scripts/installer/createtmplt.sh b/scripts/installer/createtmplt.sh index 2d164304604..db3cfd71ee1 100755 --- a/scripts/installer/createtmplt.sh +++ b/scripts/installer/createtmplt.sh @@ -6,9 +6,9 @@ # to you 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 @@ -51,7 +51,7 @@ verify_cksum() { esac echo "$1 $2" | $digestalgo -c --status #printf "$1\t$2" | $digestalgo -c --status - if [ $? -gt 0 ] + if [ $? -gt 0 ] then printf "Checksum failed, not proceeding with install\n" exit 3 @@ -92,12 +92,12 @@ uncompress() { ;; esac - if [ $? -gt 0 ] + if [ $? -gt 0 ] then printf "Failed to uncompress file, exiting " - exit 1 + exit 1 fi - + mv $tmpfile $imgfile printf "$imgfile" @@ -184,10 +184,10 @@ then tmpltfs=${tmpltfs:1} fi -if [ ! -d /$tmpltfs ] +if [ ! -d /$tmpltfs ] then zfs create -p $tmpltfs - if [ $? -gt 0 ] + if [ $? -gt 0 ] then printf "Failed to create user fs $tmpltfs\n" >&2 exit 1 @@ -203,7 +203,7 @@ fi tmpltimg2=$(uncompress $tmpltimg) tmpltimg2=$(untar $tmpltimg2 /$tmpltfs vmi-root) -if [ ! -f $tmpltimg2 ] +if [ ! -f $tmpltimg2 ] then rollback_if_needed $tmpltfs 2 "root disk file $tmpltimg doesn't exist\n" exit 3 @@ -217,15 +217,15 @@ fi #determine source file size -- it needs to be less than or equal to volsize imgsize=$(ls -lh $tmpltimg2| awk -F" " '{print $5}') -if [ ${imgsize:(-1)} == G ] +if [ ${imgsize:(-1)} == G ] then - imgsize=${imgsize%G} #strip out the G + imgsize=${imgsize%G} #strip out the G imgsize=${imgsize%.*} #...and any decimal part let imgsize=imgsize+1 # add 1 to compensate for decimal part volsizetmp=${volsize%G} if [ $volsizetmp -lt $imgsize ] then - volsize=${imgsize}G + volsize=${imgsize}G fi fi @@ -234,11 +234,11 @@ tgtfile=${tmpltfs}/vmi-root-${tmpltname} create_from_file $tmpltfs $tmpltimg2 $tgtfile $volsize $cleanup tmpltswap=$(ls -lh /$tmpltfs | grep swap) -if [ $? -eq 0 ] +if [ $? -eq 0 ] then swapsize=$(echo $tmpltswap | awk '{print $5}') tmpltswap=$(echo $tmpltswap | awk '{print $NF}') - tmpltswap=/${tmpltfs}/${tmpltswap} + tmpltswap=/${tmpltfs}/${tmpltswap} tgtfile=${tmpltfs}/vmi-swap-${tmpltname} create_from_file $tmpltfs $tmpltswap $tgtfile $swapsize $cleanup fi diff --git a/scripts/installer/createvolume.sh b/scripts/installer/createvolume.sh index 15847c52375..52792e9fc3a 100755 --- a/scripts/installer/createvolume.sh +++ b/scripts/installer/createvolume.sh @@ -6,9 +6,9 @@ # to you 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 @@ -93,12 +93,12 @@ uncompress() { ;; esac - if [ $? -gt 0 ] + if [ $? -gt 0 ] then printf "Failed to uncompress file, exiting " - exit 1 + exit 1 fi - + mv $tmpfile $imgfile printf "$imgfile" @@ -185,10 +185,10 @@ then volfs=${volfs:1} fi -if [ ! -d /$volfs ] +if [ ! -d /$volfs ] then zfs create -p $volfs - if [ $? -gt 0 ] + if [ $? -gt 0 ] then printf "Failed to create user fs $volfs\n" >&2 exit 1 @@ -204,7 +204,7 @@ fi volimg2=$(uncompress $volimg) volimg2=$(untar $volimg2 /$volfs vmi-root) -if [ ! -f $volimg2 ] +if [ ! -f $volimg2 ] then rollback_if_needed $volfs 2 "root disk file $volimg doesn't exist\n" exit 3 @@ -218,15 +218,15 @@ fi #determine source file size -- it needs to be less than or equal to volsize imgsize=$(ls -lh $volimg2| awk -F" " '{print $5}') -if [ ${imgsize:(-1)} == G ] +if [ ${imgsize:(-1)} == G ] then - imgsize=${imgsize%G} #strip out the G + imgsize=${imgsize%G} #strip out the G imgsize=${imgsize%.*} #...and any decimal part let imgsize=imgsize+1 # add 1 to compensate for decimal part volsizetmp=${volsize%G} if [ $volsizetmp -lt $imgsize ] then - volsize=${imgsize}G + volsize=${imgsize}G fi fi @@ -235,11 +235,11 @@ tgtfile=${volfs}/vmi-root-${volname} create_from_file $volfs $volimg2 $tgtfile $volsize $cleanup volswap=$(ls -lh /$volfs | grep swap) -if [ $? -eq 0 ] +if [ $? -eq 0 ] then swapsize=$(echo $volswap | awk '{print $5}') volswap=$(echo $volswap | awk '{print $NF}') - volswap=/${volfs}/${volswap} + volswap=/${volfs}/${volswap} tgtfile=${volfs}/vmi-swap-${volname} create_from_file $volfs $volswap $tgtfile $swapsize $cleanup fi diff --git a/scripts/installer/installcentos.sh b/scripts/installer/installcentos.sh index e68e0577a8e..b16fadce048 100755 --- a/scripts/installer/installcentos.sh +++ b/scripts/installer/installcentos.sh @@ -6,9 +6,9 @@ # to you 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 @@ -38,7 +38,7 @@ do ;; c) cflag=1 create_tmplt_path="$OPTARG" - ;; + ;; ?) usage exit 2 ;; @@ -47,14 +47,14 @@ done shift $(($OPTIND - 1)) -if [ "$tflag" != "1" ] || [ "$cflag" != "1" ] +if [ "$tflag" != "1" ] || [ "$cflag" != "1" ] then usage exit 2 fi tmpltfs=$template_location/public/os/centos53-x86_64 -if [ "$fflag" == "1" ] +if [ "$fflag" == "1" ] then zfs destroy -Rr $tmpltfs 2> /dev/null fi diff --git a/scripts/installer/installdomp.sh b/scripts/installer/installdomp.sh index 79ea9fda45c..9c7ab72139e 100755 --- a/scripts/installer/installdomp.sh +++ b/scripts/installer/installdomp.sh @@ -6,9 +6,9 @@ # to you 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 @@ -47,7 +47,7 @@ then fi tmpltfs=$1/private/u000000/os/consoleproxy -if [ "$fflag" == "1" ] +if [ "$fflag" == "1" ] then zfs destroy -r $tmpltfs 2> /dev/null fi diff --git a/scripts/installer/run_installer.sh b/scripts/installer/run_installer.sh index 8452e3773cb..3a96c797540 100755 --- a/scripts/installer/run_installer.sh +++ b/scripts/installer/run_installer.sh @@ -6,9 +6,9 @@ # to you 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 @@ -32,7 +32,7 @@ then fi if [ "$VMOPS_HOME" == "" ] -then +then VMOPS_HOME="/usr/local/vmops" fi diff --git a/scripts/network/domr/router_proxy.sh b/scripts/network/domr/router_proxy.sh index 945ca968d26..550ec6de91d 100755 --- a/scripts/network/domr/router_proxy.sh +++ b/scripts/network/domr/router_proxy.sh @@ -6,9 +6,9 @@ # to you 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 @@ -16,7 +16,7 @@ # specific language governing permissions and limitations # under the License. -# used as a proxy to call script inside virtual router +# used as a proxy to call script inside virtual router #set -x diff --git a/scripts/network/exdhcp/dnsmasq_edithosts.sh b/scripts/network/exdhcp/dnsmasq_edithosts.sh index 7990356edc4..f0744a9a822 100755 --- a/scripts/network/exdhcp/dnsmasq_edithosts.sh +++ b/scripts/network/exdhcp/dnsmasq_edithosts.sh @@ -6,9 +6,9 @@ # to you 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 @@ -41,9 +41,9 @@ no_dhcp_release=$? [ ! -f /etc/dhcphosts.txt ] && touch /etc/dhcphosts.txt [ ! -f /var/lib/misc/dnsmasq.leases ] && touch /var/lib/misc/dnsmasq.leases -sed -i /$1/d /etc/dhcphosts.txt -sed -i /$2,/d /etc/dhcphosts.txt -sed -i /$3,/d /etc/dhcphosts.txt +sed -i /$1/d /etc/dhcphosts.txt +sed -i /$2,/d /etc/dhcphosts.txt +sed -i /$3,/d /etc/dhcphosts.txt echo "$1,$2,$3,infinite" >>/etc/dhcphosts.txt @@ -54,9 +54,9 @@ then fi #delete leases to supplied mac and ip addresses -sed -i /$1/d /var/lib/misc/dnsmasq.leases -sed -i /"$2 "/d /var/lib/misc/dnsmasq.leases -sed -i /"$3 "/d /var/lib/misc/dnsmasq.leases +sed -i /$1/d /var/lib/misc/dnsmasq.leases +sed -i /"$2 "/d /var/lib/misc/dnsmasq.leases +sed -i /"$3 "/d /var/lib/misc/dnsmasq.leases #put in the new entry echo "0 $1 $2 $3 *" >> /var/lib/misc/dnsmasq.leases diff --git a/scripts/network/exdhcp/prepare_dhcpd.sh b/scripts/network/exdhcp/prepare_dhcpd.sh index e49d0fa175b..657fdfead20 100755 --- a/scripts/network/exdhcp/prepare_dhcpd.sh +++ b/scripts/network/exdhcp/prepare_dhcpd.sh @@ -6,9 +6,9 @@ # to you 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 diff --git a/scripts/network/exdhcp/prepare_dnsmasq.sh b/scripts/network/exdhcp/prepare_dnsmasq.sh index 70aa587e60f..5c496345e2c 100755 --- a/scripts/network/exdhcp/prepare_dnsmasq.sh +++ b/scripts/network/exdhcp/prepare_dnsmasq.sh @@ -6,9 +6,9 @@ # to you 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 @@ -129,11 +129,11 @@ config_dnsmasq domain=cloudnine.internal config_dnsmasq " # Send options to hosts which ask for a DHCP lease. # See RFC 2132 for details of available options. -# Common options can be given to dnsmasq by name: +# Common options can be given to dnsmasq by name: # run \"dnsmasq --help dhcp\" to get a list. # Note that all the common settings, such as netmask and # broadcast address, DNS server and default route, are given -# sane defaults by dnsmasq. You very likely will not need +# sane defaults by dnsmasq. You very likely will not need # any dhcp-options. If you use Windows clients and Samba, there # are some options which are recommended, they are detailed at the # end of this section. diff --git a/scripts/network/juniper/application-add.xml b/scripts/network/juniper/application-add.xml index 177329a0359..72fca676ce2 100644 --- a/scripts/network/juniper/application-add.xml +++ b/scripts/network/juniper/application-add.xml @@ -20,11 +20,11 @@ under the License. - -%name% -%protocol% + +%name% +%protocol% %dest-port-icmp% - + diff --git a/scripts/network/juniper/application-getone.xml b/scripts/network/juniper/application-getone.xml index 4f6b5546a5c..69e5417a58b 100644 --- a/scripts/network/juniper/application-getone.xml +++ b/scripts/network/juniper/application-getone.xml @@ -20,9 +20,9 @@ under the License. - -%name% - + +%name% + diff --git a/scripts/network/juniper/dest-nat-rule-add.xml b/scripts/network/juniper/dest-nat-rule-add.xml index 2ef1df29acc..2f043d614f7 100644 --- a/scripts/network/juniper/dest-nat-rule-add.xml +++ b/scripts/network/juniper/dest-nat-rule-add.xml @@ -49,8 +49,4 @@ under the License. - - - - - + diff --git a/scripts/network/juniper/guest-vlan-filter-term-add.xml b/scripts/network/juniper/guest-vlan-filter-term-add.xml index d0f52a0be44..9d4150958cc 100644 --- a/scripts/network/juniper/guest-vlan-filter-term-add.xml +++ b/scripts/network/juniper/guest-vlan-filter-term-add.xml @@ -19,17 +19,17 @@ under the License. - - -%filter-name% - -%term-name% - -%term-name% - - - - + + +%filter-name% + +%term-name% + +%term-name% + + + + diff --git a/scripts/network/juniper/private-interface-add.xml b/scripts/network/juniper/private-interface-add.xml index f0ccb6e0e76..d291597a57a 100644 --- a/scripts/network/juniper/private-interface-add.xml +++ b/scripts/network/juniper/private-interface-add.xml @@ -20,21 +20,21 @@ under the License. - -%private-interface-name% - - -%vlan-id% -%vlan-id% - - -
-%private-interface-ip% -
-
-
-
-
+ +%private-interface-name% + + +%vlan-id% +%vlan-id% + + +
+%private-interface-ip% +
+
+
+
+
diff --git a/scripts/network/juniper/private-interface-getone.xml b/scripts/network/juniper/private-interface-getone.xml index 474e6719366..bdbb19b412c 100644 --- a/scripts/network/juniper/private-interface-getone.xml +++ b/scripts/network/juniper/private-interface-getone.xml @@ -20,13 +20,13 @@ under the License. - -%private-interface-name% - - -%vlan-id% - - + +%private-interface-name% + + +%vlan-id% + + diff --git a/scripts/network/juniper/private-interface-with-filters-add.xml b/scripts/network/juniper/private-interface-with-filters-add.xml index 3ce8c55b242..ea6e01f6fb1 100644 --- a/scripts/network/juniper/private-interface-with-filters-add.xml +++ b/scripts/network/juniper/private-interface-with-filters-add.xml @@ -20,14 +20,14 @@ under the License. - -%private-interface-name% - - -%vlan-id% -%vlan-id% - - + +%private-interface-name% + + +%vlan-id% +%vlan-id% + + %input-filter-name% @@ -35,14 +35,14 @@ under the License. %output-filter-name% - -
-%private-interface-ip% -
-
-
-
-
+ +
+%private-interface-ip% +
+
+
+
+
diff --git a/scripts/network/juniper/proxy-arp-add.xml b/scripts/network/juniper/proxy-arp-add.xml index ae6dee0f239..118311fb620 100644 --- a/scripts/network/juniper/proxy-arp-add.xml +++ b/scripts/network/juniper/proxy-arp-add.xml @@ -19,17 +19,17 @@ under the License. - - - - -%public-interface-name% -
-%public-ip-address% -
-
-
-
+ + + + +%public-interface-name% +
+%public-ip-address% +
+
+
+
diff --git a/scripts/network/juniper/proxy-arp-getall.xml b/scripts/network/juniper/proxy-arp-getall.xml index 3f23a22cd5a..3ec425c28fc 100644 --- a/scripts/network/juniper/proxy-arp-getall.xml +++ b/scripts/network/juniper/proxy-arp-getall.xml @@ -19,12 +19,12 @@ under the License. - - - -%interface-name% - - + + + +%interface-name% + + diff --git a/scripts/network/juniper/proxy-arp-getone.xml b/scripts/network/juniper/proxy-arp-getone.xml index e43dc0bc5ea..3299dac9d0e 100644 --- a/scripts/network/juniper/proxy-arp-getone.xml +++ b/scripts/network/juniper/proxy-arp-getone.xml @@ -19,17 +19,17 @@ under the License. - - - - -%public-interface-name% -
-%public-ip-address% -
-
-
-
+ + + + +%public-interface-name% +
+%public-ip-address% +
+
+
+
diff --git a/scripts/network/juniper/public-ip-filter-term-add.xml b/scripts/network/juniper/public-ip-filter-term-add.xml index 9aad4c23990..e8ffd7aad41 100644 --- a/scripts/network/juniper/public-ip-filter-term-add.xml +++ b/scripts/network/juniper/public-ip-filter-term-add.xml @@ -19,22 +19,22 @@ under the License. - - -%filter-name% - -%term-name% - -<%address-type%> -%ip-address% - - - -%term-name% - - - - + + +%filter-name% + +%term-name% + +<%address-type%> +%ip-address% + + + +%term-name% + + + + diff --git a/scripts/network/juniper/security-policy-group.xml b/scripts/network/juniper/security-policy-group.xml index 1d0dc8cba12..46b57b0bfcb 100644 --- a/scripts/network/juniper/security-policy-group.xml +++ b/scripts/network/juniper/security-policy-group.xml @@ -19,13 +19,13 @@ under the License. - - - -%from-zone% -%to-zone% - - + + + +%from-zone% +%to-zone% + + diff --git a/scripts/network/juniper/zone-interface-add.xml b/scripts/network/juniper/zone-interface-add.xml index 9b2d37278ac..5f6d4c0416a 100644 --- a/scripts/network/juniper/zone-interface-add.xml +++ b/scripts/network/juniper/zone-interface-add.xml @@ -19,15 +19,15 @@ under the License. - - - -%private-zone-name% - -%zone-interface-name% - - - + + + +%private-zone-name% + +%zone-interface-name% + + + diff --git a/scripts/network/juniper/zone-interface-getone.xml b/scripts/network/juniper/zone-interface-getone.xml index 4bc5c4bc0d2..2078c015ba4 100644 --- a/scripts/network/juniper/zone-interface-getone.xml +++ b/scripts/network/juniper/zone-interface-getone.xml @@ -19,15 +19,15 @@ under the License. - - - -%private-zone-name% - -%zone-interface-name% - - - + + + +%private-zone-name% + +%zone-interface-name% + + + diff --git a/scripts/network/ping/baremetal_user_data.py b/scripts/network/ping/baremetal_user_data.py index 5a189353467..02fe845392c 100755 --- a/scripts/network/ping/baremetal_user_data.py +++ b/scripts/network/ping/baremetal_user_data.py @@ -38,7 +38,7 @@ def writeIfNotHere(fileName, texts): texts = [ "%s\n" % t for t in texts ] need = False for t in texts: - if not t in entries: + if t not in entries: entries.append(t) need = True diff --git a/scripts/storage/checkchildren.sh b/scripts/storage/checkchildren.sh index 55122d4f3a0..4185a7c25df 100755 --- a/scripts/storage/checkchildren.sh +++ b/scripts/storage/checkchildren.sh @@ -6,9 +6,9 @@ # to you 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 diff --git a/scripts/storage/installIso.sh b/scripts/storage/installIso.sh index fd301bc5ca1..89744ac3825 100755 --- a/scripts/storage/installIso.sh +++ b/scripts/storage/installIso.sh @@ -6,9 +6,9 @@ # to you 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 @@ -29,7 +29,7 @@ usage() { verify_cksum() { echo "$1 $2" | md5sum -c --status - if [ $? -gt 0 ] + if [ $? -gt 0 ] then printf "Checksum failed, not proceeding with install\n" exit 3 @@ -44,7 +44,7 @@ install_file() { mv $isofile /$isofs/$tmpltname - if [ $? -gt 0 ] + if [ $? -gt 0 ] then printf "Move operation failed, iso $isofile not installed\n" exit 4 @@ -55,7 +55,7 @@ install_file() { isofs=$isofs/$file mp=${isofs%/iso/*} mp=/$mp/iso - path=${isofs:${#mp}} + path=${isofs:${#mp}} pushd $mp ln -s $path $file popd @@ -108,10 +108,10 @@ then isofs=${isofs:1} fi -if [ ! -d /$isofs ] +if [ ! -d /$isofs ] then mkdir -p /$isofs - if [ $? -gt 0 ] + if [ $? -gt 0 ] then printf "Failed to create iso fs $isofs\n" >&2 exit 1 diff --git a/scripts/storage/qcow2/create_private_template.sh b/scripts/storage/qcow2/create_private_template.sh index 8e9e26c4104..06bf79d44cb 100755 --- a/scripts/storage/qcow2/create_private_template.sh +++ b/scripts/storage/qcow2/create_private_template.sh @@ -6,9 +6,9 @@ # to you 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 @@ -16,7 +16,7 @@ # specific language governing permissions and limitations # under the License. - + # $Id: create_private_template.sh 9804 2010-06-22 18:36:49Z alex $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/qcow2/create_private_template.sh $ # create_private_template.sh -- create a private template from a snapshot @@ -31,7 +31,7 @@ create_template() { local fspath=$1 local destpath=$2 - # if backing image exists, we need to combine them, otherwise + # if backing image exists, we need to combine them, otherwise # copy the image to preserve snapshots/compression if $qemu_img info "$tmpltimg" | grep -q backing; then qemu-img convert -O qcow2 /$fspath $destpath diff --git a/scripts/storage/qcow2/createtmplt.sh b/scripts/storage/qcow2/createtmplt.sh index b05550c14bb..4bb955e130c 100755 --- a/scripts/storage/qcow2/createtmplt.sh +++ b/scripts/storage/qcow2/createtmplt.sh @@ -6,9 +6,9 @@ # to you 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 @@ -70,12 +70,12 @@ uncompress() { ;; esac - if [ $? -gt 0 ] + if [ $? -gt 0 ] then printf "Failed to uncompress file, exiting " - exit 1 + exit 1 fi - + mv $tmpfile $imgfile printf "$imgfile" @@ -89,7 +89,7 @@ create_from_file() { if [ -b $tmpltimg ]; then $qemu_img convert -f raw -O qcow2 "$tmpltimg" /$tmpltfs/$tmpltname else - # if backing image exists, we need to combine them, otherwise + # if backing image exists, we need to combine them, otherwise # copy the image to preserve snapshots/compression if $qemu_img info "$tmpltimg" | grep -q backing; then $qemu_img convert -f qcow2 -O qcow2 "$tmpltimg" /$tmpltfs/$tmpltname >& /dev/null @@ -97,7 +97,7 @@ create_from_file() { cp -f $tmpltimg /$tmpltfs/$tmpltname fi fi - + if [ "$cleanup" == "true" ] then rm -f "$tmpltimg" @@ -161,17 +161,17 @@ do done -if [ ! -d /$tmpltfs ] +if [ ! -d /$tmpltfs ] then mkdir -p /$tmpltfs - if [ $? -gt 0 ] + if [ $? -gt 0 ] then printf "Failed to create user fs $tmpltfs\n" >&2 exit 1 fi fi -if [ ! -f $tmpltimg -a ! -b $tmpltimg ] +if [ ! -f $tmpltimg -a ! -b $tmpltimg ] then printf "root disk file $tmpltimg doesn't exist\n" exit 3 diff --git a/scripts/storage/qcow2/createvm.sh b/scripts/storage/qcow2/createvm.sh index 0971c9b9255..e3a83aed3bf 100755 --- a/scripts/storage/qcow2/createvm.sh +++ b/scripts/storage/qcow2/createvm.sh @@ -6,9 +6,9 @@ # to you 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 @@ -18,11 +18,11 @@ # $Id: createvm.sh 10292 2010-07-07 00:24:04Z edison $ $HeadURL: svn://svn.lab.vmops.com/repos/vmdev/java/scripts/storage/qcow2/createvm.sh $ -# createvm.sh -- create a vm image +# createvm.sh -- create a vm image usage() { echo "Usage (clone VM from template): createvm.sh -t -
-

{{ $t('label.accounttype') }}

- - {{ $t('label.account') }} - {{ $t('label.project') }} - -
- -
-

*{{ $t('label.domain') }}

- - - - - - {{ domain.path || domain.name || domain.description }} - - - -
- - - - +

{{ $t('label.network') }}

@@ -146,6 +67,7 @@ + + + + diff --git a/ui/src/views/compute/wizard/LoadBalancerSelection.vue b/ui/src/views/compute/wizard/LoadBalancerSelection.vue index e2ffb991e98..3ba66241d56 100644 --- a/ui/src/views/compute/wizard/LoadBalancerSelection.vue +++ b/ui/src/views/compute/wizard/LoadBalancerSelection.vue @@ -30,6 +30,7 @@ :rowKey="record => record.id" :pagination="false" :rowSelection="rowSelection" + :customRow="onClickRow" size="middle" :scroll="{ y: 225 }">