XCP-ng
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Register
    • Login

    Python help

    Scheduled Pinned Locked Moved REST API
    28 Posts 5 Posters 1.0k Views 4 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • B Offline
      Butcat DevOps Team Vates đŸȘ @Studmuffn1134
      last edited by

      Hi @Studmuffn1134,

      You’re right—some actions (like certain host operations) aren’t fully available in the REST API yet. Right now, most "GET" methods work, and some actions (like those for VMs and snapshots) are implemented. However, the REST API is still a work in progress.

      The Xen Orchestra team is currently focusing on:

      • Non-admin user management (coming soon).

      • Save/backup functionality (planned for the next few months).

      Since not everything is ready in REST yet, you might need to use both REST and JSON-RPC to access all operations.

      For JSON-RPC, check out:

      Official JSON-RPC Documentation

      Basic JSON-RPC Examples (Forum Discussion)

      S 1 Reply Last reply Reply Quote 0
      • S Offline
        Studmuffn1134 @Butcat
        last edited by

        @Butcat def shutdown_vm_hosts(host_id,xo_url,auth_token,use_force):
        root_dir = os.path.dirname(os.path.abspath(file))
        file_path = os.path.join((root_dir),"Certs\fullchain.pem")

        headers = {
            'Content-Type':'application/json',
            'Authorization':f'Bearer {auth_token}'
        }
        data = {
            "jsonrpc":"2.0",
            "method":"host.shutdown",
            "params":[host_id],
            "id":1
        }
        try:
            response = requests.post(
                xo_url,
                headers=headers,data=json.dumps(data),
                verify=file_path
            )
            print(f"Status code: {response.status_code}")
            
            if response.status_code in [200, 202, 204]:
                print(f"✓ Successfully initiated {'force' if use_force else 'clean'} shutdown")
                return True
            else:
                print(f"Error: {response.text}")
                return False
        except requests.exceptions.RequestException as e:
            print(f"Request failed: {e}")
            return False
        
        S 1 Reply Last reply Reply Quote 0
        • S Offline
          Studmuffn1134 @Studmuffn1134
          last edited by Studmuffn1134

          @Studmuffn1134 That is what i did and it still does not work I get a status code 200 but it never shuts the host off

          1 Reply Last reply Reply Quote 0
          • TheNorthernLightT Offline
            TheNorthernLight @Studmuffn1134
            last edited by

            @Studmuffn1134 LOL at "ThePlague"... (hackers unite!)

            S 1 Reply Last reply Reply Quote 0
            • S Offline
              Studmuffn1134 @TheNorthernLight
              last edited by

              @TheNorthernLight Finally someone gets the reference But what do u think I am doing wrong

              TheNorthernLightT 1 Reply Last reply Reply Quote 0
              • TheNorthernLightT Offline
                TheNorthernLight @Studmuffn1134
                last edited by

                @Studmuffn1134 Sadly, I dont know squat about python, sorry!

                S 1 Reply Last reply Reply Quote 0
                • S Offline
                  Studmuffn1134 @TheNorthernLight
                  last edited by

                  @TheNorthernLight Well could you do it in a language you know and maybe i would be able to convert it>?

                  1 Reply Last reply Reply Quote 0
                  • G Offline
                    Gurve
                    last edited by

                    Did some "kicking" around in python, I don't python that much so "readers beware"

                    How did i figure it out, the french blog from here was useful, but only showed listing methods. I was still very confused as to how to call the vm.stop and which parameters it took.

                    Enter xo-cli ❀

                    xo-cli uses jsonrpc but is CLi only, but you can get very nice info from it just have to register and call "list-methods". should be available on your xo VM

                    xo-cli register http://[yourXO].example.com [yourusername]
                    #after registering/authenticating
                    xo-cli list-commands | egrep 'vm\.' --color=always
                    

                    here you will get a nice list of all "methods" in jsonrpc related to vm and a line about vm.stop:

                    vm.stop id=<string> [force=<boolean>] [forceShutdownDelay=<number>] [bypassBlockedOperation=<boolean>]

                    which was enough information to alter the french guy's (Baron) example into this:

                    import aiohttp
                    import asyncio
                    
                    from jsonrpc_websocket import Server
                    
                    async def routine():
                        async with aiohttp.ClientSession() as client:
                            server = Server('ws://[yourXO]/api/', client)
                    
                            await server.ws_connect()
                    
                            # signIn required
                            result = await server.session.signIn(username='[xoAdmin]', password='[xoAdmin]') # email attribute is working in place of username
                            
                            #hard shutdown
                            #result = await server.vm.stop(id='3f32beeb-ab3f-a8ac-087d-fdc7ed061b58', force=(bool(1)))
                            
                            #clean Shutdown
                            result = await server.vm.stop(id='3f32beeb-ab3f-a8ac-087d-fdc7ed061b58', force=(bool(0)))
                            
                            print (result)
                    
                    asyncio.get_event_loop().run_until_complete(routine())
                    
                    
                    
                    S 1 Reply Last reply Reply Quote 0
                    • S Offline
                      Studmuffn1134 @Gurve
                      last edited by

                      @Gurve Is this for the vm's on the server or the host itself i need the host itself

                      G 1 Reply Last reply Reply Quote 0
                      • G Offline
                        Gurve @Studmuffn1134
                        last edited by

                        @Studmuffn1134 Sorry, must have somehow read another reply about vm and mixed them. But pretty sure you should be able to utilise the steps I did for host shutdown

                        xo-cli to get relevant api endpoints, xo-cli to get parameters for said endpoint and then press play

                        S 1 Reply Last reply Reply Quote 0
                        • S Offline
                          Studmuffn1134 @Gurve
                          last edited by

                          @Gurve Do i have to enable the xo-cli?

                          G 1 Reply Last reply Reply Quote 0
                          • G Offline
                            Gurve @Studmuffn1134
                            last edited by Gurve

                            @Studmuffn1134 should be available in XO vm, it was atleast for me, I just used the XO installer script from github.

                            I did a quick search with xo cli now

                            xo-cli list-commands | egrep 'host.'

                            in case it looks weird "\." is just to escape the "." which just tells regex I am looking for an actual "."

                            import aiohttp
                            import asyncio
                            
                            from jsonrpc_websocket import Server
                            
                            async def routine():
                                async with aiohttp.ClientSession() as client:
                                    server = Server('ws://[yourXO]/api/', client)
                            
                                    await server.ws_connect()
                            
                                    # signIn required
                                    result = await server.session.signIn(username='[yourXOusername]', password='[yourXOPassword]') # email attribute is working in place of username
                                    
                                    #hard shutdown VM
                                    #result = await server.vm.stop(id='3f32beeb-ab3f-a8ac-087d-fdc7ed061b58', force=(bool(1)))
                                    
                                    #clean Shutdown VM
                                    #result = await server.vm.stop(id='3f32beeb-ab3f-a8ac-087d-fdc7ed061b58', force=(bool(0)))
                            
                                    #bypassbackup and bypassevacuate set off by default but include for wholeness of parameters
                                    result = await server.host.stop(id=[hostUUID],bypassBackupCheck=(bool(0)),bypassEvacuate=bool(0))
                                    
                                    print (result)
                            
                            asyncio.get_event_loop().run_until_complete(routine())
                            

                            I just built all examples into one, here in the end is the host.stop example also

                            S 1 Reply Last reply Reply Quote 0
                            • S Offline
                              Studmuffn1134 @Gurve
                              last edited by

                              @Gurve '''def shutdown_vm_hosts(host_id,xo_url,auth_token,use_force):

                              async def routine():
                                  async with aiohttp.ClientSession() as client:
                                      server = Server('ws://192.168.100.30:2223/api/', client)
                                      await server.ws_connect()
                                      # signIn required
                                      result = await server.session.signIn(username='ThePlague', password='No') # email attribute is working in place of username
                                      hostUUID ="d2f1374c-728d-4905-85cc-e0d7166a3fbf"
                                      #hard shutdown VM
                                      #result = await server.vm.stop(id='3f32beeb-ab3f-a8ac-087d-fdc7ed061b58', force=(bool(1)))
                                      #clean Shutdown VM
                                      #result = await server.vm.stop(id='3f32beeb-ab3f-a8ac-087d-fdc7ed061b58', force=(bool(0)))
                                      #bypassbackup and bypassevacuate set off by default but include for wholeness of parameters
                                      result = await server.host.stop(id=[hostUUID],bypassBackupCheck=(bool(0)),bypassEvacuate=bool(0))
                                      print (result)''' Traceback (most recent call last):
                                      
                                        File "z:\Valera\School\Lakeland University\Finished\Programming 2\Python Programs\StudsPrograms\Shutdowntest.py", line 72, in <module>
                                      
                                          main() # second part of calling the main function
                                      
                                          ~~~~^^
                                      
                                        File "z:\Valera\School\Lakeland University\Finished\Programming 2\Python Programs\StudsPrograms\Shutdowntest.py", line 70, in main
                                      
                                          shutdown_vm_hosts(l,XO_URL,AUTH_TOKEN,use_force=False)
                                      
                                          ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                      
                                        File "z:\Valera\School\Lakeland University\Finished\Programming 2\Python Programs\StudsPrograms\Shutdowntest.py", line 29, in shutdown_vm_hosts
                                      
                                          asyncio.get_event_loop().run_until_complete(routine())
                                      
                                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^
                                      
                                        File "C:\Users\ThePlague\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 725, in run_until_complete
                                      
                                          return future.result()
                                      
                                                 ~~~~~~~~~~~~~^^
                                      
                                        File "z:\Valera\School\Lakeland University\Finished\Programming 2\Python Programs\StudsPrograms\Shutdowntest.py", line 13, in routine
                                      
                                          await server.ws_connect()
                                      
                                        File "Z:\Valera\School\Lakeland University\Finished\Programming 2\Python Programs\StudsPrograms\.venv\Lib\site-packages\jsonrpc_websocket\jsonrpc.py", line 68, in ws_connect
                                      
                                          raise TransportError('Error connecting to server', None, exc)
                                      
                                      jsonrpc_base.jsonrpc.TransportError: ('Error connecting to server', ServerDisconnectedError('Server disconnected'))
                              

                              I tried that and that is the error code I get

                              S 1 Reply Last reply Reply Quote 0
                              • S Offline
                                Studmuffn1134 @Studmuffn1134
                                last edited by

                                @Studmuffn1134 I changed my link from ws:// to https:// and it now gives me this error File "Z:\Valera\School\Lakeland University\Finished\Programming 2\Python Programs\StudsPrograms.venv\Lib\site-packages\jsonrpc_base\jsonrpc.py", line 213, in parse_response
                                raise ProtocolError(code, message, data)
                                jsonrpc_base.jsonrpc.ProtocolError: (10, 'invalid parameters', {'error': {'message': 'invalid parameters', 'code': 10, 'data': {'errors': [{'instancePath': '/id', 'schemaPath': '#/properties/id/type', 'keyword': 'type', 'params': {'type': 'string'}, 'message': 'must be string'}]}}, 'id': '0a11ec72-9300-4030-a5d2-a5c0286f3811', 'jsonrpc': '2.0'})

                                1 Reply Last reply Reply Quote 0
                                • First post
                                  Last post