2016-05-12 22:19:48 -05:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
##########################################################################
|
|
|
|
#
|
|
|
|
# pgAdmin 4 - PostgreSQL Tools
|
|
|
|
#
|
2021-01-04 04:04:45 -06:00
|
|
|
# Copyright (C) 2013 - 2021, The pgAdmin Development Team
|
2016-05-12 22:19:48 -05:00
|
|
|
# This software is released under the PostgreSQL License
|
|
|
|
#
|
|
|
|
##########################################################################
|
|
|
|
|
|
|
|
"""
|
|
|
|
Introduce a function to run the process executor in detached mode.
|
|
|
|
"""
|
|
|
|
import csv
|
|
|
|
import os
|
2016-06-21 08:12:14 -05:00
|
|
|
import sys
|
2018-10-22 02:05:21 -05:00
|
|
|
import psutil
|
2016-06-21 08:12:14 -05:00
|
|
|
from abc import ABCMeta, abstractproperty, abstractmethod
|
|
|
|
from datetime import datetime
|
2016-05-12 22:19:48 -05:00
|
|
|
from pickle import dumps, loads
|
2020-02-11 02:58:57 -06:00
|
|
|
from subprocess import Popen, PIPE
|
|
|
|
import logging
|
2016-05-12 22:19:48 -05:00
|
|
|
|
2020-07-09 08:25:33 -05:00
|
|
|
from pgadmin.utils import u_encode, file_quote, fs_encoding, \
|
2020-10-23 05:44:55 -05:00
|
|
|
get_complete_file_path, get_storage_directory, IS_WIN
|
2020-11-12 06:17:21 -06:00
|
|
|
from pgadmin.browser.server_groups.servers.utils import does_server_exists
|
Resolved quite a few file-system encoding/decoding related cases.
In order to resolve the non-ascii characters in path (in user directory,
storage path, etc) on windows, we have converted the path into the
short-path, so that - we don't need to deal with the encoding issues
(specially with Python 2).
We've resolved majority of the issues with this patch.
We still need couple issues to resolve after this in the same area.
TODO
* Add better support for non-ascii characters in the database name on
windows with Python 3
* Improve the messages created after the background processes by
different modules (such as Backup, Restore, Import/Export, etc.),
which does not show short-paths, and xml representable characters for
non-ascii characters, when found in the database objects, and the file
PATH.
Fixes #2174, #1797, #2166, #1940
Initial patch by: Surinder Kumar
Reviewed by: Murtuza Zabuawala
2017-03-07 04:00:57 -06:00
|
|
|
|
2016-06-21 08:12:14 -05:00
|
|
|
import pytz
|
|
|
|
from dateutil import parser
|
2017-02-04 08:26:57 -06:00
|
|
|
from flask import current_app
|
2018-04-04 04:47:01 -05:00
|
|
|
from flask_babelex import gettext as _
|
2016-07-22 10:25:23 -05:00
|
|
|
from flask_security import current_user
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
import config
|
|
|
|
from pgadmin.model import Process, db
|
2020-04-30 06:52:48 -05:00
|
|
|
from io import StringIO
|
2016-05-12 22:19:48 -05:00
|
|
|
|
2018-10-25 06:33:34 -05:00
|
|
|
PROCESS_NOT_STARTED = 0
|
|
|
|
PROCESS_STARTED = 1
|
|
|
|
PROCESS_FINISHED = 2
|
|
|
|
PROCESS_TERMINATED = 3
|
2020-09-29 04:38:14 -05:00
|
|
|
PROCESS_NOT_FOUND = _("Could not find a process with the specified ID.")
|
2018-10-25 06:33:34 -05:00
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
def get_current_time(format='%Y-%m-%d %H:%M:%S.%f %z'):
|
|
|
|
"""
|
|
|
|
Generate the current time string in the given format.
|
|
|
|
"""
|
|
|
|
return datetime.utcnow().replace(
|
|
|
|
tzinfo=pytz.utc
|
|
|
|
).strftime(format)
|
|
|
|
|
|
|
|
|
2020-08-31 06:15:31 -05:00
|
|
|
class IProcessDesc(object, metaclass=ABCMeta):
|
2016-05-12 22:19:48 -05:00
|
|
|
@abstractproperty
|
|
|
|
def message(self):
|
|
|
|
pass
|
|
|
|
|
2016-05-15 05:29:32 -05:00
|
|
|
@abstractmethod
|
|
|
|
def details(self, cmd, args):
|
2016-05-12 22:19:48 -05:00
|
|
|
pass
|
|
|
|
|
2020-10-23 05:44:55 -05:00
|
|
|
@property
|
|
|
|
def current_storage_dir(self):
|
|
|
|
|
|
|
|
if config.SERVER_MODE:
|
|
|
|
|
|
|
|
file = self.bfile
|
|
|
|
try:
|
|
|
|
# check if file name is encoded with UTF-8
|
|
|
|
file = self.bfile.decode('utf-8')
|
2020-11-12 06:17:21 -06:00
|
|
|
except Exception:
|
2020-10-23 05:44:55 -05:00
|
|
|
# do nothing if bfile is not encoded.
|
2020-11-12 06:17:21 -06:00
|
|
|
pass
|
2020-10-23 05:44:55 -05:00
|
|
|
|
|
|
|
path = get_complete_file_path(file)
|
|
|
|
path = file if path is None else path
|
|
|
|
|
|
|
|
if IS_WIN:
|
|
|
|
path = os.path.realpath(path)
|
|
|
|
|
|
|
|
storage_directory = os.path.basename(get_storage_directory())
|
|
|
|
|
|
|
|
if storage_directory in path:
|
|
|
|
start = path.index(storage_directory)
|
|
|
|
end = start + (len(storage_directory))
|
|
|
|
last_dir = os.path.dirname(path[end:])
|
|
|
|
else:
|
|
|
|
last_dir = file
|
|
|
|
|
2020-11-12 06:17:21 -06:00
|
|
|
last_dir = replace_path_for_win(last_dir)
|
2020-10-23 05:44:55 -05:00
|
|
|
|
|
|
|
return None if hasattr(self, 'is_import') and self.is_import \
|
|
|
|
else last_dir
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
|
2020-11-12 06:17:21 -06:00
|
|
|
def replace_path_for_win(last_dir=None):
|
|
|
|
if IS_WIN:
|
|
|
|
if '\\' in last_dir and len(last_dir) == 1:
|
|
|
|
last_dir = last_dir.replace('\\', '\\\\')
|
|
|
|
else:
|
|
|
|
last_dir = last_dir.replace('\\', '/')
|
|
|
|
|
|
|
|
return last_dir
|
|
|
|
|
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
class BatchProcess(object):
|
|
|
|
def __init__(self, **kwargs):
|
|
|
|
|
|
|
|
self.id = self.desc = self.cmd = self.args = self.log_dir = \
|
|
|
|
self.stdout = self.stderr = self.stime = self.etime = \
|
|
|
|
self.ecode = None
|
2018-03-15 06:35:47 -05:00
|
|
|
self.env = dict()
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
if 'id' in kwargs:
|
|
|
|
self._retrieve_process(kwargs['id'])
|
|
|
|
else:
|
2018-02-09 06:57:37 -06:00
|
|
|
self._create_process(
|
|
|
|
kwargs['desc'], kwargs['cmd'], kwargs['args']
|
|
|
|
)
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
def _retrieve_process(self, _id):
|
|
|
|
p = Process.query.filter_by(pid=_id, user_id=current_user.id).first()
|
|
|
|
|
|
|
|
if p is None:
|
2020-09-29 04:38:14 -05:00
|
|
|
raise LookupError(PROCESS_NOT_FOUND)
|
2016-05-12 22:19:48 -05:00
|
|
|
|
2020-04-30 06:52:48 -05:00
|
|
|
tmp_desc = loads(p.desc)
|
2018-03-13 15:45:20 -05:00
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
# ID
|
|
|
|
self.id = _id
|
|
|
|
# Description
|
2018-03-13 15:45:20 -05:00
|
|
|
self.desc = tmp_desc
|
2016-05-12 22:19:48 -05:00
|
|
|
# Status Acknowledged time
|
|
|
|
self.atime = p.acknowledge
|
|
|
|
# Command
|
|
|
|
self.cmd = p.command
|
|
|
|
# Arguments
|
|
|
|
self.args = p.arguments
|
|
|
|
# Log Directory
|
|
|
|
self.log_dir = p.logdir
|
|
|
|
# Standard ouput log file
|
|
|
|
self.stdout = os.path.join(p.logdir, 'out')
|
|
|
|
# Standard error log file
|
|
|
|
self.stderr = os.path.join(p.logdir, 'err')
|
|
|
|
# Start time
|
|
|
|
self.stime = p.start_time
|
|
|
|
# End time
|
|
|
|
self.etime = p.end_time
|
|
|
|
# Exit code
|
|
|
|
self.ecode = p.exit_code
|
2018-10-25 06:33:34 -05:00
|
|
|
# Process State
|
|
|
|
self.process_state = p.process_state
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
def _create_process(self, _desc, _cmd, _args):
|
|
|
|
ctime = get_current_time(format='%y%m%d%H%M%S%f')
|
|
|
|
log_dir = os.path.join(
|
|
|
|
config.SESSION_DB_PATH, 'process_logs'
|
2016-06-21 08:21:06 -05:00
|
|
|
)
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
def random_number(size):
|
|
|
|
import random
|
|
|
|
import string
|
|
|
|
|
|
|
|
return ''.join(
|
|
|
|
random.choice(
|
|
|
|
string.ascii_uppercase + string.digits
|
|
|
|
) for _ in range(size)
|
|
|
|
)
|
|
|
|
|
|
|
|
created = False
|
|
|
|
size = 0
|
2020-07-28 05:50:26 -05:00
|
|
|
uid = ctime
|
2016-05-12 22:19:48 -05:00
|
|
|
while not created:
|
|
|
|
try:
|
2020-07-28 05:50:26 -05:00
|
|
|
uid += random_number(size)
|
|
|
|
log_dir = os.path.join(log_dir, uid)
|
2016-05-12 22:19:48 -05:00
|
|
|
size += 1
|
|
|
|
if not os.path.exists(log_dir):
|
|
|
|
os.makedirs(log_dir, int('700', 8))
|
|
|
|
created = True
|
|
|
|
except OSError as oe:
|
|
|
|
import errno
|
|
|
|
if oe.errno != errno.EEXIST:
|
|
|
|
raise
|
|
|
|
|
|
|
|
# ID
|
|
|
|
self.id = ctime
|
|
|
|
# Description
|
|
|
|
self.desc = _desc
|
|
|
|
# Status Acknowledged time
|
|
|
|
self.atime = None
|
|
|
|
# Command
|
|
|
|
self.cmd = _cmd
|
|
|
|
# Log Directory
|
|
|
|
self.log_dir = log_dir
|
|
|
|
# Standard ouput log file
|
|
|
|
self.stdout = os.path.join(log_dir, 'out')
|
|
|
|
# Standard error log file
|
|
|
|
self.stderr = os.path.join(log_dir, 'err')
|
|
|
|
# Start time
|
|
|
|
self.stime = None
|
|
|
|
# End time
|
|
|
|
self.etime = None
|
|
|
|
# Exit code
|
|
|
|
self.ecode = None
|
2018-10-25 06:33:34 -05:00
|
|
|
# Process State
|
|
|
|
self.process_state = PROCESS_NOT_STARTED
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
# Arguments
|
2017-02-04 08:26:57 -06:00
|
|
|
self.args = _args
|
2016-05-12 22:19:48 -05:00
|
|
|
args_csv_io = StringIO()
|
|
|
|
csv_writer = csv.writer(
|
|
|
|
args_csv_io, delimiter=str(','), quoting=csv.QUOTE_MINIMAL
|
|
|
|
)
|
2020-04-30 06:52:48 -05:00
|
|
|
csv_writer.writerow(_args)
|
Resolved quite a few file-system encoding/decoding related cases.
In order to resolve the non-ascii characters in path (in user directory,
storage path, etc) on windows, we have converted the path into the
short-path, so that - we don't need to deal with the encoding issues
(specially with Python 2).
We've resolved majority of the issues with this patch.
We still need couple issues to resolve after this in the same area.
TODO
* Add better support for non-ascii characters in the database name on
windows with Python 3
* Improve the messages created after the background processes by
different modules (such as Backup, Restore, Import/Export, etc.),
which does not show short-paths, and xml representable characters for
non-ascii characters, when found in the database objects, and the file
PATH.
Fixes #2174, #1797, #2166, #1940
Initial patch by: Surinder Kumar
Reviewed by: Murtuza Zabuawala
2017-03-07 04:00:57 -06:00
|
|
|
|
|
|
|
args_val = args_csv_io.getvalue().strip(str('\r\n'))
|
2018-03-13 15:45:20 -05:00
|
|
|
tmp_desc = dumps(self.desc)
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
j = Process(
|
2020-07-28 05:50:26 -05:00
|
|
|
pid=int(uid),
|
2018-02-09 06:57:37 -06:00
|
|
|
command=_cmd,
|
2020-04-30 06:52:48 -05:00
|
|
|
arguments=args_val,
|
2018-02-09 06:57:37 -06:00
|
|
|
logdir=log_dir,
|
2018-03-13 15:45:20 -05:00
|
|
|
desc=tmp_desc,
|
2018-02-09 06:57:37 -06:00
|
|
|
user_id=current_user.id
|
2016-05-12 22:19:48 -05:00
|
|
|
)
|
|
|
|
db.session.add(j)
|
|
|
|
db.session.commit()
|
|
|
|
|
2021-01-19 02:04:14 -06:00
|
|
|
def check_start_end_time(self):
|
|
|
|
"""
|
|
|
|
Check start and end time to check process is still executing or not.
|
|
|
|
:return:
|
|
|
|
"""
|
2016-05-12 22:19:48 -05:00
|
|
|
if self.stime is not None:
|
|
|
|
if self.etime is None:
|
2020-08-07 02:07:00 -05:00
|
|
|
raise RuntimeError(_('The process has already been started.'))
|
|
|
|
raise RuntimeError(
|
2017-04-05 07:38:14 -05:00
|
|
|
_('The process has already finished and cannot be restarted.')
|
2016-06-20 11:00:54 -05:00
|
|
|
)
|
2016-05-12 22:19:48 -05:00
|
|
|
|
2021-01-19 02:04:14 -06:00
|
|
|
def start(self, cb=None):
|
|
|
|
self.check_start_end_time()
|
|
|
|
|
Resolved quite a few file-system encoding/decoding related cases.
In order to resolve the non-ascii characters in path (in user directory,
storage path, etc) on windows, we have converted the path into the
short-path, so that - we don't need to deal with the encoding issues
(specially with Python 2).
We've resolved majority of the issues with this patch.
We still need couple issues to resolve after this in the same area.
TODO
* Add better support for non-ascii characters in the database name on
windows with Python 3
* Improve the messages created after the background processes by
different modules (such as Backup, Restore, Import/Export, etc.),
which does not show short-paths, and xml representable characters for
non-ascii characters, when found in the database objects, and the file
PATH.
Fixes #2174, #1797, #2166, #1940
Initial patch by: Surinder Kumar
Reviewed by: Murtuza Zabuawala
2017-03-07 04:00:57 -06:00
|
|
|
executor = file_quote(os.path.join(
|
2020-08-31 06:15:31 -05:00
|
|
|
os.path.dirname(u_encode(__file__)), 'process_executor.py'
|
Resolved quite a few file-system encoding/decoding related cases.
In order to resolve the non-ascii characters in path (in user directory,
storage path, etc) on windows, we have converted the path into the
short-path, so that - we don't need to deal with the encoding issues
(specially with Python 2).
We've resolved majority of the issues with this patch.
We still need couple issues to resolve after this in the same area.
TODO
* Add better support for non-ascii characters in the database name on
windows with Python 3
* Improve the messages created after the background processes by
different modules (such as Backup, Restore, Import/Export, etc.),
which does not show short-paths, and xml representable characters for
non-ascii characters, when found in the database objects, and the file
PATH.
Fixes #2174, #1797, #2166, #1940
Initial patch by: Surinder Kumar
Reviewed by: Murtuza Zabuawala
2017-03-07 04:00:57 -06:00
|
|
|
))
|
2017-02-04 08:26:57 -06:00
|
|
|
|
2021-02-19 04:14:49 -06:00
|
|
|
if os.name == 'nt':
|
|
|
|
paths = os.environ['PATH'].split(os.pathsep)
|
|
|
|
|
|
|
|
current_app.logger.info(
|
|
|
|
"Process Executor: Operating System Path %s",
|
|
|
|
str(paths)
|
|
|
|
)
|
|
|
|
|
|
|
|
interpreter = self.get_interpreter(paths)
|
|
|
|
else:
|
|
|
|
interpreter = sys.executable
|
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
cmd = [
|
2021-02-19 04:14:49 -06:00
|
|
|
interpreter if interpreter is not None else 'python',
|
2017-02-04 08:26:57 -06:00
|
|
|
executor, self.cmd
|
2016-05-12 22:19:48 -05:00
|
|
|
]
|
2017-02-04 08:26:57 -06:00
|
|
|
cmd.extend(self.args)
|
|
|
|
|
2020-04-30 06:52:48 -05:00
|
|
|
current_app.logger.info(
|
2020-08-31 06:15:31 -05:00
|
|
|
"Executing the process executor with the arguments: %s",
|
2020-04-30 06:52:48 -05:00
|
|
|
str(cmd)
|
|
|
|
)
|
2017-02-04 08:26:57 -06:00
|
|
|
|
|
|
|
# Make a copy of environment, and add new variables to support
|
|
|
|
env = os.environ.copy()
|
|
|
|
env['PROCID'] = self.id
|
|
|
|
env['OUTDIR'] = self.log_dir
|
|
|
|
env['PGA_BGP_FOREGROUND'] = "1"
|
|
|
|
|
2018-03-15 06:35:47 -05:00
|
|
|
if self.env:
|
|
|
|
env.update(self.env)
|
|
|
|
|
Resolved quite a few file-system encoding/decoding related cases.
In order to resolve the non-ascii characters in path (in user directory,
storage path, etc) on windows, we have converted the path into the
short-path, so that - we don't need to deal with the encoding issues
(specially with Python 2).
We've resolved majority of the issues with this patch.
We still need couple issues to resolve after this in the same area.
TODO
* Add better support for non-ascii characters in the database name on
windows with Python 3
* Improve the messages created after the background processes by
different modules (such as Backup, Restore, Import/Export, etc.),
which does not show short-paths, and xml representable characters for
non-ascii characters, when found in the database objects, and the file
PATH.
Fixes #2174, #1797, #2166, #1940
Initial patch by: Surinder Kumar
Reviewed by: Murtuza Zabuawala
2017-03-07 04:00:57 -06:00
|
|
|
if cb is not None:
|
|
|
|
cb(env)
|
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
if os.name == 'nt':
|
2017-02-04 08:26:57 -06:00
|
|
|
DETACHED_PROCESS = 0x00000008
|
|
|
|
from subprocess import CREATE_NEW_PROCESS_GROUP
|
|
|
|
|
|
|
|
# We need to redirect the standard input, standard output, and
|
|
|
|
# standard error to devnull in order to allow it start in detached
|
|
|
|
# mode on
|
|
|
|
stdout = os.devnull
|
|
|
|
stderr = stdout
|
|
|
|
stdin = open(os.devnull, "r")
|
|
|
|
stdout = open(stdout, "a")
|
|
|
|
stderr = open(stderr, "a")
|
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
p = Popen(
|
2018-02-09 06:57:37 -06:00
|
|
|
cmd,
|
|
|
|
close_fds=False,
|
|
|
|
env=env,
|
|
|
|
stdout=stdout.fileno(),
|
|
|
|
stderr=stderr.fileno(),
|
|
|
|
stdin=stdin.fileno(),
|
2017-02-04 08:26:57 -06:00
|
|
|
creationflags=(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS)
|
2016-05-12 22:19:48 -05:00
|
|
|
)
|
|
|
|
else:
|
2020-02-11 02:58:57 -06:00
|
|
|
# if in debug mode, wait for process to complete and
|
|
|
|
# get the stdout and stderr of popen.
|
|
|
|
if config.CONSOLE_LOG_LEVEL <= logging.DEBUG:
|
2021-02-04 03:20:26 -06:00
|
|
|
p = self.get_process_output(cmd, env)
|
2020-02-11 02:58:57 -06:00
|
|
|
else:
|
|
|
|
p = Popen(
|
|
|
|
cmd, close_fds=True, stdout=None, stderr=None, stdin=None,
|
2021-01-19 02:04:14 -06:00
|
|
|
preexec_fn=self.preexec_function, env=env
|
2020-02-11 02:58:57 -06:00
|
|
|
)
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
self.ecode = p.poll()
|
2016-10-21 09:35:06 -05:00
|
|
|
|
2017-02-04 08:26:57 -06:00
|
|
|
# Execution completed immediately.
|
2017-04-05 07:38:14 -05:00
|
|
|
# Process executor cannot update the status, if it was not able to
|
2017-02-04 08:26:57 -06:00
|
|
|
# start properly.
|
|
|
|
if self.ecode is not None and self.ecode != 0:
|
|
|
|
# There is no way to find out the error message from this process
|
|
|
|
# as standard output, and standard error were redirected to
|
|
|
|
# devnull.
|
2016-10-21 09:35:06 -05:00
|
|
|
p = Process.query.filter_by(
|
|
|
|
pid=self.id, user_id=current_user.id
|
|
|
|
).first()
|
|
|
|
p.start_time = p.end_time = get_current_time()
|
|
|
|
if not p.exit_code:
|
|
|
|
p.exit_code = self.ecode
|
2018-10-25 06:33:34 -05:00
|
|
|
p.process_state = PROCESS_FINISHED
|
|
|
|
db.session.commit()
|
|
|
|
else:
|
|
|
|
# Update the process state to "Started"
|
|
|
|
p = Process.query.filter_by(
|
|
|
|
pid=self.id, user_id=current_user.id
|
|
|
|
).first()
|
|
|
|
p.process_state = PROCESS_STARTED
|
2016-10-21 09:35:06 -05:00
|
|
|
db.session.commit()
|
2016-05-12 22:19:48 -05:00
|
|
|
|
2021-01-19 02:04:14 -06:00
|
|
|
def get_process_output(self, cmd, env):
|
|
|
|
"""
|
|
|
|
:param cmd:
|
|
|
|
:param env:
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
p = Popen(
|
|
|
|
cmd, close_fds=True, stdout=PIPE, stderr=PIPE, stdin=None,
|
|
|
|
preexec_fn=self.preexec_function, env=env
|
|
|
|
)
|
2017-02-04 08:26:57 -06:00
|
|
|
|
2021-01-19 02:04:14 -06:00
|
|
|
output, errors = p.communicate()
|
|
|
|
output = output.decode() \
|
|
|
|
if hasattr(output, 'decode') else output
|
|
|
|
errors = errors.decode() \
|
|
|
|
if hasattr(errors, 'decode') else errors
|
|
|
|
current_app.logger.debug(
|
|
|
|
'Process Watcher Out:{0}'.format(output))
|
|
|
|
current_app.logger.debug(
|
|
|
|
'Process Watcher Err:{0}'.format(errors))
|
|
|
|
|
2021-02-04 03:20:26 -06:00
|
|
|
return p
|
2021-01-19 02:04:14 -06:00
|
|
|
|
|
|
|
def preexec_function(self):
|
|
|
|
import signal
|
|
|
|
# Detaching from the parent process group
|
|
|
|
os.setpgrp()
|
|
|
|
# Explicitly ignoring signals in the child process
|
|
|
|
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
|
|
|
|
2021-02-19 04:14:49 -06:00
|
|
|
def get_interpreter(self, paths):
|
|
|
|
"""
|
|
|
|
Get interpreter.
|
|
|
|
:param paths:
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
paths.insert(0, os.path.join(u_encode(sys.prefix), 'Scripts'))
|
|
|
|
paths.insert(0, u_encode(sys.prefix))
|
|
|
|
|
|
|
|
interpreter = self.which('pythonw.exe', paths)
|
|
|
|
if interpreter is None:
|
|
|
|
interpreter = self.which('python.exe', paths)
|
|
|
|
|
|
|
|
current_app.logger.info(
|
|
|
|
"Process Executor: Interpreter value in path: %s",
|
|
|
|
str(interpreter)
|
|
|
|
)
|
|
|
|
if interpreter is None and current_app.PGADMIN_RUNTIME:
|
|
|
|
# We've faced an issue with Windows 2008 R2 (x86) regarding,
|
|
|
|
# not honouring the environment variables set under the Qt
|
|
|
|
# (e.g. runtime), and also setting PYTHONHOME same as
|
|
|
|
# sys.executable (i.e. pgAdmin4.exe).
|
|
|
|
#
|
|
|
|
# As we know, we're running it under the runtime, we can assume
|
|
|
|
# that 'venv' directory will be available outside of 'bin'
|
|
|
|
# directory.
|
|
|
|
#
|
|
|
|
# We would try out luck to find python executable based on that
|
|
|
|
# assumptions.
|
|
|
|
bin_path = os.path.dirname(sys.executable)
|
|
|
|
|
|
|
|
venv = os.path.realpath(
|
|
|
|
os.path.join(bin_path, '..\\venv')
|
|
|
|
)
|
|
|
|
|
|
|
|
interpreter = self.which('pythonw.exe', [venv])
|
|
|
|
if interpreter is None:
|
|
|
|
interpreter = self.which('python.exe', [venv])
|
|
|
|
|
|
|
|
current_app.logger.info(
|
|
|
|
"Process Executor: Interpreter value in virtual "
|
|
|
|
"environment: %s", str(interpreter)
|
|
|
|
)
|
|
|
|
|
|
|
|
if interpreter is not None:
|
|
|
|
# Our assumptions are proven right.
|
|
|
|
# Let's append the 'bin' directory to the PATH environment
|
|
|
|
# variable. And, also set PYTHONHOME environment variable
|
|
|
|
# to 'venv' directory.
|
|
|
|
os.environ['PATH'] = bin_path + ';' + os.environ['PATH']
|
|
|
|
os.environ['PYTHONHOME'] = venv
|
|
|
|
|
|
|
|
return interpreter
|
|
|
|
|
|
|
|
def which(self, program, paths):
|
|
|
|
def is_exe(fpath):
|
|
|
|
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
|
|
|
|
|
|
|
|
for path in paths:
|
|
|
|
if not os.path.isdir(path):
|
|
|
|
continue
|
|
|
|
exe_file = os.path.join(u_encode(path, fs_encoding), program)
|
|
|
|
if is_exe(exe_file):
|
|
|
|
return file_quote(exe_file)
|
|
|
|
return None
|
|
|
|
|
2021-01-19 02:04:14 -06:00
|
|
|
def read_log(self, logfile, log, pos, ctime, ecode=None, enc='utf-8'):
|
|
|
|
import re
|
|
|
|
completed = True
|
|
|
|
idx = 0
|
|
|
|
c = re.compile(r"(\d+),(.*$)")
|
|
|
|
|
|
|
|
if not os.path.isfile(logfile):
|
|
|
|
return 0, False
|
|
|
|
|
|
|
|
with open(logfile, 'rb') as f:
|
|
|
|
eofs = os.fstat(f.fileno()).st_size
|
|
|
|
f.seek(pos, 0)
|
|
|
|
if pos == eofs and ecode is None:
|
|
|
|
completed = False
|
|
|
|
|
|
|
|
while pos < eofs:
|
|
|
|
idx += 1
|
|
|
|
line = f.readline()
|
|
|
|
line = line.decode(enc, 'replace')
|
|
|
|
r = c.split(line)
|
|
|
|
if len(r) < 3:
|
|
|
|
# ignore this line
|
2017-02-04 08:26:57 -06:00
|
|
|
pos = f.tell()
|
2021-01-19 02:04:14 -06:00
|
|
|
continue
|
|
|
|
if r[1] > ctime:
|
|
|
|
completed = False
|
|
|
|
break
|
|
|
|
log.append([r[1], r[2]])
|
|
|
|
pos = f.tell()
|
|
|
|
if idx >= 1024:
|
|
|
|
completed = False
|
|
|
|
break
|
|
|
|
if pos == eofs:
|
|
|
|
if ecode is None:
|
2016-05-12 22:19:48 -05:00
|
|
|
completed = False
|
2021-01-19 02:04:14 -06:00
|
|
|
break
|
|
|
|
|
|
|
|
return pos, completed
|
2016-05-12 22:19:48 -05:00
|
|
|
|
2021-01-19 02:04:14 -06:00
|
|
|
def status(self, out=0, err=0):
|
|
|
|
ctime = get_current_time(format='%y%m%d%H%M%S%f')
|
|
|
|
|
|
|
|
stdout = []
|
|
|
|
stderr = []
|
|
|
|
out_completed = err_completed = False
|
|
|
|
process_output = (out != -1 and err != -1)
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
j = Process.query.filter_by(
|
|
|
|
pid=self.id, user_id=current_user.id
|
|
|
|
).first()
|
2021-01-19 02:04:14 -06:00
|
|
|
enc = sys.getdefaultencoding()
|
|
|
|
if enc == 'ascii':
|
|
|
|
enc = 'utf-8'
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
execution_time = None
|
|
|
|
|
|
|
|
if j is not None:
|
2017-02-04 08:26:57 -06:00
|
|
|
status, updated = BatchProcess.update_process_info(j)
|
|
|
|
if updated:
|
|
|
|
db.session.commit()
|
2016-05-12 22:19:48 -05:00
|
|
|
self.stime = j.start_time
|
|
|
|
self.etime = j.end_time
|
|
|
|
self.ecode = j.exit_code
|
|
|
|
|
|
|
|
if self.stime is not None:
|
|
|
|
stime = parser.parse(self.stime)
|
|
|
|
etime = parser.parse(self.etime or get_current_time())
|
|
|
|
|
2018-06-15 09:03:53 -05:00
|
|
|
execution_time = BatchProcess.total_seconds(etime - stime)
|
2016-05-12 22:19:48 -05:00
|
|
|
|
2017-11-27 07:00:47 -06:00
|
|
|
if process_output:
|
2021-01-19 02:04:14 -06:00
|
|
|
out, out_completed = self.read_log(
|
|
|
|
self.stdout, stdout, out, ctime, self.ecode, enc
|
2018-02-09 06:57:37 -06:00
|
|
|
)
|
2021-01-19 02:04:14 -06:00
|
|
|
err, err_completed = self.read_log(
|
|
|
|
self.stderr, stderr, err, ctime, self.ecode, enc
|
2018-02-09 06:57:37 -06:00
|
|
|
)
|
2016-05-12 22:19:48 -05:00
|
|
|
else:
|
|
|
|
out_completed = err_completed = False
|
|
|
|
|
|
|
|
if out == -1 or err == -1:
|
|
|
|
return {
|
2017-02-04 08:26:57 -06:00
|
|
|
'start_time': self.stime,
|
2016-05-12 22:19:48 -05:00
|
|
|
'exit_code': self.ecode,
|
2018-10-25 06:33:34 -05:00
|
|
|
'execution_time': execution_time,
|
|
|
|
'process_state': self.process_state
|
2016-05-12 22:19:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2018-02-09 06:57:37 -06:00
|
|
|
'out': {
|
|
|
|
'pos': out,
|
|
|
|
'lines': stdout,
|
|
|
|
'done': out_completed
|
|
|
|
},
|
|
|
|
'err': {
|
|
|
|
'pos': err,
|
|
|
|
'lines': stderr,
|
|
|
|
'done': err_completed
|
|
|
|
},
|
2017-02-04 08:26:57 -06:00
|
|
|
'start_time': self.stime,
|
2016-05-12 22:19:48 -05:00
|
|
|
'exit_code': self.ecode,
|
2018-10-25 06:33:34 -05:00
|
|
|
'execution_time': execution_time,
|
|
|
|
'process_state': self.process_state
|
2016-05-12 22:19:48 -05:00
|
|
|
}
|
|
|
|
|
2020-08-21 03:22:05 -05:00
|
|
|
@staticmethod
|
|
|
|
def _check_start_time(p, data):
|
|
|
|
"""
|
|
|
|
Check start time and its related other timing checks.
|
|
|
|
:param p: Process.
|
|
|
|
:param data: Data
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
if 'start_time' in data and data['start_time']:
|
|
|
|
p.start_time = data['start_time']
|
|
|
|
|
|
|
|
# We can't have 'exit_code' without the 'start_time'
|
|
|
|
if 'exit_code' in data and \
|
|
|
|
data['exit_code'] is not None:
|
|
|
|
p.exit_code = data['exit_code']
|
|
|
|
|
|
|
|
# We can't have 'end_time' without the 'exit_code'.
|
|
|
|
if 'end_time' in data and data['end_time']:
|
|
|
|
p.end_time = data['end_time']
|
|
|
|
|
2017-02-04 08:26:57 -06:00
|
|
|
@staticmethod
|
|
|
|
def update_process_info(p):
|
|
|
|
if p.start_time is None or p.end_time is None:
|
|
|
|
status = os.path.join(p.logdir, 'status')
|
|
|
|
if not os.path.isfile(status):
|
|
|
|
return False, False
|
|
|
|
|
|
|
|
with open(status, 'r') as fp:
|
|
|
|
import json
|
|
|
|
try:
|
|
|
|
data = json.load(fp)
|
|
|
|
|
|
|
|
# First - check for the existance of 'start_time'.
|
2020-08-21 03:22:05 -05:00
|
|
|
BatchProcess._check_start_time(p, data)
|
2018-10-22 02:05:21 -05:00
|
|
|
# get the pid of the utility.
|
|
|
|
if 'pid' in data:
|
|
|
|
p.utility_pid = data['pid']
|
|
|
|
|
2017-02-04 08:26:57 -06:00
|
|
|
return True, True
|
|
|
|
|
|
|
|
except ValueError as e:
|
|
|
|
current_app.logger.warning(
|
2018-02-09 06:57:37 -06:00
|
|
|
_("Status for the background process '{0}' could "
|
|
|
|
"not be loaded.").format(p.pid)
|
2017-02-04 08:26:57 -06:00
|
|
|
)
|
|
|
|
current_app.logger.exception(e)
|
|
|
|
return False, False
|
|
|
|
return True, False
|
|
|
|
|
2020-08-21 03:22:05 -05:00
|
|
|
@staticmethod
|
|
|
|
def _check_process_desc(p):
|
|
|
|
"""
|
|
|
|
Check process desc instance and return data according to process.
|
|
|
|
:param p: process
|
|
|
|
:return: return value for details, type_desc and desc related
|
|
|
|
to process
|
|
|
|
"""
|
|
|
|
desc = loads(p.desc)
|
|
|
|
details = desc
|
|
|
|
type_desc = ''
|
2020-10-23 05:44:55 -05:00
|
|
|
current_storage_dir = None
|
2020-08-21 03:22:05 -05:00
|
|
|
|
|
|
|
if isinstance(desc, IProcessDesc):
|
2020-10-23 05:44:55 -05:00
|
|
|
|
|
|
|
from pgadmin.tools.backup import BackupMessage
|
|
|
|
from pgadmin.tools.import_export import IEMessage
|
2020-08-21 03:22:05 -05:00
|
|
|
args = []
|
|
|
|
args_csv = StringIO(
|
|
|
|
p.arguments.encode('utf-8')
|
|
|
|
if hasattr(p.arguments, 'decode') else p.arguments
|
|
|
|
)
|
|
|
|
args_reader = csv.reader(args_csv, delimiter=str(','))
|
|
|
|
for arg in args_reader:
|
|
|
|
args = args + arg
|
|
|
|
details = desc.details(p.command, args)
|
|
|
|
type_desc = desc.type_desc
|
2020-10-23 05:44:55 -05:00
|
|
|
if isinstance(desc, (BackupMessage, IEMessage)):
|
|
|
|
current_storage_dir = desc.current_storage_dir
|
2020-08-21 03:22:05 -05:00
|
|
|
desc = desc.message
|
|
|
|
|
2020-10-23 05:44:55 -05:00
|
|
|
return desc, details, type_desc, current_storage_dir
|
2020-08-21 03:22:05 -05:00
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
@staticmethod
|
|
|
|
def list():
|
|
|
|
processes = Process.query.filter_by(user_id=current_user.id)
|
2017-02-04 08:26:57 -06:00
|
|
|
changed = False
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
res = []
|
|
|
|
for p in processes:
|
2017-02-04 08:26:57 -06:00
|
|
|
status, updated = BatchProcess.update_process_info(p)
|
|
|
|
if not status:
|
|
|
|
continue
|
2020-08-21 03:22:05 -05:00
|
|
|
elif not changed:
|
2017-02-04 08:26:57 -06:00
|
|
|
changed = updated
|
|
|
|
|
|
|
|
if p.start_time is None or (
|
|
|
|
p.acknowledge is not None and p.end_time is None
|
|
|
|
):
|
2016-05-12 22:19:48 -05:00
|
|
|
continue
|
2017-02-04 08:26:57 -06:00
|
|
|
|
2020-11-12 06:17:21 -06:00
|
|
|
if BatchProcess._operate_orphan_process(p):
|
|
|
|
continue
|
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
execution_time = None
|
|
|
|
|
|
|
|
stime = parser.parse(p.start_time)
|
|
|
|
etime = parser.parse(p.end_time or get_current_time())
|
|
|
|
|
2018-06-15 09:03:53 -05:00
|
|
|
execution_time = BatchProcess.total_seconds(etime - stime)
|
2020-08-21 03:22:05 -05:00
|
|
|
|
2020-10-23 05:44:55 -05:00
|
|
|
desc, details, type_desc, current_storage_dir = BatchProcess.\
|
|
|
|
_check_process_desc(p)
|
2016-05-12 22:19:48 -05:00
|
|
|
|
|
|
|
res.append({
|
|
|
|
'id': p.pid,
|
|
|
|
'desc': desc,
|
2019-01-16 00:25:08 -06:00
|
|
|
'type_desc': type_desc,
|
2016-05-12 22:19:48 -05:00
|
|
|
'details': details,
|
2016-06-17 07:54:31 -05:00
|
|
|
'stime': stime,
|
2016-05-12 22:19:48 -05:00
|
|
|
'etime': p.end_time,
|
|
|
|
'exit_code': p.exit_code,
|
|
|
|
'acknowledge': p.acknowledge,
|
2018-10-25 06:33:34 -05:00
|
|
|
'execution_time': execution_time,
|
2020-10-23 05:44:55 -05:00
|
|
|
'process_state': p.process_state,
|
|
|
|
'current_storage_dir': current_storage_dir,
|
2016-05-12 22:19:48 -05:00
|
|
|
})
|
|
|
|
|
2017-02-04 08:26:57 -06:00
|
|
|
if changed:
|
|
|
|
db.session.commit()
|
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
return res
|
|
|
|
|
2020-11-12 06:17:21 -06:00
|
|
|
@staticmethod
|
|
|
|
def _operate_orphan_process(p):
|
|
|
|
|
|
|
|
if p and p.desc:
|
|
|
|
desc = loads(p.desc)
|
|
|
|
if does_server_exists(desc.sid, current_user.id) is False:
|
|
|
|
current_app.logger.warning(
|
|
|
|
_("Server with id '{0}' is either removed or does "
|
|
|
|
"not exists for the background process "
|
|
|
|
"'{1}'").format(desc.sid, p.pid)
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
BatchProcess.acknowledge(p.pid)
|
|
|
|
except LookupError as lerr:
|
|
|
|
current_app.logger.warning(
|
|
|
|
_("Status for the background process '{0}' could "
|
|
|
|
"not be loaded.").format(p.pid)
|
|
|
|
)
|
|
|
|
current_app.logger.exception(lerr)
|
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
2018-06-15 09:03:53 -05:00
|
|
|
@staticmethod
|
|
|
|
def total_seconds(dt):
|
2019-01-16 00:25:08 -06:00
|
|
|
return round(dt.total_seconds(), 2)
|
2018-06-15 09:03:53 -05:00
|
|
|
|
2016-05-12 22:19:48 -05:00
|
|
|
@staticmethod
|
2017-02-04 08:26:57 -06:00
|
|
|
def acknowledge(_pid):
|
|
|
|
"""
|
|
|
|
Acknowledge from the user, he/she has alredy watched the status.
|
|
|
|
|
|
|
|
Update the acknowledgement status, if the process is still running.
|
|
|
|
And, delete the process information from the configuration, and the log
|
|
|
|
files related to the process, if it has already been completed.
|
|
|
|
"""
|
2016-05-12 22:19:48 -05:00
|
|
|
p = Process.query.filter_by(
|
|
|
|
user_id=current_user.id, pid=_pid
|
|
|
|
).first()
|
|
|
|
|
|
|
|
if p is None:
|
2020-09-29 04:38:14 -05:00
|
|
|
raise LookupError(PROCESS_NOT_FOUND)
|
2016-05-12 22:19:48 -05:00
|
|
|
|
2017-02-04 08:26:57 -06:00
|
|
|
if p.end_time is not None:
|
|
|
|
logdir = p.logdir
|
2016-05-12 22:19:48 -05:00
|
|
|
db.session.delete(p)
|
2017-02-04 08:26:57 -06:00
|
|
|
import shutil
|
|
|
|
shutil.rmtree(logdir, True)
|
2016-05-12 22:19:48 -05:00
|
|
|
else:
|
|
|
|
p.acknowledge = get_current_time()
|
|
|
|
|
|
|
|
db.session.commit()
|
2018-03-15 06:35:47 -05:00
|
|
|
|
|
|
|
def set_env_variables(self, server, **kwargs):
|
|
|
|
"""Set environment variables"""
|
2018-03-19 06:01:04 -05:00
|
|
|
if server:
|
|
|
|
# Set SSL related ENV variables
|
|
|
|
if server.sslcert and server.sslkey and server.sslrootcert:
|
|
|
|
# SSL environment variables
|
|
|
|
self.env['PGSSLMODE'] = server.ssl_mode
|
|
|
|
self.env['PGSSLCERT'] = get_complete_file_path(server.sslcert)
|
|
|
|
self.env['PGSSLKEY'] = get_complete_file_path(server.sslkey)
|
|
|
|
self.env['PGSSLROOTCERT'] = get_complete_file_path(
|
|
|
|
server.sslrootcert
|
|
|
|
)
|
|
|
|
|
|
|
|
# Set service name related ENV variable
|
|
|
|
if server.service:
|
|
|
|
self.env['PGSERVICE'] = server.service
|
2018-03-15 06:35:47 -05:00
|
|
|
|
|
|
|
if 'env' in kwargs:
|
|
|
|
self.env.update(kwargs['env'])
|
2018-10-22 02:05:21 -05:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def stop_process(_pid):
|
|
|
|
"""
|
|
|
|
"""
|
|
|
|
p = Process.query.filter_by(
|
|
|
|
user_id=current_user.id, pid=_pid
|
|
|
|
).first()
|
|
|
|
|
|
|
|
if p is None:
|
2020-09-29 04:38:14 -05:00
|
|
|
raise LookupError(PROCESS_NOT_FOUND)
|
2018-10-22 02:05:21 -05:00
|
|
|
|
|
|
|
try:
|
|
|
|
process = psutil.Process(p.utility_pid)
|
|
|
|
process.terminate()
|
2018-10-25 06:33:34 -05:00
|
|
|
# Update the process state to "Terminated"
|
|
|
|
p.process_state = PROCESS_TERMINATED
|
|
|
|
db.session.commit()
|
2018-10-22 02:05:21 -05:00
|
|
|
except psutil.Error as e:
|
|
|
|
current_app.logger.warning(
|
|
|
|
_("Unable to kill the background process '{0}'").format(
|
|
|
|
p.utility_pid)
|
|
|
|
)
|
|
|
|
current_app.logger.exception(e)
|