예제 #1
0
 def sendmail(trace):
     m = mailer.Message()
     m.set_headers(to=status.admin,
                   cc="%s, %s" % (status.email, status.builder_list),
                   subject="fatal python exception")
     m.write("%s\n" % trace)
     m.write("during: %s\n" % status.get())
     m.send()
예제 #2
0
파일: handler.py 프로젝트: rudevdr/fsman
def remove_stdout(path):
    filename = status.get(path, "stdout")
    try:
        os.remove(filename)
    except FileNotFoundError:
        pass
    except TypeError:
        pass
예제 #3
0
def sample_responses(input_text):
	user_message = str(input_text).lower()
	
	if user_message in ("oi", "ola", "olá"):
		return "E ai, blz?"

	elif user_message == "contato":
		return "http://alexsetta.com/ \n            Acesse! ☝️"

	elif user_message in ("info", "inf", "rsi"):
		return status.get()

	return "Comando inválido. Tente: /help?"
	
예제 #4
0
def read_display_operation():
    #TODO: Remove ^[[K0 for clear line from printer
    running = True

    while status.exists(get_path()):
        path = get_path()
        stdout = status.get(path, "stdout")
        if os.path.exists(stdout):
            read_operation(stdout)
            pass
        sleep(0.5)

    window.erase()
    window.box()
    window.refresh()
    running = False
예제 #5
0
def wrap(main):
    try:
        main()
    except:
        exctype, value = sys.exc_info()[:2]
        if exctype == SystemExit:
            sys.exit(value)
        s = StringIO.StringIO()
        traceback.print_exc(file=s, limit=20)

        log.alert("fatal python exception")
        log.alert(s.getvalue())
        log.alert("during: %s" % status.get())

        sendmail(s.getvalue())

        sys.exit(1)
예제 #6
0
def wrap(main):
    try:
        main()
    except:
        exctype, value = sys.exc_info()[:2]
        if exctype == SystemExit:
            sys.exit(value)
        s = StringIO.StringIO()
        traceback.print_exc(file = s, limit = 20)

        log.alert("fatal python exception")
        log.alert(s.getvalue())
        log.alert("during: %s" % status.get())

        sendmail(s.getvalue())

        sys.exit(1)
예제 #7
0
    def show_status(self, instance):

        hosts = status.get()
        texto = ''
        for host in hosts:

            nome = host['hostname']
            estado = host['state']
            ram = str(host['ram'])
            vms = str(host['vms'])

            msg = nome +    '\nEstado: ' + estado + \
                            '\nRam: ' + ram + \
                            '\nVMs: ' + vms + '\n\n'

            texto = texto + msg

        self.ids.status.text = texto
예제 #8
0
#coding: utf-8

import status

hosts = status.get()
texto = ''
for host in hosts:

    nome = host['hostname']
    estado = host['state']
    ram = str(host['ram'])
    vms = str(host['vms'])

    msg =   '\n' + nome + \
            '\nEstado: ' + estado + \
            '\nRam: ' + ram + \
            '\nVMs: ' + vms + '\n'

    texto = texto + msg

print texto
예제 #9
0
 def sendmail(trace):
     m = mailer.Message()
     m.set_headers(to = status.admin, cc = "%s, %s" % (status.email, status.builder_list), subject = "fatal python exception")
     m.write("%s\n" % trace)
     m.write("during: %s\n" % status.get())
     m.send()
예제 #10
0
 def go(self):
   s = status.get(self.id)
   if s is not None and s['status'] != self.last_status:
     message = self.status_messages[s['status']]
     os.system('purple-remote "setstatus?status=%s&message=%s"' % (s['status'], message))
예제 #11
0
def run(lim_max, lim_med):
	
	hosts = status.get()
	ram = []
	running = []
	idle = []
	offline = []

	try:
		file = open("registered.txt", "r+")
		registered = file.read()	
		registered = ast.literal_eval(registered)
	except:
		print 'É preciso registrar os hosts do ambiente'
		registered = []

	for host in hosts:	# Inserts the hosts that are connected (and have VMs) in an list of actives
		if host['state'] == 'up':
			if host['vms'] > 0:
				running.append(host['hostname'])
				ram.append(host['ram']) # Captures memory consumption and inserts into a list

	for host in hosts: # Inserts hosts that are running (and do not have VMs) in a list of idlers
		if host['state'] == 'up':
			if host['vms'] == 0:
				idle.append(host['hostname'])

	for host in hosts: # Inserts hosts that are shut down (and registered) in an list of offline 
		if host['state'] == 'down':
			if host['hostname'] in registered:
				offline.append(host['hostname'])

	try:
		ram_avg = sum(ram) / len(ram) # Calculates an average of memory in use by active hosts
	except:
		ram_avg = 0
	
	print 'ativos: ' + str(running)
	print 'ociosos: ' + str(idle)
	print 'offline: ' + str(offline)
	print 'média de ram: %s' %ram_avg

## Logic of the management of the hosts to be turned on and off
	
	if ram_avg > lim_max:						## If RAM is above the maximum limit
		if len(idle) > 0:
			if len(idle) > 1:					## They keep 1 idle on and shut off others
				for i in range(len(idle)-1):	# Turn off all except 1
					print 'desligando %s' %idle[i+1]
					muda_estado.shutdown(idle[i+1])
		else:
			if len(offline) > 0:				# If there are offline hosts ...
				print 'ligando %s' %offline[0]
				muda_estado.wake(offline[0]) 			# Wake up the first offline host from the list
			else:
				print 'Não há mais hosts offline para ligar.\nO sistema está no limite!!!'
	else:
		if len(idle) > 0:
			if ram_avg >= lim_med:				## If RAM is between the medium and maximum limits
				for i in range(len(idle)-1):	# Turn off all except 1
					print 'desligando %s' %idle[i+1]
					muda_estado.shutdown(idle[i+1])
			else:
				if len(running) >= 1:		## If there is at least 1 active host
					for host in idle:				
						print 'desligando %s' %host
						muda_estado.shutdown(host)		# shut down all idle hosts
				else:								# Else...
					for i in range(len(idle)-1):	# Turn off all except 1
						print 'desligando %s' %idle[i+1]
						muda_estado.shutdown(idle[i+1])
예제 #12
0
파일: view_list.py 프로젝트: rudevdr/fsman
def init(stdscr, window_posy, window_posx, paths, inc_text):

    init_pair(1, COLOR_BLACK, COLOR_CYAN)
    init_pair(2, COLOR_BLACK, COLOR_BLUE)
    init_pair(3, COLOR_CYAN, COLOR_BLUE)
    attribute_underline = color_pair(2) + A_REVERSE + A_UNDERLINE
    attribute_nounderline = color_pair(2) + A_REVERSE

    height, width = stdscr.getmaxyx()

    lst_data = []
    lendinc = len(inc_text)

    lst_height = (11 * height) // 15
    lst_width = (2 * width) // 5
    lst_window = newwin(lst_height, lst_width, window_posy, window_posx)
    last_panel = new_panel(lst_window)
    lst_window.box()

    for index, path in enumerate(paths):
        lst_y = index + 1
        lst_x = lendinc + 1

        lst_window.addstr(lst_y, lst_x, '/'.join(path.split('/')[-2:]),
                          attribute_nounderline)
        lst_data.append((path, window_posy + lst_y, window_posx + lst_x))

    keeper.add_didc(Indicator(lst_data, inc_text, 0, attribute_nounderline))

    viewo = view_output.init(lst_height, width - lst_width, window_posy,
                             lst_width, keeper)

    stdscr.refresh()
    lst_window.refresh()
    viewo.refresh()

    attributes = (attribute_underline, attribute_nounderline)
    executor.init(lst_data, attributes, stdscr, lst_window, viewo)

    handler.update(startup=True)

    while True:
        key = stdscr.getch()
        if key == ord('q'):
            break
        elif key == KEY_RESIZE:
            height, width = stdscr.getmaxyx()
            h = (11 * height) // 15
            w = (2 * width) // 5

            lst_window.resize(h, w)
            viewo.resize(h, width - w)
            #viewo.move(window_posy, lst_width)
            #lst_window.move(window_posy, window_posx)
            sys.stdout.write(str(height) + "/" + str(width) + " ")

            stdscr.refresh()
            lst_window.refresh()
            viewo.refresh()

        elif key == ord('j'):
            keeper.move_didc_down()
        elif key == ord('k'):
            keeper.move_didc_up()
        elif key == ord('g'):
            keeper.move_didc_top()
        elif key == ord('G'):
            keeper.move_didc_bottom()
        elif key == ord('u'):
            keeper.clear_idcs()
        elif key == ord('v'):
            for index in range(0, len(lst_data)):
                keeper.enable(
                    Indicator(lst_data, inc_text, index,
                              color_pair(1) | A_REVERSE))
            keeper.didc_blink()
        elif key == ord('r'):
            lst_paths = [path[0] for path in lst_data]
            paths = status.get_all("paths")
            for path in paths:
                try:
                    index = lst_paths.index(path)
                    keeper.enable(
                        Indicator(lst_data, inc_text, index,
                                  color_pair(1) | A_REVERSE))
                except ValueError:
                    pass
        elif key == ord('R'):
            lst_paths = [path[0] for path in lst_data]
            paths = status.get_all("paths")
            not_running_paths = [
                path for path in lst_paths if path not in paths
            ]
            for path in not_running_paths:
                try:
                    index = lst_paths.index(path)
                    keeper.enable(
                        Indicator(lst_data, inc_text, index,
                                  color_pair(1) | A_REVERSE))
                except ValueError:
                    pass
        elif key == ord('S'):
            executor.execute_enqueue(keeper.get_all_obj())
        elif key == ord('K'):
            executor.kill_enqueue(keeper.get_all_obj())
        elif key == ord('V'):
            stdout_path_ = status.get(keeper.get_didc_obj(), 'stdout')
            if stdout_path_:
                break

        elif key == ord('t'):
            keeper.toggle_at_didc(
                Indicator(lst_data, inc_text, keeper.get_didc_index(),
                          color_pair(1) | A_REVERSE))

        view_output.update_view(viewo, keeper.get_didc_obj())
        update()
        viewo.refresh()
예제 #13
0
def status_json():
    return json.dumps(status.get())
예제 #14
0
 def go(self):
   s = status.get(self.id)
   self.count = self.count + 1 if s['status'] == 'away' else 0
   lock(self.count > 2)
예제 #15
0
def run(lim_max, lim_med):

    hosts = status.get()
    ram = []
    running = []
    idle = []
    offline = []

    try:
        file = open("registered.txt", "r+")
        registered = file.read()
        registered = ast.literal_eval(registered)
    except:
        print 'É preciso registrar os hosts do ambiente'
        registered = []

    for host in hosts:  # Insere os hosts que estão ligados (e possuem VMs) em uma lista de ativos
        if host['state'] == 'up':
            if host['vms'] > 0:
                running.append(host['hostname'])
                ram.append(
                    host['ram']
                )  # Captura os consumos de memória e insere em uma lista

    for host in hosts:  # Insere os hosts que estão ligados, mas não possuem VMs, em uma lista de ociosos
        if host['state'] == 'up':
            if host['vms'] == 0:
                idle.append(host['hostname'])

    for host in hosts:  # Insere os hosts que estão desligados (e estão registrados) em uma lista de offline
        if host['state'] == 'down':
            if host['hostname'] in registered:
                offline.append(host['hostname'])

    try:
        ram_avg = sum(ram) / len(
            ram)  # Calcula a média de memória em uso dos hosts ativos
    except:
        ram_avg = 0

    print 'ativos: ' + str(running)
    print 'ociosos: ' + str(idle)
    print 'offline: ' + str(offline)
    print 'média de ram: %s' % ram_avg

    ## Lógica do gerenciamento dos hosts a serem ligados e desligados

    if ram_avg > lim_max:  ## Se RAM estiver acima do limite máximo
        if len(idle) > 0:
            if len(idle) > 1:  ## Mantêm 1 ocioso ligado, mas desliga os demais
                for i in range(len(idle) - 1):  # Desliga todos menos 1
                    print 'desligando %s' % idle[i + 1]
                    muda_estado.shutdown(idle[i + 1])
        else:
            if len(offline) > 0:  # Se existir hosts offline ...
                print 'ligando %s' % offline[0]
                muda_estado.wake(
                    offline[0])  # Acorda o primeiro host offline da lista
            else:
                print 'Não há mais hosts offline para ligar.\nO sistema está no limite!!!'
    else:
        if len(idle) > 0:
            if ram_avg >= lim_med:  ## Se RAM estiver entre os limites médio e máximo
                for i in range(len(idle) - 1):  # Desliga todos menos 1
                    print 'desligando %s' % idle[i + 1]
                    muda_estado.shutdown(idle[i + 1])
            else:
                if len(running) >= 1:  ## Se houver pelo menos 1 host ativo
                    for host in idle:
                        print 'desligando %s' % host
                        muda_estado.shutdown(
                            host)  # Desliga todos os hosts ociosos
                else:  # Senão...
                    for i in range(len(idle) - 1):  # Desliga todos menos 1
                        print 'desligando %s' % idle[i + 1]
                        muda_estado.shutdown(idle[i + 1])