You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ha...@apache.org on 2025/09/26 03:26:15 UTC

(cloudstack) branch ExtensionMaaS created (now 24bd0be3096)

This is an automated email from the ASF dual-hosted git repository.

harikrishna pushed a change to branch ExtensionMaaS
in repository https://gitbox.apache.org/repos/asf/cloudstack.git


      at 24bd0be3096 Added redirect url for MaaS instance page

This branch includes the following new commits:

     new e5c5a64b4ea Adding extension support for Baremetal MaaS
     new ea7807ebd11 Added sql entries
     new 79002e7ff73 Make distro_series param read from template or VM details
     new fb08deda3fb Fix script
     new 79e2bb76e93 Fix system id usage
     new 24bd0be3096 Added redirect url for MaaS instance page

The 6 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(cloudstack) 01/06: Adding extension support for Baremetal MaaS

Posted by ha...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

harikrishna pushed a commit to branch ExtensionMaaS
in repository https://gitbox.apache.org/repos/asf/cloudstack.git

commit e5c5a64b4eabe73e65a0f7deb387c7dff0946cf6
Author: Harikrishna Patnala <ha...@gmail.com>
AuthorDate: Tue Sep 9 10:45:23 2025 +0530

    Adding extension support for Baremetal MaaS
---
 debian/cloudstack-management.install |   1 +
 extensions/MaaS/maas.py              | 209 +++++++++++++++++++++++++++++++++++
 2 files changed, 210 insertions(+)

diff --git a/debian/cloudstack-management.install b/debian/cloudstack-management.install
index b2a32bd93c1..befc7049c30 100644
--- a/debian/cloudstack-management.install
+++ b/debian/cloudstack-management.install
@@ -24,6 +24,7 @@
 /etc/cloudstack/management/config.json
 /etc/cloudstack/extensions/Proxmox/proxmox.sh
 /etc/cloudstack/extensions/HyperV/hyperv.py
+/etc/cloudstack/extensions/MaaS/maas.py
 /etc/default/cloudstack-management
 /etc/security/limits.d/cloudstack-limits.conf
 /etc/sudoers.d/cloudstack
diff --git a/extensions/MaaS/maas.py b/extensions/MaaS/maas.py
new file mode 100644
index 00000000000..93316bf0f56
--- /dev/null
+++ b/extensions/MaaS/maas.py
@@ -0,0 +1,209 @@
+#!/usr/bin/env python3
+# 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.
+
+import sys
+import json
+from requests_oauthlib import OAuth1Session
+
+
+def fail(message):
+    print(json.dumps({"error": message}))
+    sys.exit(1)
+
+
+def succeed(data):
+    print(json.dumps(data))
+    sys.exit(0)
+
+
+class MaasManager:
+    def __init__(self, config_path):
+        self.config_path = config_path
+        self.data = self.parse_json()
+        self.session = self.init_session()
+
+    def parse_json(self):
+        try:
+            with open(self.config_path, "r") as f:
+                json_data = json.load(f)
+
+            extension = json_data.get("externaldetails", {}).get("extension", {})
+            host = json_data.get("externaldetails", {}).get("host", {})
+
+            endpoint = host.get("endpoint") or extension.get("endpoint")
+            apikey = host.get("apikey") or extension.get("apikey")
+            distro_series = host.get("distro_series") or extension.get("distro_series") or "ubuntu"
+
+            if not endpoint or not apikey:
+                fail("Missing MAAS endpoint or apikey")
+
+            # normalize endpoint
+            if not endpoint.startswith("http://") and not endpoint.startswith("https://"):
+                endpoint = "http://" + endpoint
+            endpoint = endpoint.rstrip("/")
+
+            # split api key
+            parts = apikey.split(":")
+            if len(parts) != 3:
+                fail("Invalid apikey format. Expected consumer:token:secret")
+
+            consumer, token, secret = parts
+            return {
+                "endpoint": endpoint,
+                "consumer": consumer,
+                "token": token,
+                "secret": secret,
+                "distro_series": distro_series,
+                "system_id": json_data.get("cloudstack.vm.details", {}).get("details", {}).get("maas_system_id", ""),
+                "vm_name": json_data.get("cloudstack.vm.details", {}).get("name", ""),
+                "memory": json_data.get("cloudstack.vm.details", {}).get("minRam", ""),
+                "cpus": json_data.get("cloudstack.vm.details", {}).get("cpus", ""),
+                "nics": json_data.get("cloudstack.vm.details", {}).get("nics", []),
+            }
+        except Exception as e:
+            fail(f"Error parsing JSON: {str(e)}")
+
+    def init_session(self):
+        return OAuth1Session(
+            self.data["consumer"],
+            resource_owner_key=self.data["token"],
+            resource_owner_secret=self.data["secret"],
+        )
+
+    def call_maas(self, method, path, data=None):
+        if not path.startswith("/"):
+            path = "/" + path
+        url = f"{self.data['endpoint']}:5240/MAAS/api/2.0{path}"
+        resp = self.session.request(method, url, data=data)
+        if not resp.ok:
+            fail(f"MAAS API error: {resp.status_code} {resp.text}")
+        try:
+            return resp.json() if resp.text else {}
+        except ValueError:
+            return {}
+
+    def prepare(self):
+        machines = self.call_maas("GET", "/machines/")
+        ready = [m for m in machines if m.get("status_name") == "Ready"]
+        if not ready:
+            fail("No Ready machines available")
+
+        system = ready[0]
+        system_id = system["system_id"]
+        mac = system.get("interface_set", [{}])[0].get("mac_address")
+
+        if not mac:
+            fail("No MAC address found")
+
+        # Load original JSON so we can update nics
+        with open(self.config_path, "r") as f:
+            json_data = json.load(f)
+
+        if json_data.get("cloudstack.vm.details", {}).get("nics"):
+            json_data["cloudstack.vm.details"]["nics"][0]["mac"] = mac
+
+        result = {
+            "nics": json_data["cloudstack.vm.details"]["nics"],
+            "details": {"External:mac_address": mac, "maas_system_id": system_id},
+        }
+        succeed(result)
+
+    def create(self):
+        sysid = self.data.get("system_id")
+        if not sysid:
+            fail("system_id missing for create")
+        self.call_maas(
+            "POST",
+            f"/machines/{sysid}/",
+            {"op": "deploy", "distro_series": self.data["distro_series"]},
+        )
+        succeed({"status": "success", "message": f"Instance created with {self.data['distro_series']}"})
+
+    def delete(self):
+        sysid = self.data.get("system_id")
+        if not sysid:
+            fail("system_id missing for delete")
+        self.call_maas("POST", f"/machines/{sysid}/", {"op": "release"})
+        succeed({"status": "success", "message": "Instance deleted"})
+
+    def start(self):
+        sysid = self.data.get("system_id")
+        if not sysid:
+            fail("system_id missing for start")
+        self.call_maas("POST", f"/machines/{sysid}/", {"op": "power_on"})
+        succeed({"status": "success", "power_state": "PowerOn"})
+
+    def stop(self):
+        sysid = self.data.get("system_id")
+        if not sysid:
+            fail("system_id missing for stop")
+        self.call_maas("POST", f"/machines/{sysid}/", {"op": "power_off"})
+        succeed({"status": "success", "power_state": "PowerOff"})
+
+    def reboot(self):
+        sysid = self.data.get("system_id")
+        if not sysid:
+            fail("system_id missing for reboot")
+        self.call_maas("POST", f"/machines/{sysid}/", {"op": "power_cycle"})
+        succeed({"status": "success", "power_state": "PowerOn"})
+
+    def status(self):
+        sysid = self.data.get("system_id")
+        if not sysid:
+            fail("system_id missing for status")
+        resp = self.call_maas("GET", f"/machines/{sysid}/")
+        state = resp.get("power_state", "")
+        if state == "on":
+            mapped = "PowerOn"
+        elif state == "off":
+            mapped = "PowerOff"
+        else:
+            mapped = "PowerUnknown"
+        succeed({"status": "success", "power_state": mapped})
+
+
+def main():
+    if len(sys.argv) < 3:
+        fail("Usage: maas.py <action> <json-file-path>")
+
+    action = sys.argv[1].lower()
+    json_file = sys.argv[2]
+
+    try:
+        manager = MaasManager(json_file)
+    except FileNotFoundError:
+        fail(f"JSON file not found: {json_file}")
+
+    actions = {
+        "prepare": manager.prepare,
+        "create": manager.create,
+        "delete": manager.delete,
+        "start": manager.start,
+        "stop": manager.stop,
+        "reboot": manager.reboot,
+        "status": manager.status,
+    }
+
+    if action not in actions:
+        fail("Invalid action")
+
+    actions[action]()
+
+
+if __name__ == "__main__":
+    main()


(cloudstack) 04/06: Fix script

Posted by ha...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

harikrishna pushed a commit to branch ExtensionMaaS
in repository https://gitbox.apache.org/repos/asf/cloudstack.git

commit fb08deda3fbfccc1a6eff36cdadd79e6ebc5c2b0
Author: Harikrishna Patnala <ha...@gmail.com>
AuthorDate: Mon Sep 15 18:34:07 2025 +0530

    Fix script
---
 extensions/MaaS/maas.py | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/extensions/MaaS/maas.py b/extensions/MaaS/maas.py
old mode 100644
new mode 100755
index 488c9f2b068..2c39477fbb6
--- a/extensions/MaaS/maas.py
+++ b/extensions/MaaS/maas.py
@@ -74,10 +74,6 @@ class MaasManager:
                 "secret": secret,
                 "distro_series": distro_series,
                 "system_id": json_data.get("cloudstack.vm.details", {}).get("details", {}).get("maas_system_id", ""),
-                "vm_name": json_data.get("cloudstack.vm.details", {}).get("name", ""),
-                "memory": json_data.get("cloudstack.vm.details", {}).get("minRam", ""),
-                "cpus": json_data.get("cloudstack.vm.details", {}).get("cpus", ""),
-                "nics": json_data.get("cloudstack.vm.details", {}).get("nics", []),
             }
         except Exception as e:
             fail(f"Error parsing JSON: {str(e)}")


(cloudstack) 03/06: Make distro_series param read from template or VM details

Posted by ha...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

harikrishna pushed a commit to branch ExtensionMaaS
in repository https://gitbox.apache.org/repos/asf/cloudstack.git

commit 79002e7ff73c2b6817774f89cb7ca26e06f9b4dc
Author: Harikrishna Patnala <ha...@gmail.com>
AuthorDate: Thu Sep 11 16:36:26 2025 +0530

    Make distro_series param read from template or VM details
---
 extensions/MaaS/maas.py | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/extensions/MaaS/maas.py b/extensions/MaaS/maas.py
index 93316bf0f56..488c9f2b068 100644
--- a/extensions/MaaS/maas.py
+++ b/extensions/MaaS/maas.py
@@ -47,7 +47,11 @@ class MaasManager:
 
             endpoint = host.get("endpoint") or extension.get("endpoint")
             apikey = host.get("apikey") or extension.get("apikey")
-            distro_series = host.get("distro_series") or extension.get("distro_series") or "ubuntu"
+            distro_series = (
+                json_data.get("cloudstack.vm.details", {})
+                .get("details", {})
+                .get("distro_series", "ubuntu")
+            )
 
             if not endpoint or not apikey:
                 fail("Missing MAAS endpoint or apikey")


(cloudstack) 06/06: Added redirect url for MaaS instance page

Posted by ha...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

harikrishna pushed a commit to branch ExtensionMaaS
in repository https://gitbox.apache.org/repos/asf/cloudstack.git

commit 24bd0be3096ada993d3ac32b766a00a8363cc40c
Author: Harikrishna Patnala <ha...@gmail.com>
AuthorDate: Fri Sep 26 08:04:50 2025 +0530

    Added redirect url for MaaS instance page
---
 extensions/MaaS/maas.py                 |  3 +++
 ui/src/components/view/ActionButton.vue |  4 +--
 ui/src/components/widgets/Console.vue   | 44 ++++++++++++++++++++++++++-------
 3 files changed, 40 insertions(+), 11 deletions(-)

diff --git a/extensions/MaaS/maas.py b/extensions/MaaS/maas.py
index c950c93c7ce..1541d677946 100755
--- a/extensions/MaaS/maas.py
+++ b/extensions/MaaS/maas.py
@@ -139,12 +139,15 @@ class MaasManager:
         if json_data.get("cloudstack.vm.details", {}).get("nics"):
             json_data["cloudstack.vm.details"]["nics"][0]["mac"] = mac
 
+        console_url = f"http://{self.data['endpoint'].replace('http://','').replace('https://','')}:5240/MAAS/r/machine/{system_id}/summary"
+
         result = {
             "nics": json_data["cloudstack.vm.details"]["nics"],
             "details": {
                 "External:mac_address": mac,
                 "External:maas_system_id": system_id,
                 "External:hostname": hostname,
+                "External:console_url": console_url,
             },
         }
         succeed(result)
diff --git a/ui/src/components/view/ActionButton.vue b/ui/src/components/view/ActionButton.vue
index 7733efdf66e..14128a5ce55 100644
--- a/ui/src/components/view/ActionButton.vue
+++ b/ui/src/components/view/ActionButton.vue
@@ -17,7 +17,7 @@
 
 <template>
   <span class="row-action-button">
-    <a-tooltip arrowPointAtCenter placement="bottomRight" v-if="resource && resource.id && dataView && resource.hypervisor !== 'External'">
+    <a-tooltip arrowPointAtCenter placement="bottomRight" v-if="resource && resource.id && dataView">
       <template #title>
         {{ $t('label.view.console') }}
       </template>
@@ -29,7 +29,7 @@
         icon="code"
       />
     </a-tooltip>
-    <a-tooltip arrowPointAtCenter placement="bottomRight" v-if="resource && resource.id && dataView && resource.hypervisor !== 'External'">
+    <a-tooltip arrowPointAtCenter placement="bottomRight" v-if="resource && resource.id && dataView">
       <template #title>
         {{ $t('label.copy.consoleurl') }}
       </template>
diff --git a/ui/src/components/widgets/Console.vue b/ui/src/components/widgets/Console.vue
index 31105743795..edee7498991 100644
--- a/ui/src/components/widgets/Console.vue
+++ b/ui/src/components/widgets/Console.vue
@@ -17,9 +17,17 @@
 
 <template>
   <a
-    v-if="['vm', 'systemvm', 'router', 'ilbvm', 'vnfapp'].includes($route.meta.name) && 'listVirtualMachines' in $store.getters.apis && 'createConsoleEndpoint' in $store.getters.apis"
+    v-if="['vm', 'systemvm', 'router', 'ilbvm', 'vnfapp'].includes($route.meta.name) &&
+           'listVirtualMachines' in $store.getters.apis &&
+           'createConsoleEndpoint' in $store.getters.apis"
     @click="consoleUrl">
-    <a-button style="margin-left: 5px" shape="circle" type="dashed" :size="size" :disabled="['Stopped', 'Restoring', 'Error', 'Destroyed'].includes(resource.state) || resource.hostcontrolstate === 'Offline'" >
+    <a-button
+      style="margin-left: 5px"
+      shape="circle"
+      type="dashed"
+      :size="size"
+      :disabled="['Stopped', 'Restoring', 'Error', 'Destroyed'].includes(resource.state) ||
+                 resource.hostcontrolstate === 'Offline'">
       <code-outlined v-if="!copyUrlToClipboard"/>
       <copy-outlined v-else />
     </a-button>
@@ -49,11 +57,29 @@ export default {
     }
   },
   methods: {
-    consoleUrl () {
-      const params = {}
-      params.virtualmachineid = this.resource.id
-      postAPI('createConsoleEndpoint', params).then(json => {
-        this.url = (json && json.createconsoleendpointresponse) ? json.createconsoleendpointresponse.consoleendpoint.url : '#/exception/404'
+    async consoleUrl () {
+      try {
+        const externalUrl = this.resource?.details?.['External:console_url']
+        if (externalUrl) {
+          this.url = externalUrl
+          if (this.copyUrlToClipboard) {
+            this.$copyText(this.url)
+            this.$message.success({
+              content: this.$t('label.copied.clipboard')
+            })
+          } else {
+            window.open(this.url, '_blank')
+          }
+          return
+        }
+
+        const params = { virtualmachineid: this.resource.id }
+        const json = await postAPI('createConsoleEndpoint', params)
+
+        this.url = (json && json.createconsoleendpointresponse)
+          ? json.createconsoleendpointresponse.consoleendpoint.url
+          : '#/exception/404'
+
         if (json.createconsoleendpointresponse.consoleendpoint.success) {
           if (this.copyUrlToClipboard) {
             this.$copyText(this.url)
@@ -69,9 +95,9 @@ export default {
             description: json.createconsoleendpointresponse.consoleendpoint.details
           })
         }
-      }).catch(error => {
+      } catch (error) {
         this.$notifyError(error)
-      })
+      }
     }
   },
   computed: {


(cloudstack) 05/06: Fix system id usage

Posted by ha...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

harikrishna pushed a commit to branch ExtensionMaaS
in repository https://gitbox.apache.org/repos/asf/cloudstack.git

commit 79e2bb76e9304da04290a6854467ead3d88cd8fb
Author: Harikrishna Patnala <ha...@gmail.com>
AuthorDate: Thu Sep 25 11:13:06 2025 +0530

    Fix system id usage
---
 extensions/MaaS/maas.py | 58 ++++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 50 insertions(+), 8 deletions(-)

diff --git a/extensions/MaaS/maas.py b/extensions/MaaS/maas.py
index 2c39477fbb6..c950c93c7ce 100755
--- a/extensions/MaaS/maas.py
+++ b/extensions/MaaS/maas.py
@@ -44,36 +44,48 @@ class MaasManager:
 
             extension = json_data.get("externaldetails", {}).get("extension", {})
             host = json_data.get("externaldetails", {}).get("host", {})
+            vm = json_data.get("externaldetails", {}).get("virtualmachine", {})
 
             endpoint = host.get("endpoint") or extension.get("endpoint")
             apikey = host.get("apikey") or extension.get("apikey")
             distro_series = (
                 json_data.get("cloudstack.vm.details", {})
                 .get("details", {})
-                .get("distro_series", "ubuntu")
+                .get("distro_series", None)
             )
 
             if not endpoint or not apikey:
                 fail("Missing MAAS endpoint or apikey")
 
-            # normalize endpoint
             if not endpoint.startswith("http://") and not endpoint.startswith("https://"):
                 endpoint = "http://" + endpoint
             endpoint = endpoint.rstrip("/")
 
-            # split api key
             parts = apikey.split(":")
             if len(parts) != 3:
                 fail("Invalid apikey format. Expected consumer:token:secret")
 
             consumer, token, secret = parts
+
+            system_id = (
+                    json_data.get("cloudstack.vm.details", {})
+                    .get("details", {})
+                    .get("maas_system_id")
+                    or vm.get("maas_system_id", "")
+            )
+
+            vm_name = vm.get("vm_name") or json_data.get("cloudstack.vm.details", {}).get("name")
+            if not vm_name:
+                vm_name = f"cs-{system_id}" if system_id else "cs-unknown"
+
             return {
                 "endpoint": endpoint,
                 "consumer": consumer,
                 "token": token,
                 "secret": secret,
-                "distro_series": distro_series,
-                "system_id": json_data.get("cloudstack.vm.details", {}).get("details", {}).get("maas_system_id", ""),
+                "distro_series": distro_series or "ubuntu/focal",
+                "system_id": system_id,
+                "vm_name": vm_name,
             }
         except Exception as e:
             fail(f"Error parsing JSON: {str(e)}")
@@ -103,9 +115,19 @@ class MaasManager:
         if not ready:
             fail("No Ready machines available")
 
-        system = ready[0]
+        sysid = self.data.get("system_id")
+
+        if sysid:
+            match = next((m for m in ready if m["system_id"] == sysid), None)
+            if not match:
+                fail(f"Provided system_id '{sysid}' not found among Ready machines")
+            system = match
+        else:
+            system = ready[0]
+
         system_id = system["system_id"]
         mac = system.get("interface_set", [{}])[0].get("mac_address")
+        hostname = system.get("hostname", "")
 
         if not mac:
             fail("No MAC address found")
@@ -119,7 +141,11 @@ class MaasManager:
 
         result = {
             "nics": json_data["cloudstack.vm.details"]["nics"],
-            "details": {"External:mac_address": mac, "maas_system_id": system_id},
+            "details": {
+                "External:mac_address": mac,
+                "External:maas_system_id": system_id,
+                "External:hostname": hostname,
+            },
         }
         succeed(result)
 
@@ -127,10 +153,26 @@ class MaasManager:
         sysid = self.data.get("system_id")
         if not sysid:
             fail("system_id missing for create")
+
+        ds = self.data.get("distro_series", "ubuntu/focal")
+        vm_name = self.data.get("vm_name")
+
+        # Cloud-init userdata to disable netplan, flush IPs on ens35, and run dhclient
+        userdata = """#cloud-config
+network:
+  config: disabled
+runcmd:
+  - [ sh, -c, "dhclient -v -4 ens35 || true" ]
+"""
+
         self.call_maas(
             "POST",
             f"/machines/{sysid}/",
-            {"op": "deploy", "distro_series": self.data["distro_series"]},
+            {
+                "op": "deploy",
+                "distro_series": ds,
+                "userdata": userdata,
+            },
         )
         succeed({"status": "success", "message": f"Instance created with {self.data['distro_series']}"})
 


(cloudstack) 02/06: Added sql entries

Posted by ha...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

harikrishna pushed a commit to branch ExtensionMaaS
in repository https://gitbox.apache.org/repos/asf/cloudstack.git

commit ea7807ebd11a9f1783de8bb5c41f67f0ffe30095
Author: Harikrishna Patnala <ha...@gmail.com>
AuthorDate: Thu Sep 11 13:40:01 2025 +0530

    Added sql entries
---
 engine/schema/src/main/resources/META-INF/db/schema-42100to42200.sql | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/engine/schema/src/main/resources/META-INF/db/schema-42100to42200.sql b/engine/schema/src/main/resources/META-INF/db/schema-42100to42200.sql
index 4fcb2b75de5..97f11066a6d 100644
--- a/engine/schema/src/main/resources/META-INF/db/schema-42100to42200.sql
+++ b/engine/schema/src/main/resources/META-INF/db/schema-42100to42200.sql
@@ -28,3 +28,6 @@ CALL `cloud`.`IDEMPOTENT_CHANGE_COLUMN`('cloud.domain_router', 'scripts_version'
 
 -- Add the column cross_zone_instance_creation to cloud.backup_repository. if enabled it means that new Instance can be created on all Zones from Backups on this Repository.
 CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.backup_repository', 'cross_zone_instance_creation', 'TINYINT(1) DEFAULT NULL COMMENT ''Backup Repository can be used for disaster recovery on another zone''');
+
+CALL `cloud`.`INSERT_EXTENSION_IF_NOT_EXISTS`('MaaS', 'Sample extension for Baremetal MaaS written in python', 'MaaS/maas.py');
+CALL `cloud`.`INSERT_EXTENSION_DETAIL_IF_NOT_EXISTS`('MaaS', 'orchestratorrequirespreparevm', 'true', 0);