示例#1
0
def shutdownvm(vmname, istty, api):
	"""call: 'shutdown vm VM'
	description: 'Stop running the given instance. While an instance is not running, no RAM usage charges are incurred.
	             .Note: Do not attempt to shut down your instance using the standard shut down feature of its operating system.
	             .Your instance will be restarted immediately and usage charges will continue.'
	args: 'VM: Name of the instance to stop running.'
	errors: 'VM name is invalid or VM does not exist: Return exit code 3
	        .VM not in a state to be shut down (eg. not running): Return exit code 4
	        .An error occurred while waiting for VM to shut down: Return exit code 5
	        .    Note: In this case, the VM may have not shut down correctly.
	        .    You should check with "show vm" and the out-of-band console ("console")
	        .    If the VM remains uncontactable and is still running after several minutes,
	        .    please contact OrionVM technical support.
	        .VM failed to shut down: Return exit code 6
	        .    This is a serious error. Plesae contact OrionVM technical support
	        .    and we will resolve the issue.'
	"""
	vm = getvmby(vmname, api, what='hostname')
	if vm is None:
		if istty:
			print vmname, "does not exist"
		return 3
	vmid = vm['vm_id']
	if vm['state'] != 2:
		if istty:
			print vmname, "is not in state to be shut down"
		return 4

	api.actionvm(vmid=vmid,action='shutdown')

	try:
		if istty:
			stdout.write("Shutting down...")
			stdout.flush()
		while 1:
			sleep(3)
			if istty:
				stdout.write('.')
				stdout.flush()
			vm = getvmby(vmname, api, what='hostname')
			if vm['state'] == 0:
				break
			if vm['state'] > 9:
				if istty:
					print "VM failed to shut down. Please contact OrionVM technical support and we will resolve the issue."
				return 6
	except:
		if istty:
			print "Error occurred while shutting down VM."
			print "Warning: VM may or may not have shut down correctly."
			print '         Please try "show vm %s" to check if VM has shut down.' % vmname
			print '         If VM has not shut down after several minutes'
			print '         and you cannot connect to the out of band console ("console %s"),' % vmname
			print '         we reccomend you contact OrionVM technical support'
			print '         and we will address the situation.'
		return 5

	if istty:
		print "Done"
示例#2
0
文件: boot.py 项目: macropin/ovm-ctl
def bootvm(vmname, istty, api):
	"""call: 'boot vm VM'
	description: 'Begin running the given instance.'
	args: 'VM: Name of the instance to boot up.'
	errors: 'If VM name is invalid or VM does not exist: Returns exit code 3
	        .If VM is not ready to be booted (eg. is already running): Returns exit code 4
	        .If VM fails to correctly boot (booting is aborted): Returns exit code 5
	        .If an error occurs while booting: Returns exit code 6
	        .    NOTE: In this case, the VM may still boot correctly.
	        .    Try "show vm" to check if the VM is now running or still booting.'
"""
	vm = getvmby(vmname, api, what='hostname')
	if vm is None:
		if istty:
			print vmname, "does not exist"
		return 3
	vmid = vm['vm_id']
	if vm['state'] != 0:
		if istty:
			print vmname, "is not in state to be booted"
		return 4

	api.deploy(vmid=vmid)

	if istty:
		stdout.write('Booting.')
		stdout.flush()
	try:
		while 1:
			sleep(3)
			if istty:
				stdout.write('.') # Give the user some feedback that it isn't frozen
				stdout.flush()
			vm = getvmby(vmname, api, what='hostname')
			if vm['state'] not in (1,2):
				if istty:
					print "Failed to boot"
				return 5
			if vm['state'] == 2:
				break
	except:
		if istty:
			print 'Unknown error while waiting for VM to boot.'
			print 'Warning: VM is not booted. However, it is still booting.'
			print '         Please use "show vm %s" to check if VM successfully booted.' % vmname
		return 6

	if istty:
		print "Done"
示例#3
0
文件: attach.py 项目: orionvm/ovm-ctl
def attachip(ipname, vmname, istty, api):
        r"""call: 'attach ip IP to vm VM'
        description: 'Attach a given IP to a given VM,
	             .creating an ethernet interface on the VM.'
        args: 'IP: The IP Address or Friendly Name of the IP to attach.
	      .VM: The name of the VM to attach it to.'
        errors: 'For non-existing or invalid VM: Return exit code 3
	        .For non-existing or invalid IP: Return exit code 4'
        """
	vm = getvmby(vmname, api, what='hostname')
	if vm is None:
		if istty:
			print "VM %s does not exist" % vmname
		return 3

	ipaddr = None
	ip_pool = api.ip_pool()
	for ip in ip_pool:
		if ip['ip'] == ipname:
			ipaddr = ip['ip']
	if not ipaddr:
		for ip in ip_pool:
			if ip['friendly'] == ipname:
				ipaddr = ip['ip']
	if not ipaddr:
		if istty:
			print "IP %s does not exist" % ipname
		return 4
	
	vmid = vm['vm_id']
	api.attachip(ip=ipaddr, vmid=vmid)

	if istty:
		print "Attached ip %s to %s" % (ipname, vmname)
示例#4
0
def runconsole(vmname, istty, api):
	"""call: 'console VM'
	description: 'Log into the out-of-band management console on the given instance.
	             .This is roughly equivilent to directly connecting to the serial port on the machine.
	             .This command requires the programs "grep" and "ssh" be installed
	             .and accessible in a folder listed in the PATH environment variable.
	             .See NOTES section of the man page for extra notes.'
	args: 'VM: The instance to connect to.'
	errors: 'VM does not exist: Return exit code 3
	        .Fail to run ssh: Return exit code 4'
	"""

	console_ip = '49.156.16.12' # IP of OVM console server
	console_rsa = "%s ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1ZKuRj8UkoCUvGKGSGd9vQAlP3uCmq+8vBdF/SeZ2sr0Gf9+ZTn5Di8EGBBwOArU791VTtTWTg2kSC6xbearWH9xxD8omnjaYyBmqBLZ0yimVuIQWh3QS5YglxdQoGZUJ7a7ddQDLvO11f4eirP6HcNYSfGT5070jqoEiETmdcoQsdsxdJFs6GBssMoMij1i4HRDbCDPMdViEOQ19LQBCd3LsTFcmZJ/LIO9BCxsSeyV5IPkUVVzVc29JOmqDbCTcHuOidrupVheSSkZjhB0Cq6L8tOaFP/5gj7Ab6PiZPC3hOoLFgPJ3zk50RfAT2/enKqwHQFnN1QzfBBMg1kJiw==" % console_ip
	
	# Check vmname exists. This also checks user/pswd is valid.
	if not getvmby(vmname, api, what='hostname'):
		if istty:
			print 'Cannot find vm "%s"' % vmname
		return 3
	
	# Write a temporary known hosts file, which means we don't clutter up user's ~/.ssh/known_hosts:
	hostfile = tmpfile()
	hostfile.write(console_rsa)
	hostfile.flush()

	try:
		proc = Popen(['ssh', '-qqt', '-oGlobalKnownHostsFile=%s' % hostfile.name, 'console@%s' % console_ip, "%s %s %s" % (api.user, vmname, api.pswd)])
	except OSError:
		if istty:
			print 'Failed to start remote shell. Is the program "ssh" installed and accessbile?'
		return 4
示例#5
0
def clearcontext(key, vmname, istty, api):
	"""call: 'clear context key KEY from vm VM'
	description: 'Remove the given key value data from the given VM context store.
	             .THIS FUNCTION IS NOT YET IMPLEMENTED'
	args: 'KEY: Key of the data to remove from the key value store
	      .VM: The name of the VM to clear the key value data from.'
	errors: 'If the given vm does not exist, exit code 3 is returned
	        .If the given key does not exist in the context store, exit code 4 is returned'
	"""
	key = key.upper()

	vm = getvmby(vmname, api, what='hostname')
	if not vm: 
		if istty:
			print "VM %s does not exist" % vmname
		return 3

	try:
		raise Exception("This function has not been implemented yet. Stay tuned.")
		# api.set_context(vmid=vm['vmid'],key=key,value=None)
	except CurlException, e:
		if e.retcode != 404:
			raise
		if istty:
			print 'VM %s does not have context key %s' % (vmname, key)
		return 4
示例#6
0
def detachip(ipname, vmname, istty, api):
	"""call: 'detach ip IP from VM'
	description: 'Detach the given IP from the instance its attached to, allowing it to be freed or attached to a different instance instead.'
	args: 'IP: The IP address or friendly name you want to detach.
	      .VM: The name of the instance that the ip is currently attached to.'
	errors: 'VM does not exist: Returns exit code 3
	        .Invalid IP or no matching friendly IP name found: Returns exit code 4'
	"""
	vm = getvmby(vmname, api, what='hostname')
	if vm is None:
		if istty:
			print "VM %s does not exist" % vmname
		return 3

	# look up ip by friendly name
	ip = get_ip(ipname, api, istty)
	if not ip:
		if istty:
			print 'IP address invalid, or no matching friendly name found.'
		return 4
	
	vmid = vm['vm_id']
	api.detachip(ip=ip, vmid=vmid)

	if istty:
		print "Detached %s from %s" % (ipname, vmname)
示例#7
0
def detachdisk(diskname, vmname, istty, api):
	"""call: 'detach disk DISK from VM'
	description: 'Detach the given disk from the instance its attached to, removing it from that system but freeing it to be destroyed or attached elsewhere.'
	args: 'DISK: Name of the disk to detach.
	      .VM: Name of the instance that the disk is currently attached to.'
	errors: 'VM does not exist: Returns exit code 3
	        .Disk not attached to VM, or disk does not exist: Returns exit code 4'
	"""

	vm = getvmby(vmname, api, what='hostname')
	if vm is None:
		if istty:
			print "VM %s does not exist" % vmname
		return 3

	found = False
	for disk in vm['disks']:
		if disk['name'] == diskname:
			found = True
	if not found:
		if istty:
			print "Disk %s not attached to VM %s" % (diskname, vmname)
		return 4

	vmid = vm['vm_id']
	api.detachdisk(vmid=vmid, diskname=diskname)

	if istty:
		print "Detached %s from %s" % (diskname, vmname)
示例#8
0
def attachdisk(diskname, vmname, target, istty, api):
	r"""call: 'attach disk DISK to VM with target TARGET'
        description: 'Attach a given disk to a given VM, locking the disk
	             .and making it appear as a device on the VM.'
        args: 'DISK: The name of the disk to attach.
	      .VM: The name of the VM to attach to.
	      .TARGET: The name of the device (the device will appear as /dev/TARGET).
	      .        Must be of form: "xvd%s%d" ==> ((a, b, c, ..., aa, ab, etc), positive integer),
	      .        eg: "xvda1", "xvda2", "xvdb1", "xvdb25".
	      .        Note: "xvdz" is reserved. Valid range is "xvda"-"xvdy", then "xvdaa", etc.'
        errors: 'For non-existing or invalid VM: Returns exit code 3
	        .For non-existing or invalid Disk: Returns exit code 4
	        .For invalid target: Returns exit code 5'
        """
	vm = getvmby(vmname, api, what='hostname')
	if vm is None:
		if istty:
			print "VM %s does not exist" % vmname
		return 3

	if not diskname in [disk['name'] for disk in api.disk_pool()]:
		if istty:
			print "Disk %s does not exist" % diskname
		return 4

	# Note xvdz is reserved for some extra OVM features in the pipeline
	if target.startswith('xvdz') or not re.match('xvd[a-z]+[1-9][0-9]*', target):
		if istty:
			print "Target %s is not valid" % target
		return 5

	vmid = vm['vm_id']
	api.attachdisk(vmid=vmid, diskname=diskname, target=target, readonly=False)
	if istty:
		print "Attached %s to %s" % (diskname, vmname)
示例#9
0
def destroyvm(vmname, istty, api):
	"""call: 'destroy vm VM'
	description: 'Destroy given non-running instance.
	             .Note that any attached disks or IPs will still exist and continue to incur charges.'
	args: 'VM: Name of the instance to delete.'
	errors: 'VM does not exist: Return exit code 3'
	"""
	vm = getvmby(vmname, api, what='hostname')	
	if vm is None:
		print "VM does not exist"
		return 3

	vmid = vm['vm_id']

	api.dropvm(vmid=vmid)

	if istty:
		print "Destroyed vm %s" % vmname
示例#10
0
def runconsole(vmname, istty, api):
	"""call: 'console VM'
	description: 'Log into the out-of-band management console on the given instance.
	             .This is roughly equivilent to directly connecting to the serial port on the machine.
	             .This command requires the programs "grep" and "ssh" be installed
	             .and accessible in a folder listed in the PATH environment variable.
	             .See NOTES section of the man page for extra notes.'
	args: 'VM: The instance to connect to.'
	errors: 'VM does not exist: Return exit code 3
	        .Fail to run ssh: Return exit code 4
	        .ssh exits with non-zero code (generic error): Return exit code 5
	        .ssh exits with code 255 (connection or protocol error): Return exit code 6'
	"""

	console_ip = '49.156.16.12' # IP of OVM console server
	console_rsa = "%s ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzufEnOKEipxlbNqqWGy/yYMJi9g9/Co/dL4D+3RzhfH4aBDnIlrM8vfOAtIZ3UoXy7Bo9ZQdu+5XZVyZ4+ejQFJdjnphHEf82dJpwKhWajnCkqsakUBt9RoAVRKOJYxI9lCdW9xUlmr9CwpmWEnpy+fQwV4mDAa2q/eaVPk6cHvwCwYNbdyHahBrmP2EMsLShs4YQfY5hsufAN8KJPClPTn4qHYaHLHO6WwcB11uZJXEGLV4tvyfIpXVt8h6RTY4A7/b67eFFwz93Bca2/VElXgSNjW8IjF8dJdWrGNTj+2ndNE0ZdJYzO//lRyy/n7vpVUH7UmWLz4S/XfSYwZ9D" % console_ip
	
	# Check vmname exists. This also checks user/pswd is valid.
	if not getvmby(vmname, api, what='hostname'):
		if istty:
			print 'Cannot find vm "%s"' % vmname
		return 3
	
	# Write a temporary known hosts file, which means we don't clutter up user's ~/.ssh/known_hosts:
	hostfile = tmpfile()
	hostfile.write(console_rsa)
	hostfile.flush()

	try:
		proc = Popen(['ssh', '-qqt', '-oGlobalKnownHostsFile=%s' % hostfile.name, 'console@%s' % console_ip, "%s %s %s" % (api.user, vmname, api.pswd)])
	except OSError:
		if istty:
			print 'Failed to start remote shell. Is the program "ssh" installed and accessbile?'
		return 4

	ret = proc.wait()
	if ret:
		if istty:
			print 'Remote shell failed with exit code %d' % ret
		if ret == 255:
			return 6
		else:
			return 5
示例#11
0
def addcontext(vmname, key, value, istty, api):
	"""call: 'add context to vm VM with KEY = VALUE'
	description: 'Add a new context item into the key value context storage for the given VM.
	             .Valid keys must not contain whitespace but values may.
	             .If a key already exists, it will be overwritten.'
	args: 'VM: Name of the vm to attach the key value data to.
	      .KEY: The key to map the given value to. May not contain whitespace.
	      .VALUE: The value to attach to the given key.'
	errors: 'If the VM does not exist: Return exit code 3'
	"""
	key = key.upper()

	vm = getvmby(vmname, api, what='hostname')
	if not vm:
		if istty:
			print 'VM %s does not exist' % vmname
		return 3

	api.set_context(vmid=vm['vm_id'], key=key, value=value)
示例#12
0
文件: setram.py 项目: orionvm/ovm-ctl
def setram(vmname, ram, istty, api):
	"""call: 'set ram on vm NAME to SIZE'
	description: 'Update the ram of a VM. VM Must be stopped.'
	args: 'NAME: The name of the VM.
	      .SIZE: Amount of RAM to set on the VM.
	      .      Format is a number followed by M for megabytes or G for gigabytes.
	      .		 Value must be between 512M and 64G (65536M)
	errors: 'VM name is invalid or VM does not exist: Return exit code 3
	        .Incorrect format for SIZE: Return exit code 5'
	"""
	vm = getvmby(vmname, api, what='hostname')
	if not vm:
		if istty:
			print 'VM %s does not exist' % vmname
		return 3

	if vm['state'] != 0:
		if istty:
			print vmname, " is not in a state to have ram changed"
		return 4

	ram = ram.upper()
	if not re.match('^(((\d*[.])?\d+G)|([1-9][0-9]+M))$', ram):
		if istty:
			print 'Bad format for ram size: Must be a number followed by "M" for megabytes or "G" for gigabytes.'
		return 5

	unit = ram[-1]
	ram = float(ram[0:-1])
	if unit == "G":
		ram = int(ram * 1024)
		
	if ram < 512 or ram > 65536:
		if istty:
			print 'RAM must be between 512M and 64G (65536M)'
		return 5	
		
	ram = "%sM" % ram

	api.set_ram(vmid=vm['vm_id'], ram=ram)
示例#13
0
def vmwizard(name, memsize, disksize, image, boot, isatty, api):
	"""call: 'wizard vm NAME [with [ram MEMSIZE] [disk DISKSIZE] [image IMAGE]] [and boot]'
	description: 'This command is a wizard to create a ready-to-run server with the given NAME.
	             .Any arguments not provided will be prompted. If the command has "and boot" on the end,
	             .the machine will be booted immediately after creation.
	             .Further details:
	             .    Create a new VM and call it NAME. Create a disk and ip (of the same NAME) and attach them.
	             .    The disk will have size DISKSIZE and image IMAGE. The VM will have ram MEMSIZE.
	             .    If "and boot" is given, the VM is then booted.
	             .    If "and boot" is not given, it is only prompted if no other arguments are provided.'
	args: 'NAME: The name to give to the VM, disk and ip address to be created.
	      .MEMSIZE: The amount of RAM to give the VM.
	      .         Format is a number followed by M for megabytes or G for gigabytes.
	      .DISKSIZE: The size of the new disk. See the SIZE argument for "create disk".'
	output: 'If creating a windows vm, prints the inital password'
	errors: 'NOTE: In the event of any sort of error, the VM may have only been partially constructed.
	        .      Please use the show commands and check what has and has not been created.
	        .Not all arguments provided and in quiet mode: Return exit code 1 (invalid command)
	        .Incorrect format for MEMSIZE: Return exit code 3
	        .Incorrect format for DISKSIZE: Return exit code 4
	        .Invalid value for IMAGE: Return exit code 5
	        .Already a disk, ip or VM called NAME: Return exit code 6
	        .An error occurred in booting the VM: Return exit code 7
	        .    Note: This means that the VM was successfully created.
	        .    Failure to boot means it is now in a Shut Down state.
	        .Any other error occurred during the operation: Return exit code 8
"""
	boot = boot == " and boot"

	# Get inputs
	if not isatty and not (memsize and disksize and image):
		return 1
	askboot = not (memsize or disksize or image or boot)
	if not memsize:
		memsize = raw_input("How much RAM? ")
	if not disksize:
		disksize = raw_input("How much disk space? ")
	if not image:
		show.showimages(isatty, api)
		image = raw_input("Please select one of the images above: ")
	if askboot:
		boot = raw_input("Would you like to boot the VM immediately? (y/n) > ") == "y"

	if show.getvmby(name, api, what='hostname'):
		if isatty:
			print "A VM with that name already exists."
		return 6

	type = ['paravirt', 'HVM']['windows' in image]
	ret = create.createvm(name, memsize, type, isatty, api)
	if ret == 3:
		return 3
	if ret:
		raise Exception("Unknown return value from createvm: %d"%ret)

	ret = create.createdisk(name, disksize, image, isatty, api)
	if ret == 3:
		return 5
	if ret == 4:
		return 4
	if ret == 5:
		return 6
	if ret == 6:
		return 8
	if ret:
		raise Exception("Unknown return value from createdisk: %d"%ret)

	ret = attach.attachdisk(name, name, ('windows' in image) and "hda" or "xvda1", isatty, api)
	if ret:
		raise Exception("Unexpected return value from attachdisk: %d"%ret)

	ret = create.createip(name, isatty, api)
	if ret:
		raise Exception("Unknown return value from createip: %d"%ret)

	ret = attach.attachip(name, name, isatty, api)
	if ret:
		raise Exception("Unknown return value from attachip: %d"%ret)

	if 'windows' in image:
		addcontext(name, 'WINDOWS', 'true', isatty, api)
		setpass(name, '', isatty, api)

	if boot:
		ret = bootvm(name, isatty, api)
		if ret == 5:
			return 7
		if ret == 6:
			return 8
		if ret:
			raise Exception("Unexpected return value from bootvm: %d"%ret)