Ejemplo n.º 1
0
def cleanup():
    try:
        curses.isendwin() # raise if initscr() failed
    except curses.error as e:
        log.debug(e)
        log.debug("Failed before curses.initscr()")
        return -1
    curses.echo()
    curses.nocbreak()
    curses.endwin()
Ejemplo n.º 2
0
def create_request(cn, email):
    if not curses.isendwin():
        prepare2run_shellcommand()
    print('STEP 1 (create request) STEP 2 (sign request) STEP3 (generate p12)\n\n%s\n\n\n'
          'STEP 1.>>>>>Trying to generate request for %s<<<<<<\n\n' % ('-' * 70, cn))
    try:
        openssl_subj = open(sys.argv[0][:sys.argv[0].rfind('/')] + '/subj.info').readline()
    except IOError as err:
        print(' '.join('%s/subj.info' % [sys.argv[0][:sys.argv[0].rfind('/')],
                                         os.strerror(err.errno),
                                         '\n(create request) >>>>>FAILED<<<<<<']))
        input('Press ENTER to continue')
        return 1
    openssl_subj = openssl_subj.replace(' ', '~')
    openssl_subj = '/'.join([openssl_subj,
                             'CN=%s' % cn,
                             'emailAddress=%s' % email if email else ''])
    exit_status = shell_command('/usr/bin/openssl req -new '
                                '-config %s/openssl.cnf '
                                '-subj %s '
                                '-keyout %s/Certs/%s_key.pem '
                                '-out %s/Certs/%s_req.pem' %
                                (os.environ['PKI_ROOT'],
                                 openssl_subj,
                                 os.environ['PKI_ROOT'],
                                 cn,
                                 os.environ['PKI_ROOT'],
                                 cn))
    if exit_status:
        input('Press ENTER to continue')
    print('\n\n\n')
    return exit_status
Ejemplo n.º 3
0
def sign_cert(cn, email, days):
    if not curses.isendwin():
        prepare2run_shellcommand()
    print('STEP 1 (create request) STEP 2 (sign request) STEP3 (generate p12)\n\n%s\n\n\n'
          'STEP 2. >>>>>Trying to sign request %s<<<<<<\n\n' % ('-' * 70, cn))
    exit_status = shell_command('/usr/bin/openssl ca '
                                '-config %s/openssl.cnf '
                                '-days %s '
                                '-in %s/Certs/%s_req.pem '
                                '-out %s/Certs/%s_cert.pem' %
                                (os.environ['PKI_ROOT'],
                                 days,
                                 os.environ['PKI_ROOT'],
                                 cn,
                                 os.environ['PKI_ROOT'],
                                 cn))
    new_cert_hook = sys.argv[0][:sys.argv[0].rfind('/')]
    if (not exit_status and
            os.path.exists(new_cert_hook + '/hooks/new.hook') and
            os.path.getsize(new_cert_hook + '/hooks/new.hook') > 0):
        hook_stat = shell_command('%s/hooks/new.hook %s %s %s' % (new_cert_hook, cn, email, days))
        if hook_stat:
            print('CRL hook execution >>>>>FAILED<<<<<<')
            input('Press ENTER to continue')
    elif exit_status:
        print('(sign request) >>>>>FAILED<<<<<<')
        input('Press ENTER to continue')
    print('\n\n\n')
    return exit_status
Ejemplo n.º 4
0
 def run_console(container):
     if not curses.isendwin():
         curses.endwin()
     tty_amount = container.get_config_item('lxc.tty')
     for tty_x in range(1, int(tty_amount) + 1):
         if container.console(ttynum=tty_x):
             break
Ejemplo n.º 5
0
 def create_container(name, cached_template):
     if not curses.isendwin():
         curses.endwin()
     cd = lxc.Container(name)
     cached_template = cached_template.split('/')
     lxc_template_data = {}
     if cached_template[0] != 'Default':
         lxc_template_data = {'dist': cached_template[0], 'release': cached_template[1], 'arch': cached_template[2]}
     cd.create('download', 0, lxc_template_data)
     input('Press ENTER to continue')
Ejemplo n.º 6
0
 def display(self,item):
     """Prints out a gameplay item, either on the curses screen, or stdout if end_game is True."""
     colour = item.colour
     text = item.disp
 
     if curses.isendwin():
       if colour:
           print(colored(text, ("","red","yellow","cyan","magenta")[colour]), end="")
       else:
           print(text,end="")
     else:
       if colour:  screen.addstr(text, curses.color_pair(colour))
       else: screen.addstr(text)
Ejemplo n.º 7
0
    def run(self):
        '''
        run: The main loop of the application. Waits for user inputs, and acts accordingly.

        :return: None
        '''
        thread.start_new_thread(self.poll_for_messages, tuple())
        self.addCmdLine("Welcome to Chat!")
        self.addCmdLine("Login to start chatting, or type help to get a list of valid commands.")
        while True:
            try:
                assert not curses.isendwin()
                if self.mode == -1:
                    self.display.setLines(self.cmd_history)
                else:
                    if self.mode not in self.current_user.formatted_messages:
                        self.current_user.formatted_messages[self.mode] = []
                    self.display.setLines(self.current_user.formatted_messages[self.mode])
                self.displayScreen()
                # get user command
                c = self.screen.getch()
                if c == curses.KEY_UP: 
                    self.display.updown(self.UP)
                elif c == curses.KEY_DOWN:
                    self.display.updown(self.DOWN)
                elif c == self.ESC_KEY:
                    self.mode = -1
                    self.display.setLines(self.cmd_history, adjust=True)
                elif curses.keyname(c) == '^U':
                    self.display.pageup()
                elif curses.keyname(c) == '^D':
                    self.display.pagedown()
                elif c == ord('\n'):
                    # Interpret command
                    if self.mode == -1:
                        self.execute_cmd(self.input_w.line)
                    else:
                        self.P.send_message(from_name=self.current_user.username,
                                            dest_id=self.mode,
                                            msg=self.input_w.line)
                    self.input_w.clearLine()
                else:
                    self.input_w.putchar(c)
            except KeyboardInterrupt as e:
                self.exited = True
                raise e
            except Exception as e:
                pass
def main(screen):
  global settings
  screen.clear()
  curses.start_color()
  curses.use_default_colors()
  screen.scrollok(False)

  maxcompact = 3
  mincompact = 1

  ## Some sane defaults
  settings = {
    'compact'       : 1,
    'helptoggle'    : False,
  }

  for i in range(0, curses.COLORS):
    curses.init_pair(i + 1, i, -1)
  
  screen.timeout(5000)
  curses.curs_set(0) # Invisible cursor
  while not curses.isendwin():
    if settings['helptoggle']:
      display_help(screen)
    else:
      display(screen)


    char = screen.getch()
    
    if char == ord('q'): # quit
      return
    elif char == ord('z'): # increase compact
      settings['compact'] = min(settings['compact']+1, maxcompact)
      continue
    elif char == ord('Z'): # decrease compact
      settings['compact'] = max(settings['compact']-1, mincompact)
      continue
    elif char == ord('c'): # clear screen
      screen.clear()
      continue
    elif (char == ord('?')) or (char == ord('h')): #helpmenu
      settings['helptoggle'] ^= True
      continue
    else:
      continue
Ejemplo n.º 9
0
def generate_crl():
    if not curses.isendwin():
        prepare2run_shellcommand()
    print('STEP 1 (revoke cert) STEP 2 (generate CRL)\n\n%s\n\n\n'
          'STEP 2.>>>>>Trying to generate CRL<<<<<<\n\n' % ('-' * 70))
    exit_status = shell_command('/usr/bin/openssl ca -gencrl '
                                '-out %s/crl.pem '
                                '-config %s/openssl.cnf' % (os.environ['PKI_ROOT'],
                                                            os.environ['PKI_ROOT']))
    crl_hook = sys.argv[0][:sys.argv[0].rfind('/')]
    if (not exit_status and
            os.path.exists(crl_hook + '/hooks/crl.hook') and
            os.path.getsize(crl_hook + '/hooks/crl.hook') > 0):
        hook_stat = shell_command(crl_hook + '/hooks/crl.hook')
        if hook_stat:
            print('CRL hook execution >>>>>FAILED<<<<<<')
            input('Press ENTER to continue')
    elif exit_status:
        print('STEP 2 (generate CRL) >>>>>FAILED<<<<<<')
        input('Press ENTER to continue')
    print('\n\n')
    return exit_status
Ejemplo n.º 10
0
def generate_p12(cn):
    if not curses.isendwin():
        prepare2run_shellcommand()
    print('STEP 1 (create request) STEP 2 (sign request) STEP3 (generate p12)\n\n%s\n\n\n'
          'STEP 3. >>>>>Trying to generate p12 key<<<<<<\n\n' % ('-' * 70))
    exit_status = shell_command('/usr/bin/openssl pkcs12 -export -clcerts '
                                '-in %s/Certs/%s_cert.pem '
                                '-inkey %s/Certs/%s_key.pem -out %s/Certs/%s.p12' %
                                (os.environ['PKI_ROOT'],
                                 cn,
                                 os.environ['PKI_ROOT'],
                                 cn,
                                 os.environ['PKI_ROOT'],
                                 cn))
    if exit_status:
        print('(generate p12) >>>>>FAILED<<<<<<')
    try:
        if os.path.getsize('%s/Certs/%s.p12' % (os.environ['PKI_ROOT'], cn)) == 0:
            print('%s/Certs/%s.p12 is empty. Removing it ' % (os.environ['PKI_ROOT'], cn))
            os.remove('%s/Certs/%s.p12' % (os.environ['PKI_ROOT'], cn))
    except OSError as err:
        print(os.strerror(err.errno))
    finally:
        return exit_status
Ejemplo n.º 11
0
def revoke_cert(cert_detail):
    if not curses.isendwin():
        prepare2run_shellcommand()
    print('STEP 1 (revoke cert) STEP 2 (generate CRL)\n\n%s\n\n\n'
          'STEP 1.>>>>>Trying to revoke %s<<<<<<\n\n' % ('-' * 70, cert_detail['cert_file_name']))
    exit_status = shell_command('/usr/bin/openssl ca -revoke %s/signed_certs/%s.pem -config %s/openssl.cnf' %
                                (os.environ['PKI_ROOT'], cert_detail['cert_file_name'], os.environ['PKI_ROOT']))
    revoke_hook = sys.argv[0][:sys.argv[0].rfind('/')]
    if (not exit_status and
            os.path.exists(revoke_hook + '/hooks/revoke.hook') and
            os.path.getsize(revoke_hook + '/hooks/revoke.hook') > 0):
        hook_stat = shell_command('%s/hooks/revoke.hook %s %s %s' %
                                  (revoke_hook,
                                   cert_detail['cert_file_name'],
                                   cert_detail['CN'],
                                   cert_detail['emailAddress']))
        if hook_stat:
            print('CRL hook execution >>>>>FAILED<<<<<<')
            input('Press ENTER to continue')
    elif exit_status:
        print('(revoke cert)>>>>>FAILED<<<<<<')
        input('Press ENTER to continue')
    print('\n\n')
    return exit_status
Ejemplo n.º 12
0
 def draw(self):
     level = self.level
     global game
     
     screen.clear()
     nl = True
     ln = 0
     def output(str=""):
         nonlocal nl, ln
         if nl: screen.addstr(ln,0,str)
         else: screen.addstr(str)
         nl = False
     def outputln(str=""):
         nonlocal nl, ln
         if nl: screen.addstr(ln,0,str)
         else: screen.addstr(str)
         nl = True
         ln += 1
         
     width = level.display[1] or self.width
     outputln("+" + "---"*width + "-+  Level %i" % (level.number+1))
     for r, n in self:
         output("| ")
         for y,item in self.cells(r): self.display(item)
         if n is 0: outputln("|  $%4i" % level.coinscore)
         elif n is 1: outputln("|  Σ$%3i" % level.bank)
         elif level.lives > 1 and n is 2:
             outputln("|  ♡ %3i" % level.lives)
         else: outputln("|")
     outputln("+" + "---"*width + "-+")
     outputln()
     outputln(self.last_message)
     output()
     
     if not curses.isendwin():
         screen.refresh()
Ejemplo n.º 13
0
 def attach_console(cmd):
     if not curses.isendwin():
         curses.endwin()
     lxc_storage[lxc_win.value].attach_wait(lxc.attach_run_command, cmd)
Ejemplo n.º 14
0
def keyboard_shortcuts(scr_id):
    def destroy_conteiner(cd):
        if cd.running:
            cd.stop()
            cd.wait("STOPPED", 3)
        cd.destroy()

    def create_container(name, cached_template):
        if not curses.isendwin():
            curses.endwin()
        cd = lxc.Container(name)
        cached_template = cached_template.split('/')
        lxc_template_data = {}
        if cached_template[0] != 'Default':
            lxc_template_data = {'dist': cached_template[0], 'release': cached_template[1], 'arch': cached_template[2]}
        cd.create('download', 0, lxc_template_data)
        input('Press ENTER to continue')

    def run_console(container):
        if not curses.isendwin():
            curses.endwin()
        tty_amount = container.get_config_item('lxc.tty')
        for tty_x in range(1, int(tty_amount) + 1):
            if container.console(ttynum=tty_x):
                break

    def write_config(lxc_conf_key, value):
        lxc_storage[lxc_win.value].clear_config_item(lxc_conf_key)
        res = lxc_storage[lxc_win.value].set_config_item(lxc_conf_key, value)
        if res != 'B':
            lxc_storage[lxc_win.value].save_config()

    def edit_dialog():
        read_mem_limit = ''.join(lxc_storage[lxc_win.value].get_config_item('lxc.cgroup.memory.limit_in_bytes'))
        cpu_bindig = ''.join(lxc_storage[lxc_win.value].get_config_item('lxc.cgroup.cpuset.cpus'))
        cpu_shares = ''.join(lxc_storage[lxc_win.value].get_config_item('lxc.cgroup.cpu.shares'))

        m_limit = EditBar(5, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                                 curses.color_pair(3), "Memory limit (M for MBytes,G for GBytes)", read_mem_limit, False)
        cpu = EditBar(8, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                                 curses.color_pair(3), 'CPU binding. Total %s cores' % os.sysconf('SC_NPROCESSORS_ONLN'), cpu_bindig, True)
        cpu_pr = EditBar(11, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                                 curses.color_pair(3), 'CPU priority', cpu_shares, True)
        tty = EditBar(14, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                                 curses.color_pair(3), 'tty amount', lxc_storage[lxc_win.value].get_config_item('lxc.tty'), True)
        astart = EditBar(17, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                                 curses.color_pair(3), 'Autostart', lxc_storage[lxc_win.value].get_config_item('lxc.start.auto'), True)
        sdeley = EditBar(20, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                                 curses.color_pair(3), 'Start delay', lxc_storage[lxc_win.value].get_config_item('lxc.start.delay'), True)
        sorder = EditBar(23, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                                 curses.color_pair(3), 'Start order', lxc_storage[lxc_win.value].get_config_item('lxc.start.order'), True)

        lxc_OK = Button(26, int(size_x / 2) - 50, 25, 3, curses.color_pair(3), curses.color_pair(3), 'OK', 1)
        lxc_Cancel= Button(26, int((size_x / 2) - 50 + 25), 25, 3, curses.color_pair(3),
                           curses.color_pair(3), 'Cancel', 0)
        start_dialog = Dialog(m_limit, cpu, cpu_pr, tty, astart, sdeley, sorder, lxc_OK, lxc_Cancel)
        start_dialog.keyboard()
        if lxc_OK.checked:
            return (''.join(m_limit.value),
                    ''.join(cpu.value),
                    ''.join(cpu_pr.value),
                    ''.join(tty.value),
                    ''.join(astart.value),
                    ''.join(sdeley.value),
                    ''.join(sorder.value))
        else:
            return None

    def ask_string(title):
        clone_name = EditBar(5, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                                 curses.color_pair(3), title, '', False)
        lxc_OK = Button(8, int(size_x / 2) - 50, 25, 3, curses.color_pair(3), curses.color_pair(3), 'OK', 1)
        lxc_Cancel= Button(8, int((size_x / 2) - 50  + 25), 25, 3, curses.color_pair(3),
                           curses.color_pair(3), 'Cancel', 0)
        start_dialog = Dialog(clone_name, lxc_OK, lxc_Cancel)
        start_dialog.keyboard()
        if lxc_OK.checked:
            return ''.join(clone_name.value)
        else:
            return None

    def init_menu_panel():
        m_any_w = curses.newwin(1, 75, size_y - 1, 0)
        m_any_p = curses.panel.new_panel(m_any_w)
        m_run_w = curses.newwin(1, 75, size_y - 1, 75)
        m_run_p = curses.panel.new_panel(m_run_w)
        m_stop_w = curses.newwin(1, 75, size_y - 1, 75)
        m_stop_p = curses.panel.new_panel(m_stop_w)
        return {'any': (m_any_w, m_any_p), 'run': (m_run_w, m_run_p), 'stop': (m_stop_w, m_stop_p)}

    def menu(menu_win, menu_type):
        offset = 0
        for item in menu_type:
            k, descr = item.split(':')
            try:
                menu_win.addstr(0, offset, k, curses.color_pair(2) | curses.A_BOLD)
                menu_win.addstr(0, offset + 2 + len(k), '%s' % descr, curses.color_pair(3))
                offset = offset + len(item) + 2
            except:
                pass

    def scan_cache_folders():
        buf = []
        if os.path.isdir('%s/.cache/lxc' % os.environ['HOME']):
            cache_path = '%s/.cache/lxc/download' % os.environ['HOME']
        else:
            cache_path = '/var/cache/lxc/dowload'
        try:
            for top in os.listdir(cache_path):
                buf.extend(['/'.join(d[0].split('/')[-3:])
                            for d in os.walk('%s/%s' % (cache_path, top))
                            if 'default' in d[1]])
        except FileNotFoundError:
            pass
        return buf

    def interface_dialog():
        def lxc_add_if():
            lxc_interface = lxc.ContainerNetworkList(lxc_storage[lxc_win.value])
            lxc_interface.add('veth')
            lxc_storage[lxc_win.value].save_config()
            if_index.rlist = [str(net.index) for net in lxc_storage[lxc_win.value].network]
            if_index.update()

        def lxc_del_if():
            lxc_interface = lxc.ContainerNetworkList(lxc_storage[lxc_win.value])
            lxc_interface.remove(if_index.cursor_pos - 1)
            lxc_storage[lxc_win.value].save_config()
            if_index.cursor_pos = if_index.value = 0
            if_index.rlist = [str(net.index) for net in lxc_storage[lxc_win.value].network]
            if_index.update()

        def get_all_interfaces():
            with open('/proc/net/dev') as ifc:
                if_names = ifc.readlines()
            if_list = [ifn.split(':')[0].lstrip() for ifn in if_names[2:] if not 'veth' in ifn.split(':')[0]]
            if_list.remove('lo')
            return if_list

        def find_host_if(this, arg):
            val = lxc_storage[lxc_win.value].get_config_item('lxc.network.%s.link' % arg)
            this.value = this.rlist.index(val) if val in this.rlist else 0
            this.update()

        def find_if_type(this, arg):
            val = lxc_storage[lxc_win.value].get_config_item('lxc.network.%s.type' % arg)
            this.value = this.rlist.index(val) if val in this.rlist else 0
            this.update()

        def find_if_stat(this, arg):
            val = lxc_storage[lxc_win.value].get_config_item('lxc.network.%s.flags' % arg) or 'down'
            this.value = this.rlist.index(val) if val in this.rlist else 0
            this.update()

        def find_if_name(this, arg):
            val = lxc_storage[lxc_win.value].get_config_item('lxc.network.%s.name' % arg)
            this.value = list(str(val))
            this.update()

        def find_if_mac(this, arg):
            val = lxc_storage[lxc_win.value].get_config_item('lxc.network.%s.hwaddr' % arg)
            this.value = list(str(val))
            this.update()

        def find_if_ip(this, arg):
            this.value = list(lxc_storage[lxc_win.value].get_config_item('lxc.network.%s.ipv4' % arg))
            this.update()

        def find_if_ipv6(this, arg):
            this.value = list(lxc_storage[lxc_win.value].get_config_item('lxc.network.%s.ipv6' % arg))
            this.update()

        lxc_if_index = [str(net.index) for net in lxc_storage[lxc_win.value].network]
        all_if = get_all_interfaces()
        if_i = (all_if.index(lxc_storage[lxc_win.value].get_config_item('lxc.network.0.link')) + 1
                if lxc_storage[lxc_win.value].get_config_item('lxc.network.0.link') in all_if else 1)
        type_index = lxc_storage[lxc_win.value].get_config_item('lxc.network.0.type')
        flags_index = lxc_storage[lxc_win.value].get_config_item('lxc.network.0.flags') or 'down'
        if_types_list = ['veth', 'vlan', 'macvlan', 'phys']
        if_flags_list = ['down', 'up']

        if_index = RadioList(5, int(size_x / 2) - 50, 25, 10, curses.color_pair(3),
                                 curses.color_pair(3), lxc_if_index, ' LXC Interface ')
        host_if = RadioList(5, int(size_x / 2) - 25, 25, 10, curses.color_pair(3),
                                 curses.color_pair(3), all_if, ' Host Interfaces ', if_i)
        find_host_if(host_if, 0)
        if_type = RadioList(15, int(size_x / 2) - 50, 25, 10, curses.color_pair(3),
                                 curses.color_pair(3), if_types_list, ' Network type ', if_types_list.index(type_index) + 1)
        find_if_type(if_type, 0)
        if_stat = RadioList(15, int(size_x / 2) - 25, 25, 10, curses.color_pair(3),
                                 curses.color_pair(3), if_flags_list, ' Status ', if_flags_list.index(flags_index) + 1)
        find_if_stat(if_stat, 0)
        lxc_name = EditBar(25, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                           curses.color_pair(3), ' Name ',
                           lxc_storage[lxc_win.value].get_config_item('lxc.network.0.name'), False)
        lxc_mac = EditBar(28, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                           curses.color_pair(3), ' MAC ',
                           lxc_storage[lxc_win.value].get_config_item('lxc.network.0.hwaddr'), False)
        lxc_ip = EditBar(31, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                           curses.color_pair(3), ' IPv4 ',
                           ''.join(lxc_storage[lxc_win.value].get_config_item('lxc.network.0.ipv4')), False)
        lxc_ipv6 = EditBar(34, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                           curses.color_pair(3), ' IPv6 ',
                           ''.join(lxc_storage[lxc_win.value].get_config_item('lxc.network.0.ipv6')), False)

        lxc_OK = Button(37, int(size_x / 2) - 50, 25, 3, curses.color_pair(3), curses.color_pair(3), 'OK', 1)
        lxc_Cancel= Button(37, int((size_x / 2) - 50  + 25), 25, 3, curses.color_pair(3),
                           curses.color_pair(3), 'Cancel', 0)
        sb = StatusBar(40, int(size_x / 2) - 50, 50, 3,
                       curses.color_pair(3),
                       curses.color_pair(3),
                       '[ DEL/X ]: delete if [ INS/Z ]: add if')

        if_index.master = True
        host_if.local_func = find_host_if
        if_type.local_func = find_if_type
        if_stat.local_func = find_if_stat
        lxc_name.local_func = find_if_name
        lxc_mac.local_func = find_if_mac
        lxc_ip.local_func = find_if_ip
        lxc_ipv6.local_func = find_if_ipv6
        start_dialog = Dialog(if_index, host_if, if_type, if_stat, lxc_name, lxc_mac, lxc_ip, lxc_ipv6, lxc_OK, lxc_Cancel)
        start_dialog.key_map = {330: lxc_del_if, 122: lxc_add_if, 331: lxc_add_if, 120: lxc_del_if}
        start_dialog.keyboard()
        if lxc_OK.checked:
            return [if_index.rlist[if_index.value],
                    if_type.rlist[if_type.value],
                    host_if.rlist[host_if.value],
                    if_stat.rlist[if_stat.value],
                    ''.join(lxc_name.value),
                    ''.join(lxc_mac.value),
                    ''.join(lxc_ip.value),
                    ''.join(lxc_ipv6.value)]
        else:
            return None

    def new_lxc_dialog():
        cache_list = scan_cache_folders()

        cache_list.insert(0, 'Default')
        lxc_name = EditBar(5, int(size_x / 2) - 50, 50, 3, curses.color_pair(3),
                           curses.color_pair(3), ' New LXC ', '', False)
        lxc_template = RadioList(8, int(size_x / 2) - 50, 50, 18, curses.color_pair(3),
                                 curses.color_pair(3), cache_list, ' Cache ')
        lxc_OK = Button(26, int(size_x / 2) - 50, 25, 3, curses.color_pair(3), curses.color_pair(3), 'OK', 1)
        lxc_Cancel= Button(26, int((size_x / 2) - 50  + 25), 25, 3, curses.color_pair(3),
                           curses.color_pair(3), 'Cancel', 0)
        start_dialog = Dialog(lxc_name, lxc_template, lxc_OK, lxc_Cancel)
        start_dialog.keyboard()
        return (''.join(lxc_name.value), lxc_template.rlist[lxc_template.value]) if lxc_OK.checked else None

    def snapshot_dialog():
        def snap_rm():
            snap_name = lxc_snap.rlist[lxc_snap.cursor_pos - 1].split(' ')[0]
            lxc_storage[lxc_win.value].snapshot_destroy(snap_name)
            lxc_snap.cursor_pos = lxc_snap.value = 0
            lxc_snap.rlist = [" ".join([snap[0], snap[2]]) for snap in lxc_storage[lxc_win.value].snapshot_list()]
            lxc_snap.update()

        snap_list = [" ".join([snap[0], snap[2]]) for snap in lxc_storage[lxc_win.value].snapshot_list()]
        lxc_snap = RadioList(5, int(size_x / 2) - 50, 50, 18, curses.color_pair(3),
                                 curses.color_pair(3), snap_list, ' Snapshot list ')
        lxc_OK = Button(23, int(size_x / 2) - 50, 25, 3, curses.color_pair(3), curses.color_pair(3), 'Restore', 1)
        lxc_Cancel= Button(23, int((size_x / 2) - 50  + 25), 25, 3, curses.color_pair(3),
                           curses.color_pair(3), 'Cancel', 0)
        sb = StatusBar(26, int(size_x / 2) - 50, 50, 3,
                       curses.color_pair(3),
                       curses.color_pair(3),
                       'DEL/X: delete snaphot')
        start_dialog = Dialog(lxc_snap, lxc_OK, lxc_Cancel)
        start_dialog.key_map = {330: snap_rm, 120: snap_rm}
        start_dialog.keyboard()
        return lxc_snap.rlist[lxc_snap.cursor_pos - 1].split(' ')[0] if lxc_OK.checked else None

    def show_me_screen():
        nonlocal lxc_win, size_y, size_x, menu_panel, menu_panels, panel
        size_y, size_x = scr_id.getmaxyx()
        lxc_win = MenuList(0, 0, size_x, size_y - 11, curses.color_pair(1), curses.color_pair(1), lxc_list, "LXC list")
        menu_panels = init_menu_panel()
        menu(menu_panels['any'][0], menu_any)
        menu(menu_panels['run'][0], menu_run)
        menu(menu_panels['stop'][0], menu_stop)

    def get_all_lxc_list():
        nonlocal lxc_storage, lxc_list
        lxc_storage = my_list_containers(as_object=True)
        return (lxc_storage, ['[%s] %-8s %-50s %s' % ('R' if fu.init_pid > 0 else 'S',
                                            fu.get_rootfs_size(),
                                            fu.name,
                                            get_release_info(str(fu.config_file_name).replace('config', 'rootfs/etc/')))
                              for fu in lxc_storage])

    def stop_it():
        if lxc_storage[lxc_win.value].running:
            if warning('Stop container???', 'Stop It!'):
                lxc_storage[lxc_win.value].stop()
                lxc_storage[lxc_win.value].fork_size_calc()
                sb = StatusBar(5, int(size_x / 2) - 50, 7, 3, curses.color_pair(3),
                           curses.color_pair(3) | curses.A_BLINK, 'WAIT')
                curses.panel.update_panels()
                lxc_storage[lxc_win.value].wait("STOPPED", 3)
                lxc_list[lxc_win.value] = lxc_list[lxc_win.value].replace('[R]', '[S]')
                del sb
                curses.panel.update_panels()

    def warning(warn_txt, b_title):
        warning = StatusBar(5, int(size_x / 2) - 40, 40, 5,
                       curses.color_pair(3),
                       curses.color_pair(3),
                       warn_txt)
        lxc_OK = Button(10, int(size_x / 2) - 40, 20, 3, curses.color_pair(3), curses.color_pair(3), b_title, 1)
        lxc_cancel = Button(10, int(size_x / 2) - 20, 20, 3, curses.color_pair(3), curses.color_pair(3), 'Cancel', 0)
        start_dialog = Dialog(lxc_OK, lxc_cancel)
        start_dialog.keyboard()
        return 1 if lxc_OK.checked else 0

    def attach_console(cmd):
        if not curses.isendwin():
            curses.endwin()
        lxc_storage[lxc_win.value].attach_wait(lxc.attach_run_command, cmd)

    def container_full_info():
        proc = subprocess.Popen(["lxc-info", "-n", lxc_storage[lxc_win.value].name],stdout=subprocess.PIPE)
        scr_id.move(size_y - 11, 0)
        scr_id.clrtobot()
        for offset, info_line in enumerate(proc.stdout.readlines()):
            if info_line.startswith("Link:".encode()):
                break
            scr_id.addstr(size_y - (11 - offset), 0, info_line, curses.color_pair(2))


    menu_any = ['C:Create', 'D:Destroy', 'E:Properties', 'I:Interfaces', 'Space:Disk usage', 'Q:Exit']
    menu_run = ['S:Stop', 'F:Freeze', 'U:Unfreeze', 'T:Console', 'Ctrl+T: Cmd exec', 'Ctrl+O: ctop']
    menu_stop = ['R:Run', 'L:Clone', 'N:Rename', 'M:Snapshot', 'O:Snapshot menu']
    cursor_pos = 1
    cur_page = 0

    lxc_win, size_y, size_x, menu_panel, menu_panels, panel = None, 0, 0, None, None, None
    lxc_storage, lxc_list = get_all_lxc_list()
    show_me_screen()

    curses.panel.update_panels()
    scr_id.refresh()
    key = 0
    while True:
        if lxc_storage:
            container_full_info()
        if len(lxc_storage) and lxc_storage[lxc_win.value].state == "RUNNING":
            menu_panels['run'][1].show()
            menu_panels['stop'][1].hide()
        if len(lxc_storage) and lxc_storage[lxc_win.value].state == "STOPPED":
            menu_panels['run'][1].hide()
            menu_panels['stop'][1].show()
        curses.panel.update_panels()
        lxc_win.update()
        key = scr_id.getch()
        lxc_win.action(key)

        if key == curses.KEY_RESIZE:
            size_y, size_x = scr_id.getmaxyx()
            menu_panels['any'][1].move(size_y - 1 , 0)
            if size_x > 175:
                menu_panels['run'][1].move(size_y - 1 , 75)
                menu_panels['stop'][1].move(size_y - 1 , 75)
            lxc_win.win_id.resize(size_y - 11, size_x)
        elif key == 113:
            shutdown_curses(scr_id)
            for lc in lxc_storage:
                if lc.p and lc.p.is_alive():
                    lc.p.terminate()
            break
        elif key == 100 and lxc_storage:
            if warning('Destroy container???', 'Destroy It!'):
                destroy_conteiner(lxc_storage[lxc_win.value])
                lxc_storage, lxc_list = get_all_lxc_list()
                lxc_win.rlist.clear()
                lxc_win.win_id.clear()
                lxc_win.focus()
                if len(lxc_list) > 0:
                    lxc_win.rlist.extend(lxc_list)
                    lxc_win.action(259)

        elif key == 99:
            nlxcdata = new_lxc_dialog()
            if nlxcdata:
                create_container(*nlxcdata)
                lxc_storage, lxc_list = get_all_lxc_list()
                lxc_win.rlist.clear()
                lxc_win.rlist.extend(lxc_list)

        elif key == 15:
            '''Ctrl+O'''
            if lxc_storage[lxc_win.value].state == "RUNNING":
                attach_console(["top"])

        elif key == 20:
            cmd = ask_string(' Run command ')
            if cmd:
                attach_console(cmd.split(' '))
                input('Press ENTER to continue')

        elif key == 111:
            '''o key'''
            sndil = snapshot_dialog()
            if sndil:
                if lxc_storage[lxc_win.value].state == "RUNNING":
                    lxc_win.update()
                    if not warning('Container need to be stopped!', 'Stop It!'):
                        continue
                    lxc_win.update()
                    stop_it()
                lxc_storage[lxc_win.value].snapshot_restore(sndil)

        elif key == 109:
            '''m key'''
            if not curses.isendwin():
                curses.endwin()
            lxc_storage[lxc_win.value].snapshot()
            input('Press ENTER to continue')

        elif key == 114:
            lxc_storage[lxc_win.value].start()
            lxc_storage[lxc_win.value].fork_size_calc()
            sb = StatusBar(5, int(size_x / 2) - 50, 7, 3, curses.color_pair(3),
                           curses.color_pair(3) | curses.A_BLINK, 'WAIT')
            curses.panel.update_panels()
            lxc_storage[lxc_win.value].wait("RUNNING", 3)
            lxc_list[lxc_win.value] = lxc_list[lxc_win.value].replace('[S]', '[R]')
            del sb

        elif key == 115:
            stop_it()
        elif key == 105:
            if_prop = interface_dialog()
            if if_prop:
                need_reinit_if = (lxc_storage[lxc_win.value].get_config_item('lxc.network.%s.type' % if_prop[0]) !=
                                  if_prop[2])
                network_prop = ['type', 'link', 'flags', 'name', 'hwaddr', 'ipv4', 'ipv6']
                print(lxc_storage[lxc_win.value].get_config_item('lxc.network.%s.type' % if_prop[0]), if_prop[1])
                if need_reinit_if:
                    lxc_storage[lxc_win.value].clear_config_item('lxc.network.%s' % if_prop[0])
                    if_prop[0] = len(lxc_storage[lxc_win.value].network)
                for index, np in enumerate(network_prop, start=1):
                    if not need_reinit_if:
                        get_val_conf = lxc_storage[lxc_win.value].get_config_item('lxc.network.%s.%s' %
                                                                                  (if_prop[0], np))
                        if isinstance(get_val_conf, list):
                            get_val_conf = ''.join(get_val_conf)
                        if get_val_conf == if_prop[index]:
                            continue
                    write_config('lxc.network.%s.%s' % (if_prop[0], np), if_prop[index])

        elif key == 108:
            clone_name = ask_string(" Clone name ")
            if clone_name:
                clone = lxc_storage[lxc_win.value].clone(clone_name)
                lxc_storage, lxc_list = get_all_lxc_list()
                lxc_win.rlist.clear()
                lxc_win.rlist.extend(lxc_list)

        elif key == 101:
            lxc_prop = edit_dialog()
            if lxc_prop:
                write_config('lxc.cgroup.memory.limit_in_bytes', lxc_prop[0])
                write_config('lxc.cgroup.cpuset.cpus', lxc_prop[1])
                write_config('lxc.cgroup.cpu.shares', lxc_prop[2])
                write_config('lxc.tty', lxc_prop[3])
                write_config('lxc.start.auto', lxc_prop[4])
                write_config('lxc.start.delay', lxc_prop[5])
                write_config('lxc.start.order', lxc_prop[6])

        elif key == 110:
            new_name = ask_string(' Rename ')
            if new_name:
                rename = lxc_storage[lxc_win.value].rename(new_name)
                lxc_storage, lxc_list = get_all_lxc_list()
                lxc_win.rlist.clear()
                lxc_win.rlist.extend(lxc_list)

        elif key == 116:
            run_console(lxc_storage[lxc_win.value])
        elif key == 102:
            if lxc_storage[lxc_win.value].running:
                lxc_storage[lxc_win.value].freeze()
                sb = StatusBar(5, int(size_x / 2) - 50, 7, 3, curses.color_pair(3),
                           curses.color_pair(3) | curses.A_BLINK, 'WAIT')
                curses.panel.update_panels()
                lxc_storage[lxc_win.value].wait("FROZEN", 3)
                lxc_list[lxc_win.value] = lxc_list[lxc_win.value].replace('[R]', '[F]')
                del sb

        elif key == 32:
            lxc_storage[lxc_win.value].fork_size_calc(lxc_win.win_id, lxc_win.cursor_pos)
            lxc_list = ['[%s] %-8s %-50s %s' % ('R' if fu.init_pid > 0 else 'S',
                                            fu.get_rootfs_size(),
                                            fu.name,
                                            get_release_info(str(fu.config_file_name).replace('config', 'rootfs/etc/')))
                        for fu in lxc_storage]
            lxc_win.rlist.clear()
            lxc_win.rlist.extend(lxc_list)

        elif key == 117:
            if lxc_storage[lxc_win.value].running:
                lxc_storage[lxc_win.value].unfreeze()
                sb = StatusBar(5, int(size_x / 2) - 50, 7, 3, curses.color_pair(3),
                           curses.color_pair(3) | curses.A_BLINK, 'WAIT')
                curses.panel.update_panels()
                lxc_storage[lxc_win.value].wait("FROZEN", 3)
                lxc_list[lxc_win.value] = lxc_list[lxc_win.value].replace('[F]', '[R]')
                del sb
Ejemplo n.º 15
0
        while True:
            cui.clear()
            cui.putString( 10, 10, "Hello world!" )
            cui.putString( 10, 11, "This window is %dx%d" % (w,h) )
            cui.putString( 10, 13, "longname(): %s" % curses.longname() )
            cui.putString( 10, 14, "COLOR_PAIRS: %d" % curses.COLOR_PAIRS )
            cui.putString( 10, 15, "can_change_color(): %s" % curses.can_change_color() )
            cui.put( x, y, "@", fg = 'red' )
            cui.show()
            rv = None
            try:
                rv = cui.get()
            except ResizedException:
                w, h = cui.dimensions()
            if rv:
                if rv.type == "keypress":
                    if rv.key == 'q': break
                    if controls.has_key( rv.key ):
                        dx, dy = controls[ rv.key ]
                        x += dx
                        y += dy
            x = max( x, 0 )
            x = min( x, w - 1 )
            y = max( y, 0 )
            y = min( y, h - 1 )
        cui.shutdown()
    except:
        if not curses.isendwin():
            curses.endwin()
        raise
Ejemplo n.º 16
0
def handleException():
    if not curses.isendwin():
        curses.endwin()
    raise
Ejemplo n.º 17
0
 def isendwin(self):
     """Has the display been shut down?
     """
     return curses.isendwin()
Ejemplo n.º 18
0
def cleanup():
    assert not curses.isendwin()
    curses.echo()
    curses.nocbreak()
    curses.endwin()
Ejemplo n.º 19
0
 def __del__(self):
     # Deinitialize curses library, and display any errors.
     if not curses.isendwin():
         curses.endwin()
     for e in self._error_log:
         raise e