{"id":1031,"date":"2017-01-20T17:12:25","date_gmt":"2017-01-20T23:12:25","guid":{"rendered":"http:\/\/blog.ls-al.com\/?p=1031"},"modified":"2018-03-31T20:26:07","modified_gmt":"2018-04-01T01:26:07","slug":"oracle-vm-ovm-rest-api","status":"publish","type":"post","link":"https:\/\/blog.ls-al.com\/oracle-vm-ovm-rest-api\/","title":{"rendered":"Oracle VM (OVM) REST Api"},"content":{"rendered":"

############################################################################################
\nUpdate 20180331:
\nI tried a couple things from the comment section and can add the following:<\/p>\n

@chaitanya: ovcmclient worked for me also with create and clone<\/p>\n

@Dave: that still gave me the same errors and I am using documentation as its here https:\/\/docs.oracle.com\/cd\/E50245_01\/E50253\/html\/vmprg-rest-example-vm-create-python.html<\/p>\n

@Jeff: try chaitanya's suggestion python-ovmclient it worked for me
\n############################################################################################<\/p>\n

Previous article here:
\nhttp:\/\/blog.ls-al.com\/oracle-ovm-rest-api-example\/<\/p>\n

I am adding a slightly updated script here even though I could not get POST (Create new VM) and PUT (Clone VM) to work yet.<\/p>\n

Using a module for most functions.<\/p>\n

\r\nimport json\r\nfrom time import sleep\r\n\r\ndef get_id_from_name(s,baseUri,obj,name):\r\n  #sp_id=get_id_from_name(s,baseUri,'ServerPool','ovs-home')\r\n  r=s.get(baseUri+'\/'+obj)\r\n  for i in r.json():\r\n    if i['name'] == name:\r\n      id = i['id']['value']\r\n  return id\r\n\r\ndef wait_for_job(joburi,s):\r\n        while True:\r\n            time.sleep(1)\r\n            r=s.get(joburi)\r\n            job=r.json()\r\n            if job['summaryDone']:\r\n                print '{name}: {runState}'.format(name=job['name'], runState=job['jobRunState'])\r\n                if job['jobRunState'].upper() == 'FAILURE':\r\n                    raise Exception('Job failed: {error}'.format(error=job['error']))\r\n                elif job['jobRunState'].upper() == 'SUCCESS':\r\n                    if 'resultId' in job:\r\n                        return job['resultId']\r\n                    break\r\n                else:\r\n                    break     \r\n\r\ndef check_manager_state(baseUri,s):\r\n  #https:\/\/hostname:port\/ovm\/core\/wsapi\/rest\/Manager\r\n  while True:\r\n    r=s.get(baseUri+'\/Manager')\r\n    manager=r.json()\r\n    if manager[0]['managerRunState'].upper() == 'RUNNING':\r\n      break\r\n      time.sleep(1)\r\n      return;\r\n\r\ndef serverList(s,baseUri):\r\n  print "\\nServer List:"\r\n  print "##############"\r\n  r=s.get(baseUri+'\/Server')\r\n  for i in r.json():\r\n    # do something with the content\r\n    print '{:20} {:20}'.format(i['serverRunState'],i['name'])\r\n\r\ndef vmList(s,baseUri):\r\n  print "\\nVM List:"\r\n  print "########"\r\n  r=s.get(baseUri+'\/Vm')\r\n  for i in r.json():\r\n    # print '{:20} {:20}'.format(i['vmRunState'],i['name'])\r\n    print '{:20} {:35} {:30}'.format(i['vmRunState'],i['name'],i['id']['value']),\r\n    for d in i['vmDiskMappingIds']:\r\n      print d['value'],\r\n    print\r\n    # print '{name} '.format(name=i['name'])\r\n    # print i\r\n\r\ndef showVm(s,baseUri,name):\r\n  print "\\nVM Show:"\r\n  print "##########"\r\n  r=s.get(baseUri+'\/Vm')\r\n  for i in r.json():\r\n    if i['name'] == name:\r\n      print '{:20} {:55}'.format(i['vmRunState'],i['name']), \r\n      for d in i['vmDiskMappingIds']:\r\n\tif 'CDROM' not in d['name']:\r\n          print d['value'],\r\n          disk=s.get(baseUri+'\/VmDiskMapping\/'+d['value'])\r\n\t  d = disk.json()\r\n\t  if "obiee" in d['virtualDiskId']['name']:\r\n\t    dName = d['virtualDiskId']['name'].replace('obiee_template',i['name'])\r\n\t    dName = dName.split('img')[0]+'img'\r\n    \t    print 'value: {} and name {} should be renamed -> {}'.format(d['virtualDiskId']['value'],d['virtualDiskId']['name'],dName),\r\n\t    print\r\n\r\ndef cmdVm(s,baseUri,cmd,name):\r\n  print "\\nVM " + cmd\r\n  print "##########"\r\n  vm_id=get_id_from_name(s,baseUri,'Vm',name)\r\n  print vm_id\r\n  r=s.put(baseUri+'\/Vm\/'+vm_id+'\/'+cmd)\r\n  job=r.json()\r\n  # print job\r\n  # wait for the job to complete\r\n  vm_id=wait_for_job(job['id']['uri'],s)\r\n\r\ndef updateVm(s,baseUri,name):\r\n  print "\\nVM Update Vm Disk Names:"\r\n  print "##########################"\r\n  r=s.get(baseUri+'\/Vm')\r\n  for i in r.json():\r\n    if i['name'] == name:\r\n      #print i\r\n      print '{:20} {:20} {:55}'.format(i['id']['value'],i['vmRunState'],i['name'])\r\n      for disk in i['vmDiskMappingIds']:\r\n        if 'CDROM' not in disk['name']:\r\n          #print disk['value'],\r\n          value=s.get(baseUri+'\/VmDiskMapping\/'+disk['value'])\r\n          d = value.json()\r\n\t  oldName = d['virtualDiskId']['name']\r\n          newName = d['virtualDiskId']['name'].replace('obiee_template',i['name'])\r\n          newName = newName.split('img')[0]+'img'\r\n\t  d['virtualDiskId']['name']=newName\r\n\t  d['id']['name']=newName\r\n\t  d['name']=newName\r\n          \r\n          #print 'value: {:20} name: {:55} new name {}'.format(d['virtualDiskId']['value'],d['virtualDiskId']['name'],dName),\r\n          print 'value: {:20} name: {:55} new name {}'.format(disk['value'],oldName,newName)\r\n          #print d\r\n          uri='{base}\/VmDiskMapping\/{id}'.format(base=baseUri,id=d['id']['value'])\r\n\t  #print uri\r\n          r1=s.put(uri,data=json.dumps(d))\r\n          job=r1.json()\r\n    \t  #print job\r\n          # wait for the job to complete\r\n          wait_for_job(job['id']['uri'],s)\r\n\r\n      i['vmDiskMappingIds'][0]['name']='new.img'\r\n      #print i\r\n      uri='{base}\/Vm\/{id}'.format(base=baseUri,id=i['id']['value'])\r\n      #print uri\r\n      \r\n      r=s.put(uri,data=json.dumps(i))\r\n      job=r.json()\r\n      #print job\r\n      # wait for the job to complete\r\n      wait_for_job(job['id']['uri'],s)\r\n\r\ndef updateVmMemory(s,baseUri,name,memory):\r\n  print "\\nVM Update Vm Memory for " + name\r\n  print "########################################"\r\n  vm_id=get_id_from_name(s,baseUri,'Vm',name)\r\n  uri='{base}\/Vm\/{id}'.format(base=baseUri,id=vm_id)\r\n  r=s.get(uri)\r\n  d=r.json()\r\n  #print d\r\n  d['memory']='512'\r\n\r\n  r=s.put(uri,data=json.dumps(d))\r\n  job=r.json()\r\n  #print job\r\n  # wait for the job to complete\r\n  wait_for_job(job['id']['uri'],s)\r\n\r\ndef updateVirtualDisk(s,baseUri,id,newDiskName):\r\n  print "\\nVM Update Vm Disk Mapping for " + id\r\n  print "########################################"\r\n  uri='{base}\/VirtualDisk\/{id}'.format(base=baseUri,id=id)\r\n\r\n  r=s.get(uri)\r\n  disk=r.json()\r\n  #print disk\r\n\r\n  #oldName = disk['virtualDiskId']['name']\r\n  #newName = disk['virtualDiskId']['name'].replace('obiee_template',d['name'])\r\n  #newName = newName.split('img')[0]+'img'\r\n\t  \r\n  disk['name']=newDiskName\r\n\r\n  #disk['name']='newname_system.img'\r\n   \r\n  r=s.put(uri,data=json.dumps(disk))\r\n  job=r.json()\r\n  # wait for the job to complete\r\n  wait_for_job(job['id']['uri'],s)\r\n\r\ndef updateVmDiskNames(s,baseUri,name):\r\n  print "\\nVM Update Vm Disk Names for " + name\r\n  print "########################################"\r\n  vm_id=get_id_from_name(s,baseUri,'Vm',name)\r\n  uri='{base}\/Vm\/{id}'.format(base=baseUri,id=vm_id)\r\n  r=s.get(uri)\r\n  vm=r.json()\r\n\r\n  dNum=0  \r\n  for disk in vm['vmDiskMappingIds']:\r\n        if 'CDROM' not in disk['name']:\r\n\t  dNum = dNum +1\r\n\t  newDiskName=name + "_disk" + str(dNum)\r\n\t  #if "system" in disk['name']:\r\n\t  #  newDiskName=name + "_system.img"\r\n \t  #if "data1" in disk['name']:\r\n\t  #  newDiskName=name + "_data1.img"\r\n\r\n\t  ## update VmDiskMapping as shown in Repository\r\n\t  dMapping=s.get(baseUri+'\/VmDiskMapping\/'+disk['value'])\r\n\t  dm=dMapping.json()\r\n\t  updateVirtualDisk(s,baseUri,dm['virtualDiskId']['value'],newDiskName)\r\n\r\n<\/pre>\n

Main program.<\/p>\n

\r\nimport requests\r\nimport json\r\nfrom ovm_lib import *\r\n#import logging\r\n\r\ns=requests.Session()\r\ns.auth=('admin','mypassword')\r\ns.verify=False #disables SSL certificate verification\r\ns.headers.update({'Accept': 'application\/json', 'Content-Type': 'application\/json'})\r\n\r\novmmServer="192.168.1.223:7002"\r\nprint "Running against OVM Manager Server: " + ovmmServer\r\nbaseUri='https:\/\/'+ovmmServer+'\/ovm\/core\/wsapi\/rest'\r\n\r\n#logging.basicConfig(level=logging.DEBUG)\r\n\r\n## Create VM still failing\r\n## GENERAL_JSON_PARSING_ERROR', u'message': u'GEN_000031:An error occurred parsing the JSON request'\r\n\r\ndef createVm(s,baseUri,repository,serverpool,vmName):\r\n  #file:\/\/\/home\/rrosso\/OvmSDK_3.4.2.1384\/doc\/api\/webservices_r\/resource_VmRs.html#path__Vm.html\r\n  #repo_id=get_id_from_name(s,baseUri,'Repository','ovs1')\r\n  #sp_id=get_id_from_name(s,baseUri,'ServerPool','ovs-home')\r\n  repo_id=get_id_from_name(s,baseUri,'Repository',repository)\r\n  sp_id=get_id_from_name(s,baseUri,'ServerPool',serverpool)\r\n  #print 'repo_id {:20} ServerPool Id {:55}'.format(repo_id,sp_id)\r\n  #OVM> create Vm name=MyVM repository=MyRepository domainType=XEN_HVM \\ \r\n  #server=MyServer startPolicy=USE_POOL_POLICY on ServerPool name=MyServerPool\r\n\r\n  data={ "name": vmName,\r\n         "description": "A virtual machine created using the REST API",\r\n         "vmDomainType": "XEN_PVM",\r\n\t "repositoryId": repo_id,\r\n         "serverPoolId": sp_id }\r\n\r\n#  data={'serverPoolId':'0004fb00000200006aa35973e4d0e5af','repositoryId':'0004fb00000300000c6c2c52c5708b65'}\r\n  print data\r\n  uri='{base}\/Vm'.format(base=baseUri)\r\n  print uri\r\n  #print json.dumps(data)\r\n  r=s.post(uri,data=json.dumps(data))\r\n  job=r.json()\r\n  print job\r\n  # wait for the job to complete\r\n  vm_id=wait_for_job(job['id']['uri'],s)\r\n\r\n## CloneVM failing\r\n## The value for the argument "serverPoolId" was found to be null\r\ndef cloneVm(s,baseUri,templateVm,vmName):\r\n  repo_id=get_id_from_name(s,baseUri,'Repository','ovs1')\r\n  sp_id=get_id_from_name(s,baseUri,'ServerPool','ovs-home')\r\n  template_id=get_id_from_name(s,baseUri,'Vm',templateVm)\r\n  \r\n  print 'clone {} into repo_id {:20} ServerPool Id {:55}'.format(template_id,repo_id,sp_id)  \r\n  \r\n  data={ "serverPoolId": sp_id,\r\n  \t "repositoryId": repo_id,\r\n  \t "createTemplate": False\r\n        }\r\n\r\n  uri='{base}\/Vm\/{vmId}\/clone'.format(base=baseUri,vmId=template_id)\r\n  r=s.put(uri,data=json.dumps(data))\r\n  job=r.json()\r\n  print job\r\n  # wait for the job to complete\r\n  vm_id=wait_for_job(job['id']['uri'],s)\r\n  print "new vm id:" + vm_id\r\n\r\n  ## change vm name here?\r\n\r\nif __name__ == "__main__":\r\n  print\r\n  print\r\n\r\n  #check_manager_state(baseUri,s)\r\n\r\n  #createVm(s,baseUri,'VM3')\r\n  createVm(s,baseUri,'ovs2','ovs-home','ovs2-VM3')\r\n  #cloneVm(s,baseUri,'Ubuntu.0','VM4')\r\n  \r\n  serverList(s,baseUri)\r\n  vmList(s,baseUri)\r\n\r\n  #updateVmMemory(s,baseUri,'VM2','512')\r\n\r\n  #updateVmDiskNames(s,baseUri,'VM2')\r\n  #showVm(s,baseUri,'VM2')\r\n\r\n  #cmdVm(s,baseUri,'start','VM2')\r\n  #cmdVm(s,baseUri,'stop','VM2')\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"

############################################################################################ Update 20180331: I tried a couple things from the comment section and can add the following: @chaitanya: ovcmclient worked<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[29],"tags":[],"class_list":["post-1031","post","type-post","status-publish","format-standard","hentry","category-ovm"],"_links":{"self":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts\/1031","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/comments?post=1031"}],"version-history":[{"count":0,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts\/1031\/revisions"}],"wp:attachment":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/media?parent=1031"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/categories?post=1031"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/tags?post=1031"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}