Example #1
0
def panel(trans_id):
    """
    Return panel template for PSQL tools.
    :param trans_id:
    """
    params = {'trans_id': trans_id, 'title': request.form['title']}
    if 'sid_soid_mapping' not in app.config:
        app.config['sid_soid_mapping'] = dict()
    if request.args:
        params.update({k: v for k, v in request.args.items()})
    # Set TERM env for xterm.
    os.environ['TERM'] = 'xterm'

    # If psql is enabled in server mode, set psqlrc and hist paths
    # to individual user storage.
    if config.ENABLE_PSQL and config.SERVER_MODE:
        os.environ['PSQLRC'] = get_complete_file_path('.psqlrc', False)
        os.environ['PSQL_HISTORY'] = \
            get_complete_file_path('.psql_history', False)

    o_db_name = _get_database(params['sid'], params['did'])

    return render_template(
        'editor_template.html',
        sid=params['sid'],
        db=underscore_unescape(o_db_name) if o_db_name else 'postgres',
        server_type=params['server_type'],
        is_enable=config.ENABLE_PSQL,
        title=underscore_unescape(params['title']),
        theme=params['theme'],
        o_db_name=o_db_name,
        platform=_platform)
Example #2
0
def panel(trans_id):
    """
    This method calls index.html to render the erd tool.

    Args:
        panel_title: Title of the panel
    """

    params = {'trans_id': trans_id, 'title': request.form['title']}
    if request.args:
        params.update({k: v for k, v in request.args.items()})

    if 'gen' in params:
        params['gen'] = True if params['gen'] == 'true' else False

    close_url = request.form['close_url']

    # We need client OS information to render correct Keyboard shortcuts
    user_agent = UserAgent(request.headers.get('User-Agent'))
    """
    Animations and transitions are not automatically GPU accelerated and by
    default use browser's slow rendering engine. We need to set 'translate3d'
    value of '-webkit-transform' property in order to use GPU. After applying
    this property under linux, Webkit calculates wrong position of the
    elements so panel contents are not visible. To make it work, we need to
    explicitly set '-webkit-transform' property to 'none' for .ajs-notifier,
    .ajs-message, .ajs-modal classes.

    This issue is only with linux runtime application and observed in Query
    tool and debugger. When we open 'Open File' dialog then whole Query tool
    panel content is not visible though it contains HTML element in back end.

    The port number should have already been set by the runtime if we're
    running in desktop mode.
    """
    is_linux_platform = False

    from sys import platform as _platform
    if "linux" in _platform:
        is_linux_platform = True

    s = Server.query.filter_by(id=params['sid']).first()

    params.update({
        'bgcolor': s.bgcolor,
        'fgcolor': s.fgcolor,
        'client_platform': user_agent.platform,
        'is_desktop_mode': app.PGADMIN_RUNTIME,
        'is_linux': is_linux_platform
    })

    return render_template(
        "erd/index.html",
        title=underscore_unescape(params['title']),
        close_url=close_url,
        requirejs=True,
        basejs=True,
        params=json.dumps(params),
    )
Example #3
0
def get_conn_str_win(manager, db):
    """
    Get connection attributes for psql connection.
    :param manager:
    :param db:
    :return:
    """
    manager.export_password_env('PGPASSWORD')
    db = db.replace('"', '\\"')
    db = db.replace("'", "\\'")
    conn_attr =\
        'host=\'{0}\' port=\'{1}\' dbname=\'{2}\' user=\'{3}\' ' \
        'sslmode=\'{4}\' sslcompression=\'{5}\' ' \
        ''.format(
            manager.local_bind_host if manager.use_ssh_tunnel else
            manager.host,
            manager.local_bind_port if manager.use_ssh_tunnel else
            manager.port,
            db if db != '' else 'postgres',
            underscore_unescape(manager.user) if manager.user else 'postgres',
            manager.ssl_mode,
            True if manager.sslcompression else False,
        )

    if manager.hostaddr:
        conn_attr = " {0} hostaddr='{1}'".format(conn_attr, manager.hostaddr)

    if manager.passfile:
        conn_attr = " {0} passfile='{1}'".format(
            conn_attr, get_complete_file_path(manager.passfile))

    if get_complete_file_path(manager.sslcert):
        conn_attr = " {0} sslcert='{1}'".format(
            conn_attr, get_complete_file_path(manager.sslcert))

    if get_complete_file_path(manager.sslkey):
        conn_attr = " {0} sslkey='{1}'".format(
            conn_attr, get_complete_file_path(manager.sslkey))

    if get_complete_file_path(manager.sslrootcert):
        conn_attr = " {0} sslrootcert='{1}'".format(
            conn_attr, get_complete_file_path(manager.sslrootcert))

    if get_complete_file_path(manager.sslcrl):
        conn_attr = " {0} sslcrl='{1}'".format(
            conn_attr, get_complete_file_path(manager.sslcrl))

    if manager.service:
        conn_attr = " {0} service='{1}'".format(
            conn_attr, get_complete_file_path(manager.service))

    return conn_attr
Example #4
0
def panel(trans_id):
    """
    This method calls index.html to render the data grid.

    Args:
        trans_id: unique transaction id
    """

    url_params = None
    if request.args:
        url_params = {k: v for k, v in request.args.items()}

    if request.form:
        url_params['title'] = request.form['title']
        if 'sql_filter' in request.form:
            url_params['sql_filter'] = request.form['sql_filter']
        if 'query_url' in request.form:
            url_params['query_url'] = request.form['query_url']

    # We need client OS information to render correct Keyboard shortcuts
    user_agent = UserAgent(request.headers.get('User-Agent'))
    """
    Animations and transitions are not automatically GPU accelerated and by
    default use browser's slow rendering engine. We need to set 'translate3d'
    value of '-webkit-transform' property in order to use GPU. After applying
    this property under linux, Webkit calculates wrong position of the
    elements so panel contents are not visible. To make it work, we need to
    explicitly set '-webkit-transform' property to 'none' for .ajs-notifier,
    .ajs-message, .ajs-modal classes.

    This issue is only with linux runtime application and observed in Query
    tool and debugger. When we open 'Open File' dialog then whole Query tool
    panel content is not visible though it contains HTML element in back end.

    The port number should have already been set by the runtime if we're
    running in desktop mode.
    """
    is_linux_platform = False

    from sys import platform as _platform
    if "linux" in _platform:
        is_linux_platform = True

    # Fetch the server details
    bgcolor = None
    fgcolor = None

    s = Server.query.filter_by(id=url_params['sid']).first()
    if s and s.bgcolor:
        # If background is set to white means we do not have to change
        # the title background else change it as per user specified
        # background
        if s.bgcolor != '#ffffff':
            bgcolor = s.bgcolor
        fgcolor = s.fgcolor or 'black'

    layout = get_setting('SQLEditor/Layout')

    return render_template(
        "datagrid/index.html",
        _=gettext,
        uniqueId=trans_id,
        is_desktop_mode=app.PGADMIN_RUNTIME,
        is_linux=is_linux_platform,
        title=underscore_unescape(url_params['title']),
        url_params=json.dumps(url_params),
        client_platform=user_agent.platform,
        bgcolor=bgcolor,
        fgcolor=fgcolor,
        layout=layout,
    )
Example #5
0
def start_process(data):
    """
    Start the pty terminal and execute psql command and emit results to user.
    :param data:
    :return:
    """
    @copy_current_request_context
    def read_and_forward_pty_output(sid, data):

        max_read_bytes = 1024 * 20
        import time
        if _platform == 'win32':

            os.environ['PYWINPTY_BACKEND'] = '1'
            process = PtyProcess.spawn('cmd.exe')

            process.write(r'"{0}" "{1}" 2>>&1'.format(connection_data[0],
                                                      connection_data[1]))
            process.write("\r\n")
            app.config['sessions'][request.sid] = process
            pdata[request.sid] = process
            set_term_size(process, 50, 50)

            while True:
                read_stdout(process, sid, max_read_bytes, win_emit_output=True)
        else:

            p, parent, fd = create_pty_terminal(connection_data)

            while p and p.poll() is None:
                if request.sid in app.config['sessions']:
                    # This code is added to make this unit testable.
                    if "is_test" not in data:
                        sio.sleep(0.01)
                    else:
                        data['count'] += 1
                        if data['count'] == 5:
                            break

                    timeout = 0
                    # module provides access to platform-specific I/O
                    # monitoring functions
                    (data_ready, _, _) = select.select([parent, fd], [], [],
                                                       timeout)

                    read_terminal_data(parent, data_ready, max_read_bytes, sid)

    # Check user is authenticated and PSQL is enabled in config.
    if current_user.is_authenticated and config.ENABLE_PSQL:
        connection_data = []
        try:
            db = ''
            if data['db']:
                db = underscore_unescape(data['db']).replace('\\', "\\\\")

            data['db'] = db

            conn, manager = _get_connection(int(data['sid']), data)
            psql_utility = manager.utility('sql')
            connection_data = get_connection_str(psql_utility, db, manager)
        except Exception as e:
            # If any error raised during the start the PSQL emit error to UI.
            # request.sid: This sid is socket id.
            sio.emit(
                'conn_error', {
                    'error': 'Error while running psql command: {0}'.format(e),
                },
                namespace='/pty',
                room=request.sid)

        try:
            if str(data['sid']) not in app.config['sid_soid_mapping']:
                # request.sid: refer request.sid as socket id.
                app.config['sid_soid_mapping'][str(data['sid'])] = list()
                app.config['sid_soid_mapping'][str(data['sid'])].append(
                    request.sid)
            else:
                app.config['sid_soid_mapping'][str(data['sid'])].append(
                    request.sid)

            sio.start_background_task(read_and_forward_pty_output, request.sid,
                                      data)
        except Exception as e:
            sio.emit(
                'conn_error', {
                    'error': 'Error while running psql command: {0}'.format(e),
                },
                namespace='/pty',
                room=request.sid)
    else:
        # Show error if user is not authenticated.
        sio.emit('conn_not_allow', {'sid': request.sid},
                 namespace='/pty',
                 to=request.sid)