Add showTerminal button to logs view

This commit is contained in:
Johannes Zellner
2018-01-16 16:24:32 +01:00
parent ee485d8b2a
commit 98aa785ad0
4 changed files with 585 additions and 1 deletions
+6
View File
@@ -36,6 +36,12 @@ app.controller('LogsController', ['$scope', '$timeout', '$location', 'Client', f
logViewer.empty();
};
$scope.showTerminal = function () {
if (!$scope.selected) return;
window.open('/terminal.html?id=' + $scope.selected.value, 'Cloudron Terminal', 'width=1024,height=800');
};
function showLogs() {
if (!$scope.selected) return;
+406
View File
@@ -0,0 +1,406 @@
'use strict';
/* global Terminal */
// create main application module
var app = angular.module('Application', ['angular-md5', 'ui-notification']);
app.controller('TerminalController', ['$scope', '$timeout', '$location', 'Client', function ($scope, $timeout, $location, Client) {
var search = decodeURIComponent(window.location.search).slice(1).split('&').map(function (item) { return item.split('='); }).reduce(function (o, k) { o[k[0]] = k[1]; return o; }, {});
$scope.config = Client.getConfig();
$scope.user = Client.getUserInfo();
$scope.apps = [];
$scope.selected = '';
$scope.terminal = null;
$scope.terminalSocket = null;
$scope.restartAppBusy = false;
$scope.appBusy = false;
$scope.selectedAppInfo = null;
$scope.downloadFile = {
error: '',
filePath: '',
busy: false,
downloadUrl: function () {
if (!$scope.downloadFile.filePath) return '';
var filePath = $scope.downloadFile.filePath.replace(/\/*\//g, '/');
return Client.apiOrigin + '/api/v1/apps/' + $scope.selected.value + '/download?file=' + filePath + '&access_token=' + Client.getToken();
},
show: function () {
$scope.downloadFile.busy = false;
$scope.downloadFile.error = '';
$scope.downloadFile.filePath = '';
$('#downloadFileModal').modal('show');
},
submit: function () {
$scope.downloadFile.busy = true;
Client.checkDownloadableFile($scope.selected.value, $scope.downloadFile.filePath, function (error) {
$scope.downloadFile.busy = false;
if (error) {
$scope.downloadFile.error = 'The requested file does not exist.';
return;
}
// we have to click the link to make the browser do the download
// don't know how to prevent the browsers
$('#fileDownloadLink')[0].click();
$('#downloadFileModal').modal('hide');
});
}
};
$scope.uploadProgress = {
busy: false,
total: 0,
current: 0,
show: function () {
$scope.uploadProgress.total = 0;
$scope.uploadProgress.current = 0;
$('#uploadProgressModal').modal('show');
},
hide: function () {
$('#uploadProgressModal').modal('hide');
}
};
$scope.uploadFile = function () {
var fileUpload = document.querySelector('#fileUpload');
fileUpload.onchange = function (e) {
if (e.target.files.length === 0) return;
$scope.uploadProgress.busy = true;
$scope.uploadProgress.show();
Client.uploadFile($scope.selected.value, e.target.files[0], function progress(e) {
$scope.uploadProgress.total = e.total;
$scope.uploadProgress.current = e.loaded;
}, function (error) {
if (error) console.error(error);
$scope.uploadProgress.busy = false;
$scope.uploadProgress.hide();
});
};
fileUpload.click();
};
$scope.populateDropdown = function () {
Client.getInstalledApps().forEach(function (app) {
$scope.apps.push({
type: 'app',
value: app.id,
name: app.fqdn + ' (' + app.manifest.title + ')',
addons: app.manifest.addons
});
});
// $scope.selected = $scope.apps[0];
};
$scope.usesAddon = function (addon) {
if (!$scope.selected || !$scope.selected.addons) return false;
return !!Object.keys($scope.selected.addons).find(function (a) { return a === addon; });
};
function reset() {
if ($scope.terminal) {
$scope.terminal.destroy();
$scope.terminal = null;
}
if ($scope.terminalSocket) {
$scope.terminalSocket = null;
}
$scope.selectedAppInfo = null;
}
$scope.restartApp = function () {
$scope.restartAppBusy = true;
var appId = $scope.selected.value;
function waitUntilStopped(callback) {
Client.refreshInstalledApps(function (error) {
if (error) return callback(error);
Client.getApp(appId, function (error, result) {
if (error) return callback(error);
if (result.runState === 'stopped') return callback();
setTimeout(waitUntilStopped.bind(null, callback), 2000);
});
});
}
Client.stopApp(appId, function (error) {
if (error) return console.error('Failed to stop app.', error);
waitUntilStopped(function (error) {
if (error) return console.error('Failed to get app status.', error);
Client.startApp(appId, function (error) {
if (error) console.error('Failed to start app.', error);
$scope.restartAppBusy = false;
});
});
});
};
$scope.repairApp = function () {
$('#repairAppModal').modal('show');
};
$scope.repairAppBegin = function () {
$scope.appBusy = true;
function waitUntilInRepairState() {
Client.refreshInstalledApps(function (error) {
if (error) return console.error('Failed to refresh app status.', error);
Client.getApp($scope.selected.value, function (error, result) {
if (error) return console.error('Failed to get app status.', error);
if (result.installationState === 'installed') $scope.appBusy = false;
else setTimeout(waitUntilInRepairState, 2000);
});
});
}
Client.debugApp($scope.selected.value, true, function (error) {
if (error) return console.error(error);
Client.refreshInstalledApps(function (error) {
if (error) console.error(error);
$('#repairAppModal').modal('hide');
waitUntilInRepairState();
});
});
};
$scope.repairAppDone = function () {
$scope.appBusy = true;
function waitUntilInNormalState() {
Client.refreshInstalledApps(function (error) {
if (error) return console.error('Failed to refresh app status.', error);
Client.getApp($scope.selected.value, function (error, result) {
if (error) return console.error('Failed to get app status.', error);
if (result.installationState === 'installed') $scope.appBusy = false;
else setTimeout(waitUntilInNormalState, 2000);
});
});
}
Client.debugApp($scope.selected.value, false, function (error) {
if (error) return console.error(error);
Client.refreshInstalledApps(function (error) {
if (error) console.error(error);
waitUntilInNormalState();
});
});
};
function showTerminal(retry) {
reset();
if (!$scope.selected) return;
var appId = $scope.selected.value;
Client.getApp(appId, function (error, result) {
if (error) return console.error(error);
// we expect this to be called _after_ a reconfigure was issued
if (result.installationState === 'pending_configure') {
$scope.appBusy = true;
} else if (result.installationState === 'installed') {
$scope.appBusy = false;
}
$scope.selectedAppInfo = result;
$scope.terminal = new Terminal();
$scope.terminal.open(document.querySelector('#terminalContainer'));
$scope.terminal.fit();
try {
// websocket cannot use relative urls
var url = Client.apiOrigin.replace('https', 'wss') + '/api/v1/apps/' + $scope.selected.value + '/execws?tty=true&rows=' + $scope.terminal.rows + '&columns=' + $scope.terminal.cols + '&access_token=' + Client.getToken();
$scope.terminalSocket = new WebSocket(url);
$scope.terminal.attach($scope.terminalSocket);
$scope.terminalSocket.onclose = function () {
// retry in one second
$scope.terminalReconnectTimeout = setTimeout(function () {
showTerminal(true);
}, 1000);
};
// Let the browser handle paste
$scope.terminal.attachCustomKeyEventHandler(function (e) {
if (e.key === 'v' && (e.ctrlKey || e.metaKey)) return false;
});
} catch (e) {
console.error(e);
}
if (retry) $scope.terminal.writeln('Reconnecting...');
else $scope.terminal.writeln('Connecting...');
});
}
$scope.terminalInject = function (addon) {
if (!$scope.terminalSocket) return;
var cmd;
if (addon === 'mysql') cmd = 'mysql --user=${MYSQL_USERNAME} --password=${MYSQL_PASSWORD} --host=${MYSQL_HOST} ${MYSQL_DATABASE}';
else if (addon === 'postgresql') cmd = 'PGPASSWORD=${POSTGRESQL_PASSWORD} psql -h ${POSTGRESQL_HOST} -p ${POSTGRESQL_PORT} -U ${POSTGRESQL_USERNAME} -d ${POSTGRESQL_DATABASE}';
else if (addon === 'mongodb') cmd = 'mongo -u "${MONGODB_USERNAME}" -p "${MONGODB_PASSWORD}" ${MONGODB_HOST}:${MONGODB_PORT}/${MONGODB_DATABASE}';
else if (addon === 'redis') cmd = 'redis-cli -h "${REDIS_HOST}" -p "${REDIS_PORT}" -a "${REDIS_PASSWORD}"';
if (!cmd) return;
cmd += ' ';
$scope.terminalSocket.send(cmd);
$scope.terminal.focus();
};
Client.onReady($scope.populateDropdown);
// Client.onApps(function () {
// console.log('onapps')
// if ($scope.$$destroyed) return;
// if ($scope.selected.type !== 'app') return $scope.appBusy = false;
// var appId = $scope.selected.value;
// Client.getApp(appId, function (error, result) {
// if (error) return console.error(error);
// // we expect this to be called _after_ a reconfigure was issued
// if (result.installationState === 'pending_configure') {
// $scope.appBusy = true;
// } else if (result.installationState === 'installed') {
// $scope.appBusy = false;
// }
// $scope.selectedAppInfo = result;
// });
// });
// terminal right click handling
$scope.terminalClear = function () {
if (!$scope.terminal) return;
$scope.terminal.clear();
$scope.terminal.focus();
};
$scope.terminalCopy = function () {
if (!$scope.terminal) return;
// execCommand('copy') would copy any selection from the page, so do this only if terminal has a selection
if (!$scope.terminal.getSelection()) return;
document.execCommand('copy');
$scope.terminal.focus();
};
$('.contextMenuBackdrop').on('click', function (e) {
$('#terminalContextMenu').hide();
$('.contextMenuBackdrop').hide();
$scope.terminal.focus();
});
$('#terminalContainer').on('contextmenu', function (e) {
if (!$scope.terminal) return true;
e.preventDefault();
$('.contextMenuBackdrop').show();
$('#terminalContextMenu').css({
display: 'block',
left: e.pageX,
top: e.pageY
});
return false;
});
Client.getStatus(function (error, status) {
if (error) return $scope.error(error);
if (!status.activated) {
console.log('Not activated yet, closing or redirecting', status);
window.close();
window.location.href = '/';
return;
}
Client.refreshConfig(function (error) {
if (error) return $scope.error(error);
// check version and force reload if needed
if (!localStorage.version) {
localStorage.version = Client.getConfig().version;
} else if (localStorage.version !== Client.getConfig().version) {
localStorage.version = Client.getConfig().version;
window.location.reload(true);
}
Client.refreshInstalledApps(function (error) {
if (error) return $scope.error(error);
Client.getInstalledApps().forEach(function (app) {
$scope.apps.push({
type: 'app',
value: app.id,
name: app.fqdn + ' (' + app.manifest.title + ')',
addons: app.manifest.addons
});
});
// activate pre-selected log from query otherwise choose the first one
$scope.selected = $scope.apps.find(function (e) { return e.value === search.id; });
if (!$scope.selected) $scope.selected = $scope.apps[0];
// now mark the Client to be ready
Client.setReady();
$scope.initialized = true;
showTerminal();
});
});
});
// setup all the dialog focus handling
['downloadFileModal'].forEach(function (id) {
$('#' + id).on('shown.bs.modal', function () {
$(this).find("[autofocus]:first").focus();
});
});
}]);
+2 -1
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height" />
<!-- this gets changed once we get the config (because angular has not loaded yet, we see template string for a flash) -->
<title> Cloudron Logs </title>
<title> Logs </title>
<link id="favicon" href="/api/v1/cloudron/avatar" rel="icon" type="image/png">
@@ -54,6 +54,7 @@
<!-- logs actions -->
<div class="pull-right">
<a class="btn btn-primary" ng-click="showTerminal()"><i class="fa fa-terminal"></i> Terminal</a>
<a class="btn btn-primary" ng-click="clear()"><i class="fa fa-trash"></i> Clear View</a>
<a class="btn btn-primary" ng-href="{{ selected.url }}&format=short&lines=800"><i class="fa fa-download"></i> Download Full Logs</a>
</div>
+171
View File
@@ -0,0 +1,171 @@
<!DOCTYPE html>
<html ng-app="Application" ng-controller="TerminalController">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height" />
<!-- this gets changed once we get the config (because angular has not loaded yet, we see template string for a flash) -->
<title> Terminal </title>
<link id="favicon" href="/api/v1/cloudron/avatar" rel="icon" type="image/png">
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="/3rdparty/angular-ui-notification.min.css"/>
<link href="theme.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="3rdparty/css/font-awesome.min.css" rel="stylesheet" rel="stylesheet" type="text/css">
<!-- jQuery-->
<script src="3rdparty/js/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="3rdparty/js/bootstrap.min.js"></script>
<!-- Angularjs scripts -->
<script src="3rdparty/js/angular.min.js"></script>
<script src="3rdparty/js/angular-loader.min.js"></script>
<script src="3rdparty/js/angular-animate.min.js"></script>
<script src="3rdparty/js/angular-base64.min.js"></script>
<script src="3rdparty/js/angular-md5.min.js"></script>
<script src="3rdparty/js/angular-sanitize.min.js"></script>
<script src="3rdparty/js/angular-ui-notification.min.js"></script>
<!-- Angular directives for bootstrap https://angular-ui.github.io/bootstrap/ -->
<script src="3rdparty/js/ui-bootstrap-tpls-1.3.3.min.js"></script>
<!-- Clipboard handling -->
<script src="3rdparty/js/clipboard.min.js"></script>
<!-- xterm -->
<link href="3rdparty/xterm/xterm.css" rel="stylesheet">
<script src="3rdparty/xterm/xterm.js"></script>
<script src="3rdparty/xterm/addons/attach/attach.js"></script>
<script src="3rdparty/xterm/addons/fit/fit.js"></script>
<!-- Main Application -->
<script src="js/terminal.js"></script>
</head>
<body>
<!-- Modal download file -->
<div class="modal fade" id="downloadFileModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Download from {{ selected.name }}</h4>
</div>
<div class="modal-body">
<form name="downloadFileForm" ng-submit="downloadFile.submit()">
<div class="form-group" ng-class="{ 'has-error': downloadFileForm.filePath.$dirty && downloadFile.error }">
<label class="control-label" for="inputDownloadFilePath">Path to file or directory</label>
<div class="control-label" ng-show="{ 'has-error': downloadFileForm.filePath.$dirty && downloadFile.error }">
<small>{{ downloadFile.error }}</small>
</div>
<input type="text" class="form-control" name="filePath" ng-model="downloadFile.filePath" required autofocus>
</div>
<input id="inputDownloadFilePath" class="ng-hide" type="submit" ng-disabled="!downloadFile.filePath"/>
</form>
</div>
<div class="modal-footer">
<a id="fileDownloadLink" class="" ng-href="{{ downloadFile.downloadUrl() }}" target="_blank"></a>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success" ng-click="downloadFile.submit()" ng-disabled="!downloadFile.filePath"><i class="fa fa-circle-o-notch fa-spin" ng-show="downloadFile.busy"></i> Download</button>
</div>
</div>
</div>
</div>
<!-- Modal upload progress -->
<div class="modal fade" id="uploadProgressModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Uploading file to {{ selected.name }}</h4>
</div>
<div class="modal-body">
<span><b>{{ (uploadProgress.current/1000/1000).toFixed(2) }}MB</b> (total {{ (uploadProgress.total/1000/1000).toFixed(2) }}MB)</span>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-success" role="progressbar" style="width: {{ 100*(uploadProgress.current/uploadProgress.total) }}%"></div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<!-- Modal repair info -->
<div class="modal fade" id="repairAppModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Repair app {{ selected.name }} ?</h4>
</div>
<div class="modal-body">
<p>This will restart the app in repair mode. The app will start in a paused state and can be used to fix broken plugins or database content.</p>
<p class="text-danger text-bold">The app will not be reachable in repair mode!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger" ng-click="repairAppBegin()">Repair</button>
</div>
</div>
</div>
</div>
<div class="animateMe ng-hide layout-root terminal-view" ng-show="initialized">
<div class="terminal-controls">
<h3 style="display: inline-block;">{{ selected.name }}</h3>
<input type="file" id="fileUpload" class="hide"/>
<div class="pull-right">
<!-- addon actions -->
<a class="btn btn-success" ng-click="terminalInject('mysql')" ng-show="usesAddon('mysql')">MySQL</a>
<a class="btn btn-success" ng-click="terminalInject('postgresql')" ng-show="usesAddon('postgresql')">Postgres</a>
<a class="btn btn-success" ng-click="terminalInject('mongodb')" ng-show="usesAddon('mongodb')">MongoDB</a>
<a class="btn btn-success" ng-click="terminalInject('redis')" ng-show="usesAddon('redis')">Redis</a>
<!-- terminal actions -->
<a class="btn btn-primary" ng-click="restartApp()" ng-show="selected.type === 'app'" ng-disabled="restartAppBusy"><i class="fa fa-refresh" ng-class="{ 'fa-spin': restartAppBusy }"></i> Restart</a>
<a class="btn btn-primary" ng-click="uploadFile()" ng-show="selected.type === 'app' && !uploadProgress.busy"><i class="fa fa-upload"></i> Upload to /tmp</a>
<a class="btn btn-primary" ng-click="uploadProgress.show()" ng-show="uploadProgress.busy"><i class="fa fa-circle-o-notch fa-spin"></i> Uploading...</a>
<a class="btn btn-primary" ng-click="downloadFile.show()" ng-show="selected.type === 'app'"><i class="fa fa-download"></i> Download</a>
<a class="btn btn-primary" ng-click="repairApp()" ng-show="selected.type === 'app' && !selectedAppInfo.debugMode && !appBusy"><i class="fa fa-wrench"></i> Repair</a>
<a class="btn btn-danger" ng-click="repairAppDone()" ng-show="selectedAppInfo.debugMode && !appBusy"><i class="fa fa-wrench"></i> Repair Done</a>
</div>
</div>
<div class="terminal-container" id="terminalContainer" ng-hide="appBusy"></div>
<div class="terminal-container placeholder" ng-show="appBusy">
<h4>&nbsp;
<span ng-show="selectedAppInfo.installationState === 'pending_configure' && selectedAppInfo.debugMode">Restarting app for repair...</span>
<span ng-show="selectedAppInfo.installationState === 'pending_configure' && !selectedAppInfo.debugMode ">App is being reconfigured...</span>
<span ng-show="selectedAppInfo.installationState === 'installed' && !selectedAppInfo.debugMode">Waiting for app to start...</span>
<span ng-show="selectedAppInfo.installationState === 'pending_installed'">App is being installed...</span>
</h4>
<div class="progress" ng-show="appBusy" style="width: 80%">
<div class="progress-bar progress-bar-striped active" role="progressbar" style="width: 100%"></div>
</div>
</div>
<div class="contextMenuBackdrop">
<ul class="dropdown-menu" id="terminalContextMenu" style="position: absolute; display:none;">
<li><a href="" ng-click="terminalCopy()">Copy</a></li>
<li class="disabled"><a>For Paste use Ctrl+v</a></li>
<li role="separator" class="divider"></li>
<li><a href="" ng-click="terminalClear()">Clear</a></li>
</ul>
</div>
</div>
</body>
</html>