예제 #1
0
	def on_init(self, *args, **kwargs):
		bus.on("before_hello", self.on_before_hello)		
		bus.on("before_host_init", self.on_before_host_init)
		bus.on("before_restart", self.on_before_restart)

		msg_service = bus.messaging_service
		producer = msg_service.get_producer()
		producer.on("before_send", self.on_before_message_send)
		
		# Set the hostname to this instance's public hostname
		cnf = bus.cnf
		try:
			hostname_as_pubdns = int(cnf.rawini.get('ec2', 'hostname_as_pubdns'))
		except ConfigParser.Error:
			hostname_as_pubdns = True
		if hostname_as_pubdns:
			system2("hostname " + self._platform.get_public_hostname(), shell=True)		
		
		if disttool.is_ubuntu():
			# Ubuntu cloud-init scripts may disable root ssh login
			for path in ('/etc/ec2-init/ec2-config.cfg', '/etc/cloud/cloud.cfg'):
				if os.path.exists(path):
					c = filetool.read_file(path)
					c = re.sub(re.compile(r'^disable_root[^:=]*([:=]).*', re.M), r'disable_root\1 0', c)
					filetool.write_file(path, c)
			
		# Add server ssh public key to authorized_keys
		authorized_keys_path = "/root/.ssh/authorized_keys"
		if os.path.exists(authorized_keys_path):
			c = filetool.read_file(authorized_keys_path)
			ssh_key = self._platform.get_ssh_pub_key()
			idx = c.find(ssh_key)
			if idx == -1:
				if c and c[-1] != '\n':
					c += '\n'
				c += ssh_key + "\n"
				self._logger.debug("Add server ssh public key to authorized_keys")
				filetool.write_file(authorized_keys_path, c)
			elif idx > 0 and c[idx-1] != '\n':
				c = c[0:idx] + '\n' + c[idx:]
				self._logger.warn('Adding new-line character before server SSH key in authorized_keys file')
				filetool.write_file(authorized_keys_path, c)
				
		# Mount ephemeral devices
		# Seen on eucalyptus: 
		# 	- fstab contains invalid fstype and `mount -a` fails  
		mtab = Mtab()
		fstab = Fstab()
		for device in self._platform.instance_store_devices:
			if os.path.exists(device) and fstab.contains(device) and not mtab.contains(device):
				entry = fstab.find(device)[0]
				try:
					mount(device, entry.mpoint, ('-o', entry.options))
				except:
					self._logger.warn(sys.exc_info()[1])
예제 #2
0
	def apply_public_ssh_key(self, source_path=None):
		source_path = source_path or self.public_key_path 
		if not os.path.exists(self.ssh_dir):
			os.makedirs(self.ssh_dir)
			rchown(self.name, self.ssh_dir)
		
		pub_key = read_file(source_path,logger=self._logger)
		path = os.path.join(self.ssh_dir, 'authorized_keys')
		keys = read_file(path,logger=self._logger) if os.path.exists(path) else ''
		
		if not keys or not pub_key in keys:
			write_file(path, data='\n%s %s\n' % (pub_key, self.name), mode='a', logger=self._logger)
			rchown(self.name, path)
예제 #3
0
def get_cache_size():
	mcd_conf = read_file(mcd_conf_path)
	if mcd_conf:
		result = re.search(mem_re, mcd_conf)
		if result:
			return result.group('memory')
		else: 
			return MemcachedCnfController.options.cache_size.default_value
예제 #4
0
	def records(self):
		l = []
		text = read_file(self.path) or ''
		for line in text.splitlines():
			if line.strip() and not line.strip().startswith('#'):
				record = PgHbaRecord.from_string(line)
				l.append(record)
		return l
예제 #5
0
def set_cache_size(sub):
		mcd_conf = read_file(mcd_conf_path)
	
		if mcd_conf:
			if expression.findall(mcd_conf):
				write_file(mcd_conf_path, re.sub(expression, sub, mcd_conf))
			else:
				write_file(mcd_conf_path, sub, mode='a')
예제 #6
0
 def _read_ssh_keys_file(self):
     content = read_file(
         self.authorized_keys_file,
         msg="Reading autorized keys from %s" % self.authorized_keys_file,
         logger=self._logger,
     )
     if content == None:
         raise UpdateSshAuthorizedKeysError("Unable to read ssh keys from %s" % self.authorized_keys_file)
     return content
예제 #7
0
    def disable_requiretty(self):
        """
		requiretty      If set, sudo will only run when the user is logged in to a real tty.  
		When this flag is set, sudo can only be  run from a login session and not via other means 
		such  as cron(8) or cgi-bin scripts.  This flag is off by default on all systems but CentOS5.
		"""
        path = "/etc/sudoers"
        self._logger.debug("Disabling requiretty in %s" % path)
        if not disttool.is_ubuntu():
            orig = read_file(path)
            new = re.sub("Defaults\s+requiretty", "\n", orig)
            if new != orig:
                write_file(path, new)
예제 #8
0
	def get_user_data(self, key=None):
		cnf = bus.cnf
		if self._userdata is None:
			path = cnf.private_path('.user-data')
			if os.path.exists(path):
				rawmeta = read_file(path)
				if not rawmeta:
					raise PlatformError("Empty user-data")
				self._userdata = self._parse_user_data(rawmeta)
		if key and self._userdata:
			return self._userdata[key] if key in self._userdata else None
		else:
			return self._userdata
예제 #9
0
파일: mdadm.py 프로젝트: golovast/scalarizr
	def _get_array_by_device(self, device):
		devname = os.path.basename(device)
		out = filetool.read_file('/proc/mdstat')
		if not out:
			raise Exception("Can't get array info from /proc/mdstat.")

		for line in out.splitlines():
			if devname in line:
				array = line.split()[0]
				break
		else:
			raise Exception("Device %s isn't part of any array." % device)

		return '/dev/%s' % array
예제 #10
0
파일: mdadm.py 프로젝트: golovast/scalarizr
	def __init__(self):
		if not os.path.exists(MDADM_EXEC):
			if disttool.is_redhat_based():
				system2(('/usr/bin/yum', '-d0', '-y', 'install', 'mdadm', '-x', 'exim'), raise_exc=False)
			else:
				mgr = dynimp.package_mgr()				
				mgr.install('mdadm', mgr.candidates('mdadm')[-1])
		for location in ['/etc ', '/lib']:
			path = os.path.join(location, 'udev/rules.d/85-mdadm.rules')
			if os.path.exists(path):

				rule = read_file(path)
				if rule:
					rule = re.sub(re.compile('^([^#])', re.M), '#\\1', rule)
					write_file(path, rule)

		self._raid_devices_re  	= re.compile('Raid\s+Devices\s+:\s+(?P<count>\d+)')
		self._total_devices_re 	= re.compile('Total\s+Devices\s+:\s+(?P<count>\d+)')
		self._state_re         	= re.compile('State\s+:\s+(?P<state>.+)')
		self._rebuild_re       	= re.compile('Rebuild\s+Status\s+:\s+(?P<percent>\d+)%')
		self._level_re			= re.compile('Raid Level : (?P<level>.+)')
예제 #11
0
def main():
	
	parser = OptionParser(usage="Usage: %prog [options] key=value key2=value2 ...")
	parser.add_option("-e", "--endpoint", dest="endpoint", default=None, help="Messaging server URL")
	parser.add_option("-q", "--queue", dest="queue", help="Queue to send message into")
	parser.add_option("-n", "--name", dest="name", help="Message name")
	parser.add_option("-f", "--file", dest="msgfile", help="File with message")
	
	(options, args) = parser.parse_args()
	
	if not options.queue or (not options.msgfile and not options.name):
		print parser.format_help()
		sys.exit()
	
	
	init_script()

	msg_service = bus.messaging_service
	producer = msg_service.get_producer()
	if options.endpoint:
		producer.endpoint = options.endpoint

	msg = msg_service.new_message()

	if options.msgfile:
		str = read_file(options.msgfile, error_msg='Cannot open message file %s' % options.msgfile)
		if str:
			msg.fromxml(str)
		
	if msg.name:
		msg.name = options.name
		
	for pair in args:
		k, v = pair.split("=")
		msg.body[k] = v
		
	producer.send(options.queue, msg)

	print "Done"
예제 #12
0
def new_queryenv():
	init_cnf()
	key_path = os.path.join(bus.etc_path, ini.get('general', 'crypto_key_path'))
	server_id = ini.get('general', 'server_id')
	url = ini.get('general','queryenv_url')
	api_version = QUERYENV_API_VERSION
	if not api_version:
		cnf = bus.cnf
		if not bus.scalr_version:
			version_file = cnf.private_path('.scalr-version')
			if os.path.exists(version_file):
				bus.scalr_version = tuple(read_file(version_file).strip().split('.'))
		
		if bus.scalr_version:
			if bus.scalr_version >= (3, 5, 3):
				api_version = '2012-07-01'
			elif bus.scalr_version >= (3, 1, 0):
				api_version = '2012-04-17'
			else:
				api_version = '2010-09-23'
		else:
			api_version = '2012-07-01'
	return QueryEnvService(url, server_id, key_path, api_version)		
예제 #13
0
	def status(self):
		'''
		@return: Service status
		@rtype: scalarizr.util.initdv2.Status
		'''
		if self.pid_file:
			if not os.path.exists(self.pid_file):
				return Status.NOT_RUNNING
			pid = read_file(self.pid_file).strip()
			if os.path.isfile('/proc/%s/status' % pid):
				try:
					fp = open('/proc/%s/status' % pid)
					status = fp.read()
				except:
					return Status.NOT_RUNNING
				finally:
					fp.close()
					
				if status:
					pid_state = re.search('State:\s+(?P<state>\w)', status).group('state')
					if pid_state in ('T', 'Z'):
						return Status.NOT_RUNNING
			else:
				return Status.NOT_RUNNING
		if self.socks:
			try:
				for sock in self.socks:
					timeout = sock.timeout
					sock.timeout = 1
					try:
						wait_sock(sock)
					finally:
						sock.timeout = timeout
			except InitdError:
				return Status.NOT_RUNNING
		
		return Status.RUNNING
예제 #14
0
			if not options.queue or (not options.msgfile and not options.name):
				com=Help(com_dict)
				com.run()
				sys.exit()

			msg_service = bus.messaging_service
			producer = msg_service.get_producer()

			init_cnf()

			producer.endpoint = options.endpoint or ini.get('messaging_p2p', 'producer_url')	
			msg = msg_service.new_message()

			if options.msgfile:
				str = read_file(options.msgfile, error_msg='Cannot open message file %s' %
					options.msgfile)
				if str:
					msg.fromxml(str)
			else:
				msg.body = kv

			if options.name:
				msg.name = options.name

			producer.send(options.queue, msg)

			print "Done"		

		if options.reinit:
			print 'Call scalarizr to reinitialize role (see /var/log/scalarizr.log for results)'
			
예제 #15
0
		elif optparser.values.gen_key:
			# Generate key-pair
			do_keygen()
			sys.exit()

		logger.debug("Initialize scalarizr...")
		_init()

		# Starting scalarizr daemon initialization
		globals()['_pid'] = pid = os.getpid()		
		logger.info('[pid: %d] Starting scalarizr %s', pid, __version__)
		
		# Check for another running scalarzir 
		if os.path.exists(PID_FILE):
			try:
				another_pid = int(read_file(PID_FILE).strip())
			except ValueError:
				pass
			else:
				if pid != another_pid and os.path.exists('/proc/%s/status' % (another_pid,)):
					logger.error('Cannot start scalarizr: Another process (pid: %s) already running', another_pid)
					sys.exit(1)
					
		# Write PID
		write_file(PID_FILE, str(pid))
			
		cnf = bus.cnf
		cnf.on('apply_user_data', _apply_user_data)
		
		if optparser.values.configure:
			do_configure()
예제 #16
0
	def private_key(self):
		if not os.path.exists(self.private_key_path):
			self.generate_private_ssh_key()
			self.apply_private_ssh_key()
		return read_file(self.private_key_path, logger=self._logger)
예제 #17
0
	def public_key(self):
		if not os.path.exists(self.public_key_path):
			key = self.extract_public_ssh_key()
			write_file(self.public_key_path, key, logger=self._logger)
			self.apply_public_ssh_key()
		return read_file(self.public_key_path, logger=self._logger)
예제 #18
0
파일: lvm2.py 프로젝트: golovast/scalarizr
def lvm_group_b64(vg):
	vgfile = '/etc/lvm/backup/%s' % os.path.basename(vg)
	if os.path.exists(vgfile):
		return binascii.b2a_base64(read_file(vgfile))
예제 #19
0
	def _get_state(self):
		filename = self.private_path('.state')
		if not os.path.exists(filename):
			return ScalarizrState.UNKNOWN
		return str.strip(filetool.read_file(filename, logger=self._logger))