Compare commits
105 Commits
bg-create-
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| bb7dbcbf82 | |||
| 41e82efd26 | |||
| f19eab4c55 | |||
| 01ad13b5b4 | |||
| b7242ba6dd | |||
|
|
a883084bba | ||
|
|
0de0cc484d | ||
|
|
1625126924 | ||
|
|
ef90db025c | ||
|
|
1650a61831 | ||
|
|
cb96c04c21 | ||
|
|
610b04a738 | ||
|
|
0a05fa7abc | ||
|
|
c769ae63a2 | ||
|
|
f4fb979c63 | ||
|
|
c9590c8cfa | ||
|
|
d9b25cdb18 | ||
|
|
faad50ff4c | ||
|
|
c8371a8ea7 | ||
|
|
1708e29faf | ||
|
|
5b92439356 | ||
|
|
d86a856997 | ||
|
|
2a31f8c8d7 | ||
|
|
f2734c86ca | ||
|
|
73cf107029 | ||
|
|
92fbb9581e | ||
|
|
9ab5738ae3 | ||
|
|
ca61354cfe | ||
|
|
db1dbdb42f | ||
|
|
004550f6e6 | ||
|
|
205f61ae47 | ||
|
|
a16bb95c4e | ||
|
|
57dfd9c01b | ||
|
|
f4561c2fe2 | ||
|
|
1ee48d0274 | ||
|
|
384d544bf2 | ||
|
|
df09caaf46 | ||
|
|
e59250d1fd | ||
|
|
e0176bbcbc | ||
|
|
53cc80fc7f | ||
|
|
47d1196dde | ||
|
|
267ff9e7f1 | ||
|
|
0cecf26569 | ||
|
|
ee0e8066d3 | ||
|
|
6edb458910 | ||
|
|
5ed09d1a98 | ||
|
|
ad8fec6a1a | ||
|
|
c30e6a9d4f | ||
|
|
b1ca08fd0c | ||
|
|
d98745431b | ||
|
|
6b69e26de3 | ||
|
|
a8286e7742 | ||
|
|
58c6fe7c35 | ||
|
|
74a11c7be3 | ||
|
|
1f3217f598 | ||
|
|
52f4bfe9e2 | ||
|
|
a88000281f | ||
|
|
b33734bab6 | ||
|
|
6c7019ccb7 | ||
|
|
bad3850fcc | ||
|
|
9b92793b89 | ||
|
|
6569da0242 | ||
|
|
33d6462875 | ||
|
|
19690e7847 | ||
|
|
5aa90abc2d | ||
|
|
ba7de90a50 | ||
|
|
7ceadc8599 | ||
|
|
f077c337ec | ||
|
|
eb603f9f31 | ||
|
|
385cdd6f0c | ||
|
|
303fb03f1f | ||
|
|
3e3e4503eb | ||
|
|
70363a9109 | ||
|
|
59310cbb09 | ||
|
|
d88136c569 | ||
|
|
0d44fb704b | ||
|
|
bf2430f1fc | ||
|
|
2211ebcefb | ||
|
|
440ec5553e | ||
|
|
17c14b1192 | ||
|
|
8c60406bb5 | ||
|
|
9db18c95a5 | ||
|
|
985bbf27c9 | ||
|
|
f8cb5e36af | ||
|
|
1bcb370ca1 | ||
|
|
e3c278e708 | ||
|
|
54896fb157 | ||
|
|
fec359afac | ||
|
|
97f5691c87 | ||
|
|
9807b51519 | ||
|
|
b8125e396a | ||
|
|
73afa1a8d7 | ||
|
|
942678de38 | ||
|
|
3834c37013 | ||
|
|
a425412bdd | ||
|
|
c004d299c1 | ||
|
|
5ab45c1031 | ||
|
|
0bd99a3edc | ||
|
|
3592ffda52 | ||
|
|
5b5fd2f5df | ||
|
|
b18c9854b6 | ||
|
|
2b2fcca39c | ||
|
|
9e82ab0890 | ||
|
|
e3da458b37 | ||
|
|
8fa4232148 |
@@ -8,7 +8,7 @@
|
|||||||
"prettier/standard"
|
"prettier/standard"
|
||||||
],
|
],
|
||||||
"parserOptions": {
|
"parserOptions": {
|
||||||
"ecmaVersion": 2017
|
"ecmaVersion": 2018
|
||||||
},
|
},
|
||||||
"plugins": [
|
"plugins": [
|
||||||
"mocha",
|
"mocha",
|
||||||
|
|||||||
23
.github/dependabot.yml
vendored
Normal file
23
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: "npm"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "daily"
|
||||||
|
|
||||||
|
pull-request-branch-name:
|
||||||
|
# Separate sections of the branch name with a hyphen
|
||||||
|
# Docker images use the branch name and do not support slashes in tags
|
||||||
|
# https://github.com/overleaf/google-ops/issues/822
|
||||||
|
# https://docs.github.com/en/github/administering-a-repository/configuration-options-for-dependency-updates#pull-request-branch-nameseparator
|
||||||
|
separator: "-"
|
||||||
|
|
||||||
|
# Block informal upgrades -- security upgrades use a separate queue.
|
||||||
|
# https://docs.github.com/en/github/administering-a-repository/configuration-options-for-dependency-updates#open-pull-requests-limit
|
||||||
|
open-pull-requests-limit: 0
|
||||||
|
|
||||||
|
# currently assign team-magma to all dependabot PRs - this may change in
|
||||||
|
# future if we reorganise teams
|
||||||
|
labels:
|
||||||
|
- "dependencies"
|
||||||
|
- "Team-Magma"
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -11,3 +11,6 @@ db.sqlite-wal
|
|||||||
db.sqlite-shm
|
db.sqlite-shm
|
||||||
config/*
|
config/*
|
||||||
npm-debug.log
|
npm-debug.log
|
||||||
|
|
||||||
|
# managed by dev-environment$ bin/update_build_scripts
|
||||||
|
.npmrc
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
# Instead run bin/update_build_scripts from
|
# Instead run bin/update_build_scripts from
|
||||||
# https://github.com/sharelatex/sharelatex-dev-environment
|
# https://github.com/sharelatex/sharelatex-dev-environment
|
||||||
|
|
||||||
FROM node:10.19.0 as base
|
FROM node:10.22.1 as base
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY install_deps.sh /app
|
COPY install_deps.sh /app
|
||||||
@@ -15,12 +15,10 @@ FROM base as app
|
|||||||
#wildcard as some files may not be in all repos
|
#wildcard as some files may not be in all repos
|
||||||
COPY package*.json npm-shrink*.json /app/
|
COPY package*.json npm-shrink*.json /app/
|
||||||
|
|
||||||
RUN npm install --quiet
|
RUN npm ci --quiet
|
||||||
|
|
||||||
COPY . /app
|
COPY . /app
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
FROM base
|
FROM base
|
||||||
|
|
||||||
COPY --from=app /app /app
|
COPY --from=app /app /app
|
||||||
|
|||||||
131
Jenkinsfile
vendored
131
Jenkinsfile
vendored
@@ -1,131 +0,0 @@
|
|||||||
String cron_string = BRANCH_NAME == "master" ? "@daily" : ""
|
|
||||||
|
|
||||||
pipeline {
|
|
||||||
agent any
|
|
||||||
|
|
||||||
environment {
|
|
||||||
GIT_PROJECT = "clsi"
|
|
||||||
JENKINS_WORKFLOW = "clsi-sharelatex"
|
|
||||||
TARGET_URL = "${env.JENKINS_URL}blue/organizations/jenkins/${JENKINS_WORKFLOW}/detail/$BRANCH_NAME/$BUILD_NUMBER/pipeline"
|
|
||||||
GIT_API_URL = "https://api.github.com/repos/overleaf/${GIT_PROJECT}/statuses/$GIT_COMMIT"
|
|
||||||
}
|
|
||||||
|
|
||||||
triggers {
|
|
||||||
pollSCM('* * * * *')
|
|
||||||
cron(cron_string)
|
|
||||||
}
|
|
||||||
|
|
||||||
stages {
|
|
||||||
|
|
||||||
stage('Install') {
|
|
||||||
steps {
|
|
||||||
withCredentials([usernamePassword(credentialsId: 'GITHUB_INTEGRATION', usernameVariable: 'GH_AUTH_USERNAME', passwordVariable: 'GH_AUTH_PASSWORD')]) {
|
|
||||||
sh "curl $GIT_API_URL \
|
|
||||||
--data '{ \
|
|
||||||
\"state\" : \"pending\", \
|
|
||||||
\"target_url\": \"$TARGET_URL\", \
|
|
||||||
\"description\": \"Your build is underway\", \
|
|
||||||
\"context\": \"ci/jenkins\" }' \
|
|
||||||
-u $GH_AUTH_USERNAME:$GH_AUTH_PASSWORD"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Build') {
|
|
||||||
steps {
|
|
||||||
sh 'make build'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Linting') {
|
|
||||||
steps {
|
|
||||||
sh 'DOCKER_COMPOSE_FLAGS="-f docker-compose.ci.yml" make format'
|
|
||||||
sh 'DOCKER_COMPOSE_FLAGS="-f docker-compose.ci.yml" make lint'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Unit Tests') {
|
|
||||||
steps {
|
|
||||||
sh 'DOCKER_COMPOSE_FLAGS="-f docker-compose.ci.yml" make test_unit'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Acceptance Tests') {
|
|
||||||
steps {
|
|
||||||
sh 'DOCKER_COMPOSE_FLAGS="-f docker-compose.ci.yml" make test_acceptance'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Package and docker push') {
|
|
||||||
steps {
|
|
||||||
sh 'echo ${BUILD_NUMBER} > build_number.txt'
|
|
||||||
sh 'touch build.tar.gz' // Avoid tar warning about files changing during read
|
|
||||||
sh 'DOCKER_COMPOSE_FLAGS="-f docker-compose.ci.yml" make tar'
|
|
||||||
|
|
||||||
withCredentials([file(credentialsId: 'gcr.io_overleaf-ops', variable: 'DOCKER_REPO_KEY_PATH')]) {
|
|
||||||
sh 'docker login -u _json_key --password-stdin https://gcr.io/overleaf-ops < ${DOCKER_REPO_KEY_PATH}'
|
|
||||||
}
|
|
||||||
sh 'DOCKER_REPO=gcr.io/overleaf-ops make publish'
|
|
||||||
sh 'docker logout https://gcr.io/overleaf-ops'
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Publish to s3') {
|
|
||||||
steps {
|
|
||||||
sh 'echo ${BRANCH_NAME}-${BUILD_NUMBER} > build_number.txt'
|
|
||||||
withAWS(credentials:'S3_CI_BUILDS_AWS_KEYS', region:"${S3_REGION_BUILD_ARTEFACTS}") {
|
|
||||||
s3Upload(file:'build.tar.gz', bucket:"${S3_BUCKET_BUILD_ARTEFACTS}", path:"${JOB_NAME}/${BUILD_NUMBER}.tar.gz")
|
|
||||||
}
|
|
||||||
withAWS(credentials:'S3_CI_BUILDS_AWS_KEYS', region:"${S3_REGION_BUILD_ARTEFACTS}") {
|
|
||||||
// The deployment process uses this file to figure out the latest build
|
|
||||||
s3Upload(file:'build_number.txt', bucket:"${S3_BUCKET_BUILD_ARTEFACTS}", path:"${JOB_NAME}/latest")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
post {
|
|
||||||
always {
|
|
||||||
sh 'DOCKER_COMPOSE_FLAGS="-f docker-compose.ci.yml" make test_clean'
|
|
||||||
sh 'make clean'
|
|
||||||
}
|
|
||||||
|
|
||||||
success {
|
|
||||||
withCredentials([usernamePassword(credentialsId: 'GITHUB_INTEGRATION', usernameVariable: 'GH_AUTH_USERNAME', passwordVariable: 'GH_AUTH_PASSWORD')]) {
|
|
||||||
sh "curl $GIT_API_URL \
|
|
||||||
--data '{ \
|
|
||||||
\"state\" : \"success\", \
|
|
||||||
\"target_url\": \"$TARGET_URL\", \
|
|
||||||
\"description\": \"Your build succeeded!\", \
|
|
||||||
\"context\": \"ci/jenkins\" }' \
|
|
||||||
-u $GH_AUTH_USERNAME:$GH_AUTH_PASSWORD"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
failure {
|
|
||||||
mail(from: "${EMAIL_ALERT_FROM}",
|
|
||||||
to: "${EMAIL_ALERT_TO}",
|
|
||||||
subject: "Jenkins build failed: ${JOB_NAME}:${BUILD_NUMBER}",
|
|
||||||
body: "Build: ${BUILD_URL}")
|
|
||||||
withCredentials([usernamePassword(credentialsId: 'GITHUB_INTEGRATION', usernameVariable: 'GH_AUTH_USERNAME', passwordVariable: 'GH_AUTH_PASSWORD')]) {
|
|
||||||
sh "curl $GIT_API_URL \
|
|
||||||
--data '{ \
|
|
||||||
\"state\" : \"failure\", \
|
|
||||||
\"target_url\": \"$TARGET_URL\", \
|
|
||||||
\"description\": \"Your build failed\", \
|
|
||||||
\"context\": \"ci/jenkins\" }' \
|
|
||||||
-u $GH_AUTH_USERNAME:$GH_AUTH_PASSWORD"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The options directive is for configuration that applies to the whole job.
|
|
||||||
options {
|
|
||||||
// we'd like to make sure remove old builds, so we don't fill up our storage!
|
|
||||||
buildDiscarder(logRotator(numToKeepStr:'50'))
|
|
||||||
|
|
||||||
// And we'd really like to be sure that this build doesn't hang forever, so let's time it out after:
|
|
||||||
timeout(time: 30, unit: 'MINUTES')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
6
Makefile
6
Makefile
@@ -25,13 +25,13 @@ clean:
|
|||||||
docker rmi gcr.io/overleaf-ops/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
|
docker rmi gcr.io/overleaf-ops/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
|
||||||
|
|
||||||
format:
|
format:
|
||||||
$(DOCKER_COMPOSE) run --rm test_unit npm run format
|
$(DOCKER_COMPOSE) run --rm test_unit npm run --silent format
|
||||||
|
|
||||||
format_fix:
|
format_fix:
|
||||||
$(DOCKER_COMPOSE) run --rm test_unit npm run format:fix
|
$(DOCKER_COMPOSE) run --rm test_unit npm run --silent format:fix
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
$(DOCKER_COMPOSE) run --rm test_unit npm run lint
|
$(DOCKER_COMPOSE) run --rm test_unit npm run --silent lint
|
||||||
|
|
||||||
test: format lint test_unit test_acceptance
|
test: format lint test_unit test_acceptance
|
||||||
|
|
||||||
|
|||||||
19
README.md
19
README.md
@@ -1,6 +1,8 @@
|
|||||||
overleaf/clsi
|
overleaf/clsi
|
||||||
===============
|
===============
|
||||||
|
|
||||||
|
**Note:** Original repo here: https://github.com/overleaf/clsi
|
||||||
|
|
||||||
A web api for compiling LaTeX documents in the cloud
|
A web api for compiling LaTeX documents in the cloud
|
||||||
|
|
||||||
The Common LaTeX Service Interface (CLSI) provides a RESTful interface to traditional LaTeX tools (or, more generally, any command line tool for composing marked-up documents into a display format such as PDF or HTML). The CLSI listens on the following ports by default:
|
The Common LaTeX Service Interface (CLSI) provides a RESTful interface to traditional LaTeX tools (or, more generally, any command line tool for composing marked-up documents into a display format such as PDF or HTML). The CLSI listens on the following ports by default:
|
||||||
@@ -34,20 +36,21 @@ The CLSI can be installed and set up as part of the entire [Overleaf stack](http
|
|||||||
|
|
||||||
$ git clone git@github.com:overleaf/clsi.git
|
$ git clone git@github.com:overleaf/clsi.git
|
||||||
|
|
||||||
Then install the require npm modules:
|
Then install the require npm modules and run:
|
||||||
|
|
||||||
$ npm install
|
$ npm install
|
||||||
|
$ npm start
|
||||||
|
|
||||||
Then compile the coffee script source files:
|
|
||||||
|
|
||||||
$ grunt install
|
|
||||||
|
|
||||||
Finally, (after configuring your local database - see the Config section), run the CLSI service:
|
|
||||||
|
|
||||||
$ grunt run
|
|
||||||
|
|
||||||
The CLSI should then be running at http://localhost:3013.
|
The CLSI should then be running at http://localhost:3013.
|
||||||
|
|
||||||
|
**Note:** to install texlive-full on ubuntu:
|
||||||
|
$ sudo apt install texlive-full
|
||||||
|
|
||||||
|
Possible REST API clients to test are:
|
||||||
|
* Postman
|
||||||
|
* Insomnia
|
||||||
|
|
||||||
Config
|
Config
|
||||||
------
|
------
|
||||||
|
|
||||||
|
|||||||
137
app.js
137
app.js
@@ -5,7 +5,7 @@
|
|||||||
* DS207: Consider shorter variations of null checks
|
* DS207: Consider shorter variations of null checks
|
||||||
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
|
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
|
||||||
*/
|
*/
|
||||||
let tenMinutes
|
const tenMinutes = 10 * 60 * 1000
|
||||||
const Metrics = require('metrics-sharelatex')
|
const Metrics = require('metrics-sharelatex')
|
||||||
Metrics.initialize('clsi')
|
Metrics.initialize('clsi')
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ if ((Settings.sentry != null ? Settings.sentry.dsn : undefined) != null) {
|
|||||||
logger.initializeErrorReporting(Settings.sentry.dsn)
|
logger.initializeErrorReporting(Settings.sentry.dsn)
|
||||||
}
|
}
|
||||||
|
|
||||||
const smokeTest = require('smoke-test-sharelatex')
|
const smokeTest = require('./test/smoke/js/SmokeTests')
|
||||||
const ContentTypeMapper = require('./app/js/ContentTypeMapper')
|
const ContentTypeMapper = require('./app/js/ContentTypeMapper')
|
||||||
const Errors = require('./app/js/Errors')
|
const Errors = require('./app/js/Errors')
|
||||||
|
|
||||||
@@ -49,31 +49,29 @@ app.use(function(req, res, next) {
|
|||||||
return next()
|
return next()
|
||||||
})
|
})
|
||||||
|
|
||||||
app.param('project_id', function(req, res, next, project_id) {
|
app.param('project_id', function (req, res, next, projectId) {
|
||||||
if (project_id != null ? project_id.match(/^[a-zA-Z0-9_-]+$/) : undefined) {
|
if (projectId != null ? projectId.match(/^[a-zA-Z0-9_-]+$/) : undefined) {
|
||||||
return next()
|
return next()
|
||||||
} else {
|
} else {
|
||||||
return next(new Error('invalid project id'))
|
return next(new Error('invalid project id'))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
app.param('user_id', function(req, res, next, user_id) {
|
app.param('user_id', function (req, res, next, userId) {
|
||||||
if (user_id != null ? user_id.match(/^[0-9a-f]{24}$/) : undefined) {
|
if (userId != null ? userId.match(/^[0-9a-f]{24}$/) : undefined) {
|
||||||
return next()
|
return next()
|
||||||
} else {
|
} else {
|
||||||
return next(new Error('invalid user id'))
|
return next(new Error('invalid user id'))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
app.param('build_id', function(req, res, next, build_id) {
|
app.param('build_id', function (req, res, next, buildId) {
|
||||||
if (
|
if (
|
||||||
build_id != null
|
buildId != null ? buildId.match(OutputCacheManager.BUILD_REGEX) : undefined
|
||||||
? build_id.match(OutputCacheManager.BUILD_REGEX)
|
|
||||||
: undefined
|
|
||||||
) {
|
) {
|
||||||
return next()
|
return next()
|
||||||
} else {
|
} else {
|
||||||
return next(new Error(`invalid build id ${build_id}`))
|
return next(new Error(`invalid build id ${buildId}`))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -136,17 +134,16 @@ const staticServer = ForbidSymlinks(express.static, Settings.path.compilesDir, {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
app.get('/project/:project_id/user/:user_id/build/:build_id/output/*', function(
|
app.get(
|
||||||
req,
|
'/project/:project_id/user/:user_id/build/:build_id/output/*',
|
||||||
res,
|
function (req, res, next) {
|
||||||
next
|
|
||||||
) {
|
|
||||||
// for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
|
// for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
|
||||||
req.url =
|
req.url =
|
||||||
`/${req.params.project_id}-${req.params.user_id}/` +
|
`/${req.params.project_id}-${req.params.user_id}/` +
|
||||||
OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
|
OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
|
||||||
return staticServer(req, res, next)
|
return staticServer(req, res, next)
|
||||||
})
|
}
|
||||||
|
)
|
||||||
|
|
||||||
app.get('/project/:project_id/build/:build_id/output/*', function (
|
app.get('/project/:project_id/build/:build_id/output/*', function (
|
||||||
req,
|
req,
|
||||||
@@ -192,69 +189,49 @@ app.get('/oops', function(req, res, next) {
|
|||||||
|
|
||||||
app.get('/status', (req, res, next) => res.send('CLSI is alive\n'))
|
app.get('/status', (req, res, next) => res.send('CLSI is alive\n'))
|
||||||
|
|
||||||
const resCacher = {
|
Settings.processTooOld = false
|
||||||
contentType(setContentType) {
|
|
||||||
this.setContentType = setContentType
|
|
||||||
},
|
|
||||||
send(code, body) {
|
|
||||||
this.code = code
|
|
||||||
this.body = body
|
|
||||||
},
|
|
||||||
|
|
||||||
// default the server to be down
|
|
||||||
code: 500,
|
|
||||||
body: {},
|
|
||||||
setContentType: 'application/json'
|
|
||||||
}
|
|
||||||
|
|
||||||
let shutdownTime
|
|
||||||
if (Settings.processLifespanLimitMs) {
|
if (Settings.processLifespanLimitMs) {
|
||||||
Settings.processLifespanLimitMs +=
|
Settings.processLifespanLimitMs +=
|
||||||
Settings.processLifespanLimitMs * (Math.random() / 10)
|
Settings.processLifespanLimitMs * (Math.random() / 10)
|
||||||
shutdownTime = Date.now() + Settings.processLifespanLimitMs
|
logger.info(
|
||||||
logger.info('Lifespan limited to ', shutdownTime)
|
'Lifespan limited to ',
|
||||||
}
|
Date.now() + Settings.processLifespanLimitMs
|
||||||
|
)
|
||||||
|
|
||||||
const checkIfProcessIsTooOld = function(cont) {
|
setTimeout(() => {
|
||||||
if (shutdownTime && shutdownTime < Date.now()) {
|
|
||||||
logger.log('shutting down, process is too old')
|
logger.log('shutting down, process is too old')
|
||||||
resCacher.send = function() {}
|
Settings.processTooOld = true
|
||||||
resCacher.code = 500
|
}, Settings.processLifespanLimitMs)
|
||||||
resCacher.body = { processToOld: true }
|
|
||||||
} else {
|
|
||||||
cont()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Settings.smokeTest) {
|
function runSmokeTest() {
|
||||||
const runSmokeTest = function() {
|
if (Settings.processTooOld) return
|
||||||
checkIfProcessIsTooOld(function() {
|
|
||||||
logger.log('running smoke tests')
|
logger.log('running smoke tests')
|
||||||
smokeTest.run(
|
smokeTest.triggerRun((err) => {
|
||||||
require.resolve(__dirname + '/test/smoke/js/SmokeTests.js')
|
if (err) logger.error({ err }, 'smoke tests failed')
|
||||||
)({}, resCacher)
|
setTimeout(runSmokeTest, 30 * 1000)
|
||||||
return setTimeout(runSmokeTest, 30 * 1000)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
if (Settings.smokeTest) {
|
||||||
runSmokeTest()
|
runSmokeTest()
|
||||||
}
|
}
|
||||||
|
|
||||||
app.get('/health_check', function (req, res) {
|
app.get('/health_check', function (req, res) {
|
||||||
res.contentType(resCacher.setContentType)
|
if (Settings.processTooOld) {
|
||||||
return res.status(resCacher.code).send(resCacher.body)
|
return res.status(500).json({ processTooOld: true })
|
||||||
|
}
|
||||||
|
smokeTest.sendLastResult(res)
|
||||||
})
|
})
|
||||||
|
|
||||||
app.get('/smoke_test_force', (req, res) =>
|
app.get('/smoke_test_force', (req, res) => smokeTest.sendNewResult(res))
|
||||||
smokeTest.run(require.resolve(__dirname + '/test/smoke/js/SmokeTests.js'))(
|
|
||||||
req,
|
|
||||||
res
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
app.use(function (error, req, res, next) {
|
app.use(function (error, req, res, next) {
|
||||||
if (error instanceof Errors.NotFoundError) {
|
if (error instanceof Errors.NotFoundError) {
|
||||||
logger.warn({ err: error, url: req.url }, 'not found error')
|
logger.log({ err: error, url: req.url }, 'not found error')
|
||||||
return res.sendStatus(404)
|
return res.sendStatus(404)
|
||||||
|
} else if (error.code === 'EPIPE') {
|
||||||
|
// inspect container returns EPIPE when shutting down
|
||||||
|
return res.sendStatus(503) // send 503 Unavailable response
|
||||||
} else {
|
} else {
|
||||||
logger.error({ err: error, url: req.url }, 'server error')
|
logger.error({ err: error, url: req.url }, 'server error')
|
||||||
return res.sendStatus((error != null ? error.statusCode : undefined) || 500)
|
return res.sendStatus((error != null ? error.statusCode : undefined) || 500)
|
||||||
@@ -323,46 +300,48 @@ loadHttpServer.post('/state/maint', function(req, res, next) {
|
|||||||
const port =
|
const port =
|
||||||
__guard__(
|
__guard__(
|
||||||
Settings.internal != null ? Settings.internal.clsi : undefined,
|
Settings.internal != null ? Settings.internal.clsi : undefined,
|
||||||
x => x.port
|
(x) => x.port
|
||||||
) || 3013
|
) || 3013
|
||||||
const host =
|
const host =
|
||||||
__guard__(
|
__guard__(
|
||||||
Settings.internal != null ? Settings.internal.clsi : undefined,
|
Settings.internal != null ? Settings.internal.clsi : undefined,
|
||||||
x1 => x1.host
|
(x1) => x1.host
|
||||||
) || 'localhost'
|
) || 'localhost'
|
||||||
|
|
||||||
const load_tcp_port = Settings.internal.load_balancer_agent.load_port
|
const loadTcpPort = Settings.internal.load_balancer_agent.load_port
|
||||||
const load_http_port = Settings.internal.load_balancer_agent.local_port
|
const loadHttpPort = Settings.internal.load_balancer_agent.local_port
|
||||||
|
|
||||||
if (!module.parent) {
|
if (!module.parent) {
|
||||||
// Called directly
|
// Called directly
|
||||||
app.listen(port, host, error =>
|
app.listen(port, host, (error) => {
|
||||||
|
if (error) {
|
||||||
|
logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
|
||||||
|
} else {
|
||||||
logger.info(`CLSI starting up, listening on ${host}:${port}`)
|
logger.info(`CLSI starting up, listening on ${host}:${port}`)
|
||||||
)
|
|
||||||
|
|
||||||
loadTcpServer.listen(load_tcp_port, host, function(error) {
|
|
||||||
if (error != null) {
|
|
||||||
throw error
|
|
||||||
}
|
}
|
||||||
return logger.info(`Load tcp agent listening on load port ${load_tcp_port}`)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
loadHttpServer.listen(load_http_port, host, function(error) {
|
loadTcpServer.listen(loadTcpPort, host, function (error) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
return logger.info(
|
return logger.info(`Load tcp agent listening on load port ${loadTcpPort}`)
|
||||||
`Load http agent listening on load port ${load_http_port}`
|
})
|
||||||
)
|
|
||||||
|
loadHttpServer.listen(loadHttpPort, host, function (error) {
|
||||||
|
if (error != null) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
return logger.info(`Load http agent listening on load port ${loadHttpPort}`)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = app
|
module.exports = app
|
||||||
|
|
||||||
setInterval(
|
setInterval(() => {
|
||||||
() => ProjectPersistenceManager.clearExpiredProjects(),
|
ProjectPersistenceManager.refreshExpiryTimeout()
|
||||||
(tenMinutes = 10 * 60 * 1000)
|
ProjectPersistenceManager.clearExpiredProjects()
|
||||||
)
|
}, tenMinutes)
|
||||||
|
|
||||||
function __guard__(value, transform) {
|
function __guard__(value, transform) {
|
||||||
return typeof value !== 'undefined' && value !== null
|
return typeof value !== 'undefined' && value !== null
|
||||||
|
|||||||
@@ -55,6 +55,10 @@ module.exports = CompileController = {
|
|||||||
} else if (error instanceof Errors.FilesOutOfSyncError) {
|
} else if (error instanceof Errors.FilesOutOfSyncError) {
|
||||||
code = 409 // Http 409 Conflict
|
code = 409 // Http 409 Conflict
|
||||||
status = 'retry'
|
status = 'retry'
|
||||||
|
} else if (error && error.code === 'EPIPE') {
|
||||||
|
// docker returns EPIPE when shutting down
|
||||||
|
code = 503 // send 503 Unavailable response
|
||||||
|
status = 'unavailable'
|
||||||
} else if (error != null ? error.terminated : undefined) {
|
} else if (error != null ? error.terminated : undefined) {
|
||||||
status = 'terminated'
|
status = 'terminated'
|
||||||
} else if (error != null ? error.validate : undefined) {
|
} else if (error != null ? error.validate : undefined) {
|
||||||
@@ -112,7 +116,7 @@ module.exports = CompileController = {
|
|||||||
compile: {
|
compile: {
|
||||||
status,
|
status,
|
||||||
error: (error != null ? error.message : undefined) || error,
|
error: (error != null ? error.message : undefined) || error,
|
||||||
outputFiles: outputFiles.map(file => ({
|
outputFiles: outputFiles.map((file) => ({
|
||||||
url:
|
url:
|
||||||
`${Settings.apis.clsi.url}/project/${request.project_id}` +
|
`${Settings.apis.clsi.url}/project/${request.project_id}` +
|
||||||
(request.user_id != null
|
(request.user_id != null
|
||||||
@@ -193,17 +197,21 @@ module.exports = CompileController = {
|
|||||||
const v = parseFloat(req.query.v)
|
const v = parseFloat(req.query.v)
|
||||||
const { project_id } = req.params
|
const { project_id } = req.params
|
||||||
const { user_id } = req.params
|
const { user_id } = req.params
|
||||||
return CompileManager.syncFromPdf(project_id, user_id, page, h, v, function(
|
return CompileManager.syncFromPdf(
|
||||||
error,
|
project_id,
|
||||||
codePositions
|
user_id,
|
||||||
) {
|
page,
|
||||||
|
h,
|
||||||
|
v,
|
||||||
|
function (error, codePositions) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return next(error)
|
return next(error)
|
||||||
}
|
}
|
||||||
return res.json({
|
return res.json({
|
||||||
code: codePositions
|
code: codePositions
|
||||||
})
|
})
|
||||||
})
|
}
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
wordcount(req, res, next) {
|
wordcount(req, res, next) {
|
||||||
@@ -214,6 +222,15 @@ module.exports = CompileController = {
|
|||||||
const { project_id } = req.params
|
const { project_id } = req.params
|
||||||
const { user_id } = req.params
|
const { user_id } = req.params
|
||||||
const { image } = req.query
|
const { image } = req.query
|
||||||
|
if (
|
||||||
|
image &&
|
||||||
|
Settings.clsi &&
|
||||||
|
Settings.clsi.docker &&
|
||||||
|
Settings.clsi.docker.allowedImages &&
|
||||||
|
!Settings.clsi.docker.allowedImages.includes(image)
|
||||||
|
) {
|
||||||
|
return res.status(400).send('invalid image')
|
||||||
|
}
|
||||||
logger.log({ image, file, project_id }, 'word count request')
|
logger.log({ image, file, project_id }, 'word count request')
|
||||||
|
|
||||||
return CompileManager.wordcount(project_id, user_id, file, image, function (
|
return CompileManager.wordcount(project_id, user_id, file, image, function (
|
||||||
|
|||||||
@@ -53,18 +53,15 @@ module.exports = CompileManager = {
|
|||||||
}
|
}
|
||||||
const compileDir = getCompileDir(request.project_id, request.user_id)
|
const compileDir = getCompileDir(request.project_id, request.user_id)
|
||||||
const lockFile = Path.join(compileDir, '.project-lock')
|
const lockFile = Path.join(compileDir, '.project-lock')
|
||||||
// create local home and tmp directories in the compile dir
|
|
||||||
const homeDir = Path.join(compileDir, '.project-home')
|
|
||||||
const tmpDir = Path.join(compileDir, '.project-tmp')
|
|
||||||
// use a .project-lock file in the compile directory to prevent
|
// use a .project-lock file in the compile directory to prevent
|
||||||
// simultaneous compiles
|
// simultaneous compiles
|
||||||
async.each([compileDir, homeDir, tmpDir], fse.ensureDir, function (error) {
|
return fse.ensureDir(compileDir, function (error) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return LockManager.runWithLock(
|
return LockManager.runWithLock(
|
||||||
lockFile,
|
lockFile,
|
||||||
releaseLock => CompileManager.doCompile(request, releaseLock),
|
(releaseLock) => CompileManager.doCompile(request, releaseLock),
|
||||||
callback
|
callback
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
@@ -123,7 +120,7 @@ module.exports = CompileManager = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const createTikzFileIfRequired = callback =>
|
const createTikzFileIfRequired = (callback) =>
|
||||||
TikzManager.checkMainFile(
|
TikzManager.checkMainFile(
|
||||||
compileDir,
|
compileDir,
|
||||||
request.rootResourcePath,
|
request.rootResourcePath,
|
||||||
@@ -145,6 +142,10 @@ module.exports = CompileManager = {
|
|||||||
)
|
)
|
||||||
// set up environment variables for chktex
|
// set up environment variables for chktex
|
||||||
const env = {}
|
const env = {}
|
||||||
|
if (Settings.texliveOpenoutAny && Settings.texliveOpenoutAny !== '') {
|
||||||
|
// override default texlive openout_any environment variable
|
||||||
|
env.openout_any = Settings.texliveOpenoutAny
|
||||||
|
}
|
||||||
// only run chktex on LaTeX files (not knitr .Rtex files or any others)
|
// only run chktex on LaTeX files (not knitr .Rtex files or any others)
|
||||||
const isLaTeXFile =
|
const isLaTeXFile =
|
||||||
request.rootResourcePath != null
|
request.rootResourcePath != null
|
||||||
@@ -176,9 +177,9 @@ module.exports = CompileManager = {
|
|||||||
request.imageName != null
|
request.imageName != null
|
||||||
? request.imageName.match(/:(.*)/)
|
? request.imageName.match(/:(.*)/)
|
||||||
: undefined,
|
: undefined,
|
||||||
x1 => x1[1]
|
(x1) => x1[1]
|
||||||
),
|
),
|
||||||
x => x.replace(/\./g, '-')
|
(x) => x.replace(/\./g, '-')
|
||||||
) || 'default'
|
) || 'default'
|
||||||
if (!request.project_id.match(/^[0-9a-f]{24}$/)) {
|
if (!request.project_id.match(/^[0-9a-f]{24}$/)) {
|
||||||
tag = 'other'
|
tag = 'other'
|
||||||
@@ -198,15 +199,14 @@ module.exports = CompileManager = {
|
|||||||
timeout: request.timeout,
|
timeout: request.timeout,
|
||||||
image: request.imageName,
|
image: request.imageName,
|
||||||
flags: request.flags,
|
flags: request.flags,
|
||||||
environment: env
|
environment: env,
|
||||||
|
compileGroup: request.compileGroup
|
||||||
},
|
},
|
||||||
function (error, output, stats, timings) {
|
function (error, output, stats, timings) {
|
||||||
// request was for validation only
|
// request was for validation only
|
||||||
let metric_key, metric_value
|
let metric_key, metric_value
|
||||||
if (request.check === 'validate') {
|
if (request.check === 'validate') {
|
||||||
const result = (error != null
|
const result = (error != null ? error.code : undefined)
|
||||||
? error.code
|
|
||||||
: undefined)
|
|
||||||
? 'fail'
|
? 'fail'
|
||||||
: 'pass'
|
: 'pass'
|
||||||
error = new Error('validation')
|
error = new Error('validation')
|
||||||
@@ -337,7 +337,7 @@ module.exports = CompileManager = {
|
|||||||
proc.on('error', callback)
|
proc.on('error', callback)
|
||||||
|
|
||||||
let stderr = ''
|
let stderr = ''
|
||||||
proc.stderr.on('data', chunk => (stderr += chunk.toString()))
|
proc.stderr.setEncoding('utf8').on('data', (chunk) => (stderr += chunk))
|
||||||
|
|
||||||
return proc.on('close', function (code) {
|
return proc.on('close', function (code) {
|
||||||
if (code === 0) {
|
if (code === 0) {
|
||||||
@@ -358,7 +358,7 @@ module.exports = CompileManager = {
|
|||||||
if (err != null) {
|
if (err != null) {
|
||||||
return callback(err)
|
return callback(err)
|
||||||
}
|
}
|
||||||
const allDirs = Array.from(files).map(file => Path.join(root, file))
|
const allDirs = Array.from(files).map((file) => Path.join(root, file))
|
||||||
return callback(null, allDirs)
|
return callback(null, allDirs)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
@@ -429,15 +429,7 @@ module.exports = CompileManager = {
|
|||||||
const compileDir = getCompileDir(project_id, user_id)
|
const compileDir = getCompileDir(project_id, user_id)
|
||||||
const synctex_path = `${base_dir}/output.pdf`
|
const synctex_path = `${base_dir}/output.pdf`
|
||||||
const command = ['code', synctex_path, file_path, line, column]
|
const command = ['code', synctex_path, file_path, line, column]
|
||||||
return fse.ensureDir(compileDir, function(error) {
|
CompileManager._runSynctex(project_id, user_id, command, function (
|
||||||
if (error != null) {
|
|
||||||
logger.err(
|
|
||||||
{ error, project_id, user_id, file_name },
|
|
||||||
'error ensuring dir for sync from code'
|
|
||||||
)
|
|
||||||
return callback(error)
|
|
||||||
}
|
|
||||||
return CompileManager._runSynctex(project_id, user_id, command, function(
|
|
||||||
error,
|
error,
|
||||||
stdout
|
stdout
|
||||||
) {
|
) {
|
||||||
@@ -448,11 +440,7 @@ module.exports = CompileManager = {
|
|||||||
{ project_id, user_id, file_name, line, column, command, stdout },
|
{ project_id, user_id, file_name, line, column, command, stdout },
|
||||||
'synctex code output'
|
'synctex code output'
|
||||||
)
|
)
|
||||||
return callback(
|
return callback(null, CompileManager._parseSynctexFromCodeOutput(stdout))
|
||||||
null,
|
|
||||||
CompileManager._parseSynctexFromCodeOutput(stdout)
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -465,15 +453,7 @@ module.exports = CompileManager = {
|
|||||||
const base_dir = Settings.path.synctexBaseDir(compileName)
|
const base_dir = Settings.path.synctexBaseDir(compileName)
|
||||||
const synctex_path = `${base_dir}/output.pdf`
|
const synctex_path = `${base_dir}/output.pdf`
|
||||||
const command = ['pdf', synctex_path, page, h, v]
|
const command = ['pdf', synctex_path, page, h, v]
|
||||||
return fse.ensureDir(compileDir, function(error) {
|
CompileManager._runSynctex(project_id, user_id, command, function (
|
||||||
if (error != null) {
|
|
||||||
logger.err(
|
|
||||||
{ error, project_id, user_id, file_name },
|
|
||||||
'error ensuring dir for sync to code'
|
|
||||||
)
|
|
||||||
return callback(error)
|
|
||||||
}
|
|
||||||
return CompileManager._runSynctex(project_id, user_id, command, function(
|
|
||||||
error,
|
error,
|
||||||
stdout
|
stdout
|
||||||
) {
|
) {
|
||||||
@@ -489,29 +469,23 @@ module.exports = CompileManager = {
|
|||||||
CompileManager._parseSynctexFromPdfOutput(stdout, base_dir)
|
CompileManager._parseSynctexFromPdfOutput(stdout, base_dir)
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
|
||||||
},
|
},
|
||||||
|
|
||||||
_checkFileExists(path, callback) {
|
_checkFileExists(dir, filename, callback) {
|
||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error) {}
|
callback = function (error) {}
|
||||||
}
|
}
|
||||||
const synctexDir = Path.dirname(path)
|
const file = Path.join(dir, filename)
|
||||||
const synctexFile = Path.join(synctexDir, 'output.synctex.gz')
|
return fs.stat(dir, function (error, stats) {
|
||||||
return fs.stat(synctexDir, function(error, stats) {
|
|
||||||
if ((error != null ? error.code : undefined) === 'ENOENT') {
|
if ((error != null ? error.code : undefined) === 'ENOENT') {
|
||||||
return callback(
|
return callback(new Errors.NotFoundError('no output directory'))
|
||||||
new Errors.NotFoundError('called synctex with no output directory')
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return fs.stat(synctexFile, function(error, stats) {
|
return fs.stat(file, function (error, stats) {
|
||||||
if ((error != null ? error.code : undefined) === 'ENOENT') {
|
if ((error != null ? error.code : undefined) === 'ENOENT') {
|
||||||
return callback(
|
return callback(new Errors.NotFoundError('no output file'))
|
||||||
new Errors.NotFoundError('called synctex with no output file')
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
@@ -535,13 +509,21 @@ module.exports = CompileManager = {
|
|||||||
const directory = getCompileDir(project_id, user_id)
|
const directory = getCompileDir(project_id, user_id)
|
||||||
const timeout = 60 * 1000 // increased to allow for large projects
|
const timeout = 60 * 1000 // increased to allow for large projects
|
||||||
const compileName = getCompileName(project_id, user_id)
|
const compileName = getCompileName(project_id, user_id)
|
||||||
|
const compileGroup = 'synctex'
|
||||||
|
CompileManager._checkFileExists(directory, 'output.synctex.gz', (error) => {
|
||||||
|
if (error) {
|
||||||
|
return callback(error)
|
||||||
|
}
|
||||||
return CommandRunner.run(
|
return CommandRunner.run(
|
||||||
compileName,
|
compileName,
|
||||||
command,
|
command,
|
||||||
directory,
|
directory,
|
||||||
Settings.clsi != null ? Settings.clsi.docker.image : undefined,
|
Settings.clsi && Settings.clsi.docker
|
||||||
|
? Settings.clsi.docker.image
|
||||||
|
: undefined,
|
||||||
timeout,
|
timeout,
|
||||||
{},
|
{},
|
||||||
|
compileGroup,
|
||||||
function (error, output) {
|
function (error, output) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
logger.err(
|
logger.err(
|
||||||
@@ -553,6 +535,7 @@ module.exports = CompileManager = {
|
|||||||
return callback(null, output.stdout)
|
return callback(null, output.stdout)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
_parseSynctexFromCodeOutput(output) {
|
_parseSynctexFromCodeOutput(output) {
|
||||||
@@ -605,6 +588,7 @@ module.exports = CompileManager = {
|
|||||||
const compileDir = getCompileDir(project_id, user_id)
|
const compileDir = getCompileDir(project_id, user_id)
|
||||||
const timeout = 60 * 1000
|
const timeout = 60 * 1000
|
||||||
const compileName = getCompileName(project_id, user_id)
|
const compileName = getCompileName(project_id, user_id)
|
||||||
|
const compileGroup = 'wordcount'
|
||||||
return fse.ensureDir(compileDir, function (error) {
|
return fse.ensureDir(compileDir, function (error) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
logger.err(
|
logger.err(
|
||||||
@@ -620,6 +604,7 @@ module.exports = CompileManager = {
|
|||||||
image,
|
image,
|
||||||
timeout,
|
timeout,
|
||||||
{},
|
{},
|
||||||
|
compileGroup,
|
||||||
function (error) {
|
function (error) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
|
|||||||
@@ -1,21 +1,3 @@
|
|||||||
/* eslint-disable
|
|
||||||
camelcase,
|
|
||||||
handle-callback-err,
|
|
||||||
no-return-assign,
|
|
||||||
no-unused-vars,
|
|
||||||
*/
|
|
||||||
// TODO: This file was created by bulk-decaffeinate.
|
|
||||||
// Fix any style issues and re-enable lint.
|
|
||||||
/*
|
|
||||||
* decaffeinate suggestions:
|
|
||||||
* DS101: Remove unnecessary use of Array.from
|
|
||||||
* DS102: Remove unnecessary code created because of implicit returns
|
|
||||||
* DS103: Rewrite code to no longer use __guard__
|
|
||||||
* DS205: Consider reworking code to avoid use of IIFEs
|
|
||||||
* DS207: Consider shorter variations of null checks
|
|
||||||
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
|
|
||||||
*/
|
|
||||||
let DockerRunner, oneHour
|
|
||||||
const Settings = require('settings-sharelatex')
|
const Settings = require('settings-sharelatex')
|
||||||
const logger = require('logger-sharelatex')
|
const logger = require('logger-sharelatex')
|
||||||
const Docker = require('dockerode')
|
const Docker = require('dockerode')
|
||||||
@@ -25,30 +7,33 @@ const async = require('async')
|
|||||||
const LockManager = require('./DockerLockManager')
|
const LockManager = require('./DockerLockManager')
|
||||||
const fs = require('fs')
|
const fs = require('fs')
|
||||||
const Path = require('path')
|
const Path = require('path')
|
||||||
const _ = require('underscore')
|
const _ = require('lodash')
|
||||||
|
|
||||||
|
const ONE_HOUR_IN_MS = 60 * 60 * 1000
|
||||||
logger.info('using docker runner')
|
logger.info('using docker runner')
|
||||||
|
|
||||||
const usingSiblingContainers = () =>
|
function usingSiblingContainers() {
|
||||||
__guard__(
|
return (
|
||||||
Settings != null ? Settings.path : undefined,
|
Settings != null &&
|
||||||
x => x.sandboxedCompilesHostDir
|
Settings.path != null &&
|
||||||
) != null
|
Settings.path.sandboxedCompilesHostDir != null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
let containerMonitorTimeout
|
let containerMonitorTimeout
|
||||||
let containerMonitorInterval
|
let containerMonitorInterval
|
||||||
|
|
||||||
module.exports = DockerRunner = {
|
const DockerRunner = {
|
||||||
ERR_NOT_DIRECTORY: new Error('not a directory'),
|
run(
|
||||||
ERR_TERMINATED: new Error('terminated'),
|
projectId,
|
||||||
ERR_EXITED: new Error('exited'),
|
command,
|
||||||
ERR_TIMED_OUT: new Error('container timed out'),
|
directory,
|
||||||
|
image,
|
||||||
run(project_id, command, directory, image, timeout, environment, callback) {
|
timeout,
|
||||||
let name
|
environment,
|
||||||
if (callback == null) {
|
compileGroup,
|
||||||
callback = function(error, output) {}
|
callback
|
||||||
}
|
) {
|
||||||
if (usingSiblingContainers()) {
|
if (usingSiblingContainers()) {
|
||||||
const _newPath = Settings.path.sandboxedCompilesHostDir
|
const _newPath = Settings.path.sandboxedCompilesHostDir
|
||||||
logger.log(
|
logger.log(
|
||||||
@@ -65,16 +50,20 @@ module.exports = DockerRunner = {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const volumes = {}
|
const volumes = { [directory]: '/compile' }
|
||||||
volumes[directory] = '/compile'
|
|
||||||
|
|
||||||
command = Array.from(command).map(arg =>
|
command = command.map((arg) =>
|
||||||
__guardMethod__(arg.toString(), 'replace', o =>
|
arg.toString().replace('$COMPILE_DIR', '/compile')
|
||||||
o.replace('$COMPILE_DIR', '/compile')
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
if (image == null) {
|
if (image == null) {
|
||||||
;({ image } = Settings.clsi.docker)
|
image = Settings.clsi.docker.image
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
Settings.clsi.docker.allowedImages &&
|
||||||
|
!Settings.clsi.docker.allowedImages.includes(image)
|
||||||
|
) {
|
||||||
|
return callback(new Error('image not allowed'))
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Settings.texliveImageNameOveride != null) {
|
if (Settings.texliveImageNameOveride != null) {
|
||||||
@@ -87,28 +76,31 @@ module.exports = DockerRunner = {
|
|||||||
image,
|
image,
|
||||||
volumes,
|
volumes,
|
||||||
timeout,
|
timeout,
|
||||||
environment
|
environment,
|
||||||
|
compileGroup
|
||||||
)
|
)
|
||||||
const fingerprint = DockerRunner._fingerprintContainer(options)
|
const fingerprint = DockerRunner._fingerprintContainer(options)
|
||||||
options.name = name = `project-${project_id}-${fingerprint}`
|
const name = `project-${projectId}-${fingerprint}`
|
||||||
|
options.name = name
|
||||||
|
|
||||||
// logOptions = _.clone(options)
|
// logOptions = _.clone(options)
|
||||||
// logOptions?.HostConfig?.SecurityOpt = "secomp used, removed in logging"
|
// logOptions?.HostConfig?.SecurityOpt = "secomp used, removed in logging"
|
||||||
logger.log({ project_id }, 'running docker container')
|
logger.log({ projectId }, 'running docker container')
|
||||||
DockerRunner._runAndWaitForContainer(options, volumes, timeout, function(
|
DockerRunner._runAndWaitForContainer(
|
||||||
error,
|
options,
|
||||||
output
|
volumes,
|
||||||
) {
|
timeout,
|
||||||
|
(error, output) => {
|
||||||
if (error && error.statusCode === 500) {
|
if (error && error.statusCode === 500) {
|
||||||
logger.log(
|
logger.log(
|
||||||
{ err: error, project_id },
|
{ err: error, projectId },
|
||||||
'error running container so destroying and retrying'
|
'error running container so destroying and retrying'
|
||||||
)
|
)
|
||||||
return DockerRunner.destroyContainer(name, null, true, function(error) {
|
DockerRunner.destroyContainer(name, null, true, (error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return DockerRunner._runAndWaitForContainer(
|
DockerRunner._runAndWaitForContainer(
|
||||||
options,
|
options,
|
||||||
volumes,
|
volumes,
|
||||||
timeout,
|
timeout,
|
||||||
@@ -116,121 +108,111 @@ module.exports = DockerRunner = {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
return callback(error, output)
|
callback(error, output)
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// pass back the container name to allow it to be killed
|
||||||
return name
|
return name
|
||||||
}, // pass back the container name to allow it to be killed
|
},
|
||||||
|
|
||||||
kill(container_id, callback) {
|
kill(containerId, callback) {
|
||||||
if (callback == null) {
|
logger.log({ containerId }, 'sending kill signal to container')
|
||||||
callback = function(error) {}
|
const container = dockerode.getContainer(containerId)
|
||||||
}
|
container.kill((error) => {
|
||||||
logger.log({ container_id }, 'sending kill signal to container')
|
|
||||||
const container = dockerode.getContainer(container_id)
|
|
||||||
return container.kill(function(error) {
|
|
||||||
if (
|
if (
|
||||||
error != null &&
|
error != null &&
|
||||||
__guardMethod__(error != null ? error.message : undefined, 'match', o =>
|
error.message != null &&
|
||||||
o.match(/Cannot kill container .* is not running/)
|
error.message.match(/Cannot kill container .* is not running/)
|
||||||
)
|
|
||||||
) {
|
) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
{ err: error, container_id },
|
{ err: error, containerId },
|
||||||
'container not running, continuing'
|
'container not running, continuing'
|
||||||
)
|
)
|
||||||
error = null
|
error = null
|
||||||
}
|
}
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
logger.error({ err: error, container_id }, 'error killing container')
|
logger.error({ err: error, containerId }, 'error killing container')
|
||||||
return callback(error)
|
callback(error)
|
||||||
} else {
|
} else {
|
||||||
return callback()
|
callback()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
_runAndWaitForContainer(options, volumes, timeout, _callback) {
|
_runAndWaitForContainer(options, volumes, timeout, _callback) {
|
||||||
if (_callback == null) {
|
const callback = _.once(_callback)
|
||||||
_callback = function(error, output) {}
|
|
||||||
}
|
|
||||||
const callback = function(...args) {
|
|
||||||
_callback(...Array.from(args || []))
|
|
||||||
// Only call the callback once
|
|
||||||
return (_callback = function() {})
|
|
||||||
}
|
|
||||||
|
|
||||||
const { name } = options
|
const { name } = options
|
||||||
|
|
||||||
let streamEnded = false
|
let streamEnded = false
|
||||||
let containerReturned = false
|
let containerReturned = false
|
||||||
let output = {}
|
let output = {}
|
||||||
|
|
||||||
const callbackIfFinished = function() {
|
function callbackIfFinished() {
|
||||||
if (streamEnded && containerReturned) {
|
if (streamEnded && containerReturned) {
|
||||||
return callback(null, output)
|
callback(null, output)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const attachStreamHandler = function(error, _output) {
|
function attachStreamHandler(error, _output) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
output = _output
|
output = _output
|
||||||
streamEnded = true
|
streamEnded = true
|
||||||
return callbackIfFinished()
|
callbackIfFinished()
|
||||||
}
|
}
|
||||||
|
|
||||||
return DockerRunner.startContainer(
|
DockerRunner.startContainer(
|
||||||
options,
|
options,
|
||||||
volumes,
|
volumes,
|
||||||
attachStreamHandler,
|
attachStreamHandler,
|
||||||
function(error, containerId) {
|
(error, containerId) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
|
|
||||||
return DockerRunner.waitForContainer(name, timeout, function(
|
DockerRunner.waitForContainer(name, timeout, (error, exitCode) => {
|
||||||
error,
|
|
||||||
exitCode
|
|
||||||
) {
|
|
||||||
let err
|
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
if (exitCode === 137) {
|
if (exitCode === 137) {
|
||||||
// exit status from kill -9
|
// exit status from kill -9
|
||||||
err = DockerRunner.ERR_TERMINATED
|
const err = new Error('terminated')
|
||||||
err.terminated = true
|
err.terminated = true
|
||||||
return callback(err)
|
return callback(err)
|
||||||
}
|
}
|
||||||
if (exitCode === 1) {
|
if (exitCode === 1) {
|
||||||
// exit status from chktex
|
// exit status from chktex
|
||||||
err = DockerRunner.ERR_EXITED
|
const err = new Error('exited')
|
||||||
err.code = exitCode
|
err.code = exitCode
|
||||||
return callback(err)
|
return callback(err)
|
||||||
}
|
}
|
||||||
containerReturned = true
|
containerReturned = true
|
||||||
__guard__(
|
if (options != null && options.HostConfig != null) {
|
||||||
options != null ? options.HostConfig : undefined,
|
options.HostConfig.SecurityOpt = null
|
||||||
x => (x.SecurityOpt = null)
|
}
|
||||||
) // small log line
|
logger.log({ exitCode, options }, 'docker container has exited')
|
||||||
logger.log({ err, exitCode, options }, 'docker container has exited')
|
callbackIfFinished()
|
||||||
return callbackIfFinished()
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
_getContainerOptions(command, image, volumes, timeout, environment) {
|
_getContainerOptions(
|
||||||
let m, year
|
command,
|
||||||
let key, value, hostVol, dockerVol
|
image,
|
||||||
|
volumes,
|
||||||
|
timeout,
|
||||||
|
environment,
|
||||||
|
compileGroup
|
||||||
|
) {
|
||||||
const timeoutInSeconds = timeout / 1000
|
const timeoutInSeconds = timeout / 1000
|
||||||
|
|
||||||
const dockerVolumes = {}
|
const dockerVolumes = {}
|
||||||
for (hostVol in volumes) {
|
for (const hostVol in volumes) {
|
||||||
dockerVol = volumes[hostVol]
|
const dockerVol = volumes[hostVol]
|
||||||
dockerVolumes[dockerVol] = {}
|
dockerVolumes[dockerVol] = {}
|
||||||
|
|
||||||
if (volumes[hostVol].slice(-3).indexOf(':r') === -1) {
|
if (volumes[hostVol].slice(-3).indexOf(':r') === -1) {
|
||||||
@@ -241,17 +223,14 @@ module.exports = DockerRunner = {
|
|||||||
// merge settings and environment parameter
|
// merge settings and environment parameter
|
||||||
const env = {}
|
const env = {}
|
||||||
for (const src of [Settings.clsi.docker.env, environment || {}]) {
|
for (const src of [Settings.clsi.docker.env, environment || {}]) {
|
||||||
for (key in src) {
|
for (const key in src) {
|
||||||
value = src[key]
|
const value = src[key]
|
||||||
env[key] = value
|
env[key] = value
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// set the path based on the image year
|
// set the path based on the image year
|
||||||
if ((m = image.match(/:([0-9]+)\.[0-9]+/))) {
|
const match = image.match(/:([0-9]+)\.[0-9]+/)
|
||||||
year = m[1]
|
const year = match ? match[1] : '2014'
|
||||||
} else {
|
|
||||||
year = '2014'
|
|
||||||
}
|
|
||||||
env.PATH = `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/texlive/${year}/bin/x86_64-linux/`
|
env.PATH = `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/texlive/${year}/bin/x86_64-linux/`
|
||||||
const options = {
|
const options = {
|
||||||
Cmd: command,
|
Cmd: command,
|
||||||
@@ -261,23 +240,11 @@ module.exports = DockerRunner = {
|
|||||||
NetworkDisabled: true,
|
NetworkDisabled: true,
|
||||||
Memory: 1024 * 1024 * 1024 * 1024, // 1 Gb
|
Memory: 1024 * 1024 * 1024 * 1024, // 1 Gb
|
||||||
User: Settings.clsi.docker.user,
|
User: Settings.clsi.docker.user,
|
||||||
Env: (() => {
|
Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
|
||||||
const result = []
|
|
||||||
for (key in env) {
|
|
||||||
value = env[key]
|
|
||||||
result.push(`${key}=${value}`)
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
})(), // convert the environment hash to an array
|
|
||||||
HostConfig: {
|
HostConfig: {
|
||||||
Binds: (() => {
|
Binds: Object.entries(volumes).map(
|
||||||
const result1 = []
|
([hostVol, dockerVol]) => `${hostVol}:${dockerVol}`
|
||||||
for (hostVol in volumes) {
|
),
|
||||||
dockerVol = volumes[hostVol]
|
|
||||||
result1.push(`${hostVol}:${dockerVol}`)
|
|
||||||
}
|
|
||||||
return result1
|
|
||||||
})(),
|
|
||||||
LogConfig: { Type: 'none', Config: {} },
|
LogConfig: { Type: 'none', Config: {} },
|
||||||
Ulimits: [
|
Ulimits: [
|
||||||
{
|
{
|
||||||
@@ -291,10 +258,7 @@ module.exports = DockerRunner = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (Settings.path != null && Settings.path.synctexBinHostPath != null) {
|
||||||
(Settings.path != null ? Settings.path.synctexBinHostPath : undefined) !=
|
|
||||||
null
|
|
||||||
) {
|
|
||||||
options.HostConfig.Binds.push(
|
options.HostConfig.Binds.push(
|
||||||
`${Settings.path.synctexBinHostPath}:/opt/synctex:ro`
|
`${Settings.path.synctexBinHostPath}:/opt/synctex:ro`
|
||||||
)
|
)
|
||||||
@@ -310,31 +274,45 @@ module.exports = DockerRunner = {
|
|||||||
options.HostConfig.Runtime = Settings.clsi.docker.runtime
|
options.HostConfig.Runtime = Settings.clsi.docker.runtime
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (Settings.clsi.docker.Readonly) {
|
||||||
|
options.HostConfig.ReadonlyRootfs = true
|
||||||
|
options.HostConfig.Tmpfs = { '/tmp': 'rw,noexec,nosuid,size=65536k' }
|
||||||
|
options.Volumes['/home/tex'] = {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow per-compile group overriding of individual settings
|
||||||
|
if (
|
||||||
|
Settings.clsi.docker.compileGroupConfig &&
|
||||||
|
Settings.clsi.docker.compileGroupConfig[compileGroup]
|
||||||
|
) {
|
||||||
|
const override = Settings.clsi.docker.compileGroupConfig[compileGroup]
|
||||||
|
for (const key in override) {
|
||||||
|
_.set(options, key, override[key])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return options
|
return options
|
||||||
},
|
},
|
||||||
|
|
||||||
_fingerprintContainer(containerOptions) {
|
_fingerprintContainer(containerOptions) {
|
||||||
// Yay, Hashing!
|
// Yay, Hashing!
|
||||||
const json = JSON.stringify(containerOptions)
|
const json = JSON.stringify(containerOptions)
|
||||||
return crypto
|
return crypto.createHash('md5').update(json).digest('hex')
|
||||||
.createHash('md5')
|
|
||||||
.update(json)
|
|
||||||
.digest('hex')
|
|
||||||
},
|
},
|
||||||
|
|
||||||
startContainer(options, volumes, attachStreamHandler, callback) {
|
startContainer(options, volumes, attachStreamHandler, callback) {
|
||||||
return LockManager.runWithLock(
|
LockManager.runWithLock(
|
||||||
options.name,
|
options.name,
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
// Check that volumes exist before starting the container.
|
// Check that volumes exist before starting the container.
|
||||||
// When a container is started with volume pointing to a
|
// When a container is started with volume pointing to a
|
||||||
// non-existent directory then docker creates the directory but
|
// non-existent directory then docker creates the directory but
|
||||||
// with root ownership.
|
// with root ownership.
|
||||||
DockerRunner._checkVolumes(options, volumes, function(err) {
|
DockerRunner._checkVolumes(options, volumes, (err) => {
|
||||||
if (err != null) {
|
if (err != null) {
|
||||||
return releaseLock(err)
|
return releaseLock(err)
|
||||||
}
|
}
|
||||||
return DockerRunner._startContainer(
|
DockerRunner._startContainer(
|
||||||
options,
|
options,
|
||||||
volumes,
|
volumes,
|
||||||
attachStreamHandler,
|
attachStreamHandler,
|
||||||
@@ -348,93 +326,85 @@ module.exports = DockerRunner = {
|
|||||||
|
|
||||||
// Check that volumes exist and are directories
|
// Check that volumes exist and are directories
|
||||||
_checkVolumes(options, volumes, callback) {
|
_checkVolumes(options, volumes, callback) {
|
||||||
if (callback == null) {
|
|
||||||
callback = function(error, containerName) {}
|
|
||||||
}
|
|
||||||
if (usingSiblingContainers()) {
|
if (usingSiblingContainers()) {
|
||||||
// Server Pro, with sibling-containers active, skip checks
|
// Server Pro, with sibling-containers active, skip checks
|
||||||
return callback(null)
|
return callback(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
const checkVolume = (path, cb) =>
|
const checkVolume = (path, cb) =>
|
||||||
fs.stat(path, function(err, stats) {
|
fs.stat(path, (err, stats) => {
|
||||||
if (err != null) {
|
if (err != null) {
|
||||||
return cb(err)
|
return cb(err)
|
||||||
}
|
}
|
||||||
if (!(stats != null ? stats.isDirectory() : undefined)) {
|
if (!stats.isDirectory()) {
|
||||||
return cb(DockerRunner.ERR_NOT_DIRECTORY)
|
return cb(new Error('not a directory'))
|
||||||
}
|
}
|
||||||
return cb()
|
cb()
|
||||||
})
|
})
|
||||||
const jobs = []
|
const jobs = []
|
||||||
for (const vol in volumes) {
|
for (const vol in volumes) {
|
||||||
;(vol => jobs.push(cb => checkVolume(vol, cb)))(vol)
|
jobs.push((cb) => checkVolume(vol, cb))
|
||||||
}
|
}
|
||||||
return async.series(jobs, callback)
|
async.series(jobs, callback)
|
||||||
},
|
},
|
||||||
|
|
||||||
_startContainer(options, volumes, attachStreamHandler, callback) {
|
_startContainer(options, volumes, attachStreamHandler, callback) {
|
||||||
if (callback == null) {
|
|
||||||
callback = function(error, output) {}
|
|
||||||
}
|
|
||||||
callback = _.once(callback)
|
callback = _.once(callback)
|
||||||
const { name } = options
|
const { name } = options
|
||||||
|
|
||||||
logger.log({ container_name: name }, 'starting container')
|
logger.log({ container_name: name }, 'starting container')
|
||||||
const container = dockerode.getContainer(name)
|
const container = dockerode.getContainer(name)
|
||||||
|
|
||||||
const createAndStartContainer = () =>
|
function createAndStartContainer() {
|
||||||
dockerode.createContainer(options, function(error, container) {
|
dockerode.createContainer(options, (error, container) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return startExistingContainer()
|
startExistingContainer()
|
||||||
})
|
})
|
||||||
var startExistingContainer = () =>
|
}
|
||||||
|
|
||||||
|
function startExistingContainer() {
|
||||||
DockerRunner.attachToContainer(
|
DockerRunner.attachToContainer(
|
||||||
options.name,
|
options.name,
|
||||||
attachStreamHandler,
|
attachStreamHandler,
|
||||||
function(error) {
|
(error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return container.start(function(error) {
|
container.start((error) => {
|
||||||
if (
|
if (error != null && error.statusCode !== 304) {
|
||||||
error != null &&
|
callback(error)
|
||||||
(error != null ? error.statusCode : undefined) !== 304
|
|
||||||
) {
|
|
||||||
// already running
|
|
||||||
return callback(error)
|
|
||||||
} else {
|
} else {
|
||||||
return callback()
|
// already running
|
||||||
|
callback()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
return container.inspect(function(error, stats) {
|
}
|
||||||
if ((error != null ? error.statusCode : undefined) === 404) {
|
|
||||||
return createAndStartContainer()
|
container.inspect((error, stats) => {
|
||||||
|
if (error != null && error.statusCode === 404) {
|
||||||
|
createAndStartContainer()
|
||||||
} else if (error != null) {
|
} else if (error != null) {
|
||||||
logger.err(
|
logger.err(
|
||||||
{ container_name: name, error },
|
{ container_name: name, error },
|
||||||
'unable to inspect container to start'
|
'unable to inspect container to start'
|
||||||
)
|
)
|
||||||
return callback(error)
|
callback(error)
|
||||||
} else {
|
} else {
|
||||||
return startExistingContainer()
|
startExistingContainer()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
attachToContainer(containerId, attachStreamHandler, attachStartCallback) {
|
attachToContainer(containerId, attachStreamHandler, attachStartCallback) {
|
||||||
const container = dockerode.getContainer(containerId)
|
const container = dockerode.getContainer(containerId)
|
||||||
return container.attach({ stdout: 1, stderr: 1, stream: 1 }, function(
|
container.attach({ stdout: 1, stderr: 1, stream: 1 }, (error, stream) => {
|
||||||
error,
|
|
||||||
stream
|
|
||||||
) {
|
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
logger.error(
|
logger.error(
|
||||||
{ err: error, container_id: containerId },
|
{ err: error, containerId },
|
||||||
'error attaching to container'
|
'error attaching to container'
|
||||||
)
|
)
|
||||||
return attachStartCallback(error)
|
return attachStartCallback(error)
|
||||||
@@ -442,10 +412,10 @@ module.exports = DockerRunner = {
|
|||||||
attachStartCallback()
|
attachStartCallback()
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.log({ container_id: containerId }, 'attached to container')
|
logger.log({ containerId }, 'attached to container')
|
||||||
|
|
||||||
const MAX_OUTPUT = 1024 * 1024 // limit output to 1MB
|
const MAX_OUTPUT = 1024 * 1024 // limit output to 1MB
|
||||||
const createStringOutputStream = function(name) {
|
function createStringOutputStream(name) {
|
||||||
return {
|
return {
|
||||||
data: '',
|
data: '',
|
||||||
overflowed: false,
|
overflowed: false,
|
||||||
@@ -454,18 +424,18 @@ module.exports = DockerRunner = {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (this.data.length < MAX_OUTPUT) {
|
if (this.data.length < MAX_OUTPUT) {
|
||||||
return (this.data += data)
|
this.data += data
|
||||||
} else {
|
} else {
|
||||||
logger.error(
|
logger.error(
|
||||||
{
|
{
|
||||||
container_id: containerId,
|
containerId,
|
||||||
length: this.data.length,
|
length: this.data.length,
|
||||||
maxLen: MAX_OUTPUT
|
maxLen: MAX_OUTPUT
|
||||||
},
|
},
|
||||||
`${name} exceeds max size`
|
`${name} exceeds max size`
|
||||||
)
|
)
|
||||||
this.data += `(...truncated at ${MAX_OUTPUT} chars...)`
|
this.data += `(...truncated at ${MAX_OUTPUT} chars...)`
|
||||||
return (this.overflowed = true)
|
this.overflowed = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// kill container if too much output
|
// kill container if too much output
|
||||||
@@ -478,63 +448,52 @@ module.exports = DockerRunner = {
|
|||||||
|
|
||||||
container.modem.demuxStream(stream, stdout, stderr)
|
container.modem.demuxStream(stream, stdout, stderr)
|
||||||
|
|
||||||
stream.on('error', err =>
|
stream.on('error', (err) =>
|
||||||
logger.error(
|
logger.error(
|
||||||
{ err, container_id: containerId },
|
{ err, containerId },
|
||||||
'error reading from container stream'
|
'error reading from container stream'
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
return stream.on('end', () =>
|
stream.on('end', () =>
|
||||||
attachStreamHandler(null, { stdout: stdout.data, stderr: stderr.data })
|
attachStreamHandler(null, { stdout: stdout.data, stderr: stderr.data })
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
waitForContainer(containerId, timeout, _callback) {
|
waitForContainer(containerId, timeout, _callback) {
|
||||||
if (_callback == null) {
|
const callback = _.once(_callback)
|
||||||
_callback = function(error, exitCode) {}
|
|
||||||
}
|
|
||||||
const callback = function(...args) {
|
|
||||||
_callback(...Array.from(args || []))
|
|
||||||
// Only call the callback once
|
|
||||||
return (_callback = function() {})
|
|
||||||
}
|
|
||||||
|
|
||||||
const container = dockerode.getContainer(containerId)
|
const container = dockerode.getContainer(containerId)
|
||||||
|
|
||||||
let timedOut = false
|
let timedOut = false
|
||||||
const timeoutId = setTimeout(function() {
|
const timeoutId = setTimeout(() => {
|
||||||
timedOut = true
|
timedOut = true
|
||||||
logger.log(
|
logger.log({ containerId }, 'timeout reached, killing container')
|
||||||
{ container_id: containerId },
|
container.kill((err) => {
|
||||||
'timeout reached, killing container'
|
logger.warn({ err, containerId }, 'failed to kill container')
|
||||||
)
|
})
|
||||||
return container.kill(function() {})
|
|
||||||
}, timeout)
|
}, timeout)
|
||||||
|
|
||||||
logger.log({ container_id: containerId }, 'waiting for docker container')
|
logger.log({ containerId }, 'waiting for docker container')
|
||||||
return container.wait(function(error, res) {
|
container.wait((error, res) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
clearTimeout(timeoutId)
|
clearTimeout(timeoutId)
|
||||||
logger.error(
|
logger.error({ err: error, containerId }, 'error waiting for container')
|
||||||
{ err: error, container_id: containerId },
|
|
||||||
'error waiting for container'
|
|
||||||
)
|
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
if (timedOut) {
|
if (timedOut) {
|
||||||
logger.log({ containerId }, 'docker container timed out')
|
logger.log({ containerId }, 'docker container timed out')
|
||||||
error = DockerRunner.ERR_TIMED_OUT
|
error = new Error('container timed out')
|
||||||
error.timedout = true
|
error.timedout = true
|
||||||
return callback(error)
|
callback(error)
|
||||||
} else {
|
} else {
|
||||||
clearTimeout(timeoutId)
|
clearTimeout(timeoutId)
|
||||||
logger.log(
|
logger.log(
|
||||||
{ container_id: containerId, exitCode: res.StatusCode },
|
{ containerId, exitCode: res.StatusCode },
|
||||||
'docker container returned'
|
'docker container returned'
|
||||||
)
|
)
|
||||||
return callback(null, res.StatusCode)
|
callback(null, res.StatusCode)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
@@ -546,12 +505,9 @@ module.exports = DockerRunner = {
|
|||||||
// async exception, but if you delete by id it just does a normal
|
// async exception, but if you delete by id it just does a normal
|
||||||
// error callback. We fall back to deleting by name if no id is
|
// error callback. We fall back to deleting by name if no id is
|
||||||
// supplied.
|
// supplied.
|
||||||
if (callback == null) {
|
LockManager.runWithLock(
|
||||||
callback = function(error) {}
|
|
||||||
}
|
|
||||||
return LockManager.runWithLock(
|
|
||||||
containerName,
|
containerName,
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
DockerRunner._destroyContainer(
|
DockerRunner._destroyContainer(
|
||||||
containerId || containerName,
|
containerId || containerName,
|
||||||
shouldForce,
|
shouldForce,
|
||||||
@@ -562,46 +518,31 @@ module.exports = DockerRunner = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
_destroyContainer(containerId, shouldForce, callback) {
|
_destroyContainer(containerId, shouldForce, callback) {
|
||||||
if (callback == null) {
|
logger.log({ containerId }, 'destroying docker container')
|
||||||
callback = function(error) {}
|
|
||||||
}
|
|
||||||
logger.log({ container_id: containerId }, 'destroying docker container')
|
|
||||||
const container = dockerode.getContainer(containerId)
|
const container = dockerode.getContainer(containerId)
|
||||||
return container.remove({ force: shouldForce === true }, function(error) {
|
container.remove({ force: shouldForce === true, v: true }, (error) => {
|
||||||
if (
|
if (error != null && error.statusCode === 404) {
|
||||||
error != null &&
|
|
||||||
(error != null ? error.statusCode : undefined) === 404
|
|
||||||
) {
|
|
||||||
logger.warn(
|
logger.warn(
|
||||||
{ err: error, container_id: containerId },
|
{ err: error, containerId },
|
||||||
'container not found, continuing'
|
'container not found, continuing'
|
||||||
)
|
)
|
||||||
error = null
|
error = null
|
||||||
}
|
}
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
logger.error(
|
logger.error({ err: error, containerId }, 'error destroying container')
|
||||||
{ err: error, container_id: containerId },
|
|
||||||
'error destroying container'
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
logger.log({ container_id: containerId }, 'destroyed container')
|
logger.log({ containerId }, 'destroyed container')
|
||||||
}
|
}
|
||||||
return callback(error)
|
callback(error)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
// handle expiry of docker containers
|
// handle expiry of docker containers
|
||||||
|
|
||||||
MAX_CONTAINER_AGE:
|
MAX_CONTAINER_AGE: Settings.clsi.docker.maxContainerAge || ONE_HOUR_IN_MS,
|
||||||
Settings.clsi.docker.maxContainerAge || (oneHour = 60 * 60 * 1000),
|
|
||||||
|
|
||||||
examineOldContainer(container, callback) {
|
examineOldContainer(container, callback) {
|
||||||
if (callback == null) {
|
const name = container.Name || (container.Names && container.Names[0])
|
||||||
callback = function(error, name, id, ttl) {}
|
|
||||||
}
|
|
||||||
const name =
|
|
||||||
container.Name ||
|
|
||||||
(container.Names != null ? container.Names[0] : undefined)
|
|
||||||
const created = container.Created * 1000 // creation time is returned in seconds
|
const created = container.Created * 1000 // creation time is returned in seconds
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
const age = now - created
|
const age = now - created
|
||||||
@@ -611,36 +552,29 @@ module.exports = DockerRunner = {
|
|||||||
{ containerName: name, created, now, age, maxAge, ttl },
|
{ containerName: name, created, now, age, maxAge, ttl },
|
||||||
'checking whether to destroy container'
|
'checking whether to destroy container'
|
||||||
)
|
)
|
||||||
return callback(null, name, container.Id, ttl)
|
return { name, id: container.Id, ttl }
|
||||||
},
|
},
|
||||||
|
|
||||||
destroyOldContainers(callback) {
|
destroyOldContainers(callback) {
|
||||||
if (callback == null) {
|
dockerode.listContainers({ all: true }, (error, containers) => {
|
||||||
callback = function(error) {}
|
|
||||||
}
|
|
||||||
return dockerode.listContainers({ all: true }, function(error, containers) {
|
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
const jobs = []
|
const jobs = []
|
||||||
for (const container of Array.from(containers || [])) {
|
for (const container of containers) {
|
||||||
;(container =>
|
const { name, id, ttl } = DockerRunner.examineOldContainer(container)
|
||||||
DockerRunner.examineOldContainer(container, function(
|
|
||||||
err,
|
|
||||||
name,
|
|
||||||
id,
|
|
||||||
ttl
|
|
||||||
) {
|
|
||||||
if (name.slice(0, 9) === '/project-' && ttl <= 0) {
|
if (name.slice(0, 9) === '/project-' && ttl <= 0) {
|
||||||
return jobs.push(cb =>
|
// strip the / prefix
|
||||||
DockerRunner.destroyContainer(name, id, false, () => cb())
|
// the LockManager uses the plain container name
|
||||||
|
const plainName = name.slice(1)
|
||||||
|
jobs.push((cb) =>
|
||||||
|
DockerRunner.destroyContainer(plainName, id, false, () => cb())
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}))(container)
|
|
||||||
}
|
}
|
||||||
// Ignore errors because some containers get stuck but
|
// Ignore errors because some containers get stuck but
|
||||||
// will be destroyed next time
|
// will be destroyed next time
|
||||||
return async.series(jobs, callback)
|
async.series(jobs, callback)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -657,8 +591,13 @@ module.exports = DockerRunner = {
|
|||||||
const randomDelay = Math.floor(Math.random() * 5 * 60 * 1000)
|
const randomDelay = Math.floor(Math.random() * 5 * 60 * 1000)
|
||||||
containerMonitorTimeout = setTimeout(() => {
|
containerMonitorTimeout = setTimeout(() => {
|
||||||
containerMonitorInterval = setInterval(
|
containerMonitorInterval = setInterval(
|
||||||
() => DockerRunner.destroyOldContainers(),
|
() =>
|
||||||
(oneHour = 60 * 60 * 1000)
|
DockerRunner.destroyOldContainers((err) => {
|
||||||
|
if (err) {
|
||||||
|
logger.error({ err }, 'failed to destroy old containers')
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
ONE_HOUR_IN_MS
|
||||||
)
|
)
|
||||||
}, randomDelay)
|
}, randomDelay)
|
||||||
},
|
},
|
||||||
@@ -669,27 +608,12 @@ module.exports = DockerRunner = {
|
|||||||
containerMonitorTimeout = undefined
|
containerMonitorTimeout = undefined
|
||||||
}
|
}
|
||||||
if (containerMonitorInterval) {
|
if (containerMonitorInterval) {
|
||||||
clearInterval(containerMonitorTimeout)
|
clearInterval(containerMonitorInterval)
|
||||||
containerMonitorTimeout = undefined
|
containerMonitorInterval = undefined
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
DockerRunner.startContainerMonitor()
|
DockerRunner.startContainerMonitor()
|
||||||
|
|
||||||
function __guard__(value, transform) {
|
module.exports = DockerRunner
|
||||||
return typeof value !== 'undefined' && value !== null
|
|
||||||
? transform(value)
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
function __guardMethod__(obj, methodName, transform) {
|
|
||||||
if (
|
|
||||||
typeof obj !== 'undefined' &&
|
|
||||||
obj !== null &&
|
|
||||||
typeof obj[methodName] === 'function'
|
|
||||||
) {
|
|
||||||
return transform(obj, methodName)
|
|
||||||
} else {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ const Settings = require('settings-sharelatex')
|
|||||||
const logger = require('logger-sharelatex')
|
const logger = require('logger-sharelatex')
|
||||||
const Metrics = require('./Metrics')
|
const Metrics = require('./Metrics')
|
||||||
const CommandRunner = require('./CommandRunner')
|
const CommandRunner = require('./CommandRunner')
|
||||||
|
const fs = require('fs')
|
||||||
|
|
||||||
const ProcessTable = {} // table of currently running jobs (pids or docker container names)
|
const ProcessTable = {} // table of currently running jobs (pids or docker container names)
|
||||||
|
|
||||||
@@ -35,7 +36,8 @@ module.exports = LatexRunner = {
|
|||||||
timeout,
|
timeout,
|
||||||
image,
|
image,
|
||||||
environment,
|
environment,
|
||||||
flags
|
flags,
|
||||||
|
compileGroup
|
||||||
} = options
|
} = options
|
||||||
if (!compiler) {
|
if (!compiler) {
|
||||||
compiler = 'pdflatex'
|
compiler = 'pdflatex'
|
||||||
@@ -45,7 +47,15 @@ module.exports = LatexRunner = {
|
|||||||
} // milliseconds
|
} // milliseconds
|
||||||
|
|
||||||
logger.log(
|
logger.log(
|
||||||
{ directory, compiler, timeout, mainFile, environment, flags },
|
{
|
||||||
|
directory,
|
||||||
|
compiler,
|
||||||
|
timeout,
|
||||||
|
mainFile,
|
||||||
|
environment,
|
||||||
|
flags,
|
||||||
|
compileGroup
|
||||||
|
},
|
||||||
'starting compile'
|
'starting compile'
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -78,6 +88,7 @@ module.exports = LatexRunner = {
|
|||||||
image,
|
image,
|
||||||
timeout,
|
timeout,
|
||||||
environment,
|
environment,
|
||||||
|
compileGroup,
|
||||||
function (error, output) {
|
function (error, output) {
|
||||||
delete ProcessTable[id]
|
delete ProcessTable[id]
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
@@ -85,13 +96,13 @@ module.exports = LatexRunner = {
|
|||||||
}
|
}
|
||||||
const runs =
|
const runs =
|
||||||
__guard__(
|
__guard__(
|
||||||
__guard__(output != null ? output.stderr : undefined, x1 =>
|
__guard__(output != null ? output.stderr : undefined, (x1) =>
|
||||||
x1.match(/^Run number \d+ of .*latex/gm)
|
x1.match(/^Run number \d+ of .*latex/gm)
|
||||||
),
|
),
|
||||||
x => x.length
|
(x) => x.length
|
||||||
) || 0
|
) || 0
|
||||||
const failed =
|
const failed =
|
||||||
__guard__(output != null ? output.stdout : undefined, x2 =>
|
__guard__(output != null ? output.stdout : undefined, (x2) =>
|
||||||
x2.match(/^Latexmk: Errors/m)
|
x2.match(/^Latexmk: Errors/m)
|
||||||
) != null
|
) != null
|
||||||
? 1
|
? 1
|
||||||
@@ -111,27 +122,55 @@ module.exports = LatexRunner = {
|
|||||||
stderr != null
|
stderr != null
|
||||||
? stderr.match(/Percent of CPU this job got: (\d+)/m)
|
? stderr.match(/Percent of CPU this job got: (\d+)/m)
|
||||||
: undefined,
|
: undefined,
|
||||||
x3 => x3[1]
|
(x3) => x3[1]
|
||||||
) || 0
|
) || 0
|
||||||
timings['cpu-time'] =
|
timings['cpu-time'] =
|
||||||
__guard__(
|
__guard__(
|
||||||
stderr != null
|
stderr != null
|
||||||
? stderr.match(/User time.*: (\d+.\d+)/m)
|
? stderr.match(/User time.*: (\d+.\d+)/m)
|
||||||
: undefined,
|
: undefined,
|
||||||
x4 => x4[1]
|
(x4) => x4[1]
|
||||||
) || 0
|
) || 0
|
||||||
timings['sys-time'] =
|
timings['sys-time'] =
|
||||||
__guard__(
|
__guard__(
|
||||||
stderr != null
|
stderr != null
|
||||||
? stderr.match(/System time.*: (\d+.\d+)/m)
|
? stderr.match(/System time.*: (\d+.\d+)/m)
|
||||||
: undefined,
|
: undefined,
|
||||||
x5 => x5[1]
|
(x5) => x5[1]
|
||||||
) || 0
|
) || 0
|
||||||
|
// record output files
|
||||||
|
LatexRunner.writeLogOutput(project_id, directory, output, () => {
|
||||||
return callback(error, output, stats, timings)
|
return callback(error, output, stats, timings)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
))
|
))
|
||||||
},
|
},
|
||||||
|
|
||||||
|
writeLogOutput(project_id, directory, output, callback) {
|
||||||
|
if (!output) {
|
||||||
|
return callback()
|
||||||
|
}
|
||||||
|
// internal method for writing non-empty log files
|
||||||
|
function _writeFile(file, content, cb) {
|
||||||
|
if (content && content.length > 0) {
|
||||||
|
fs.writeFile(file, content, (err) => {
|
||||||
|
if (err) {
|
||||||
|
logger.error({ project_id, file }, 'error writing log file') // don't fail on error
|
||||||
|
}
|
||||||
|
cb()
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
cb()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// write stdout and stderr, ignoring errors
|
||||||
|
_writeFile(Path.join(directory, 'output.stdout'), output.stdout, () => {
|
||||||
|
_writeFile(Path.join(directory, 'output.stderr'), output.stderr, () => {
|
||||||
|
callback()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
killLatex(project_id, callback) {
|
killLatex(project_id, callback) {
|
||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error) {}
|
callback = function (error) {}
|
||||||
@@ -163,7 +202,7 @@ module.exports = LatexRunner = {
|
|||||||
return (
|
return (
|
||||||
__guard__(
|
__guard__(
|
||||||
Settings != null ? Settings.clsi : undefined,
|
Settings != null ? Settings.clsi : undefined,
|
||||||
x => x.latexmkCommandPrefix
|
(x) => x.latexmkCommandPrefix
|
||||||
) || []
|
) || []
|
||||||
).concat(args)
|
).concat(args)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -15,17 +15,29 @@
|
|||||||
*/
|
*/
|
||||||
let CommandRunner
|
let CommandRunner
|
||||||
const { spawn } = require('child_process')
|
const { spawn } = require('child_process')
|
||||||
|
const _ = require('underscore')
|
||||||
const logger = require('logger-sharelatex')
|
const logger = require('logger-sharelatex')
|
||||||
|
|
||||||
logger.info('using standard command runner')
|
logger.info('using standard command runner')
|
||||||
|
|
||||||
module.exports = CommandRunner = {
|
module.exports = CommandRunner = {
|
||||||
run(project_id, command, directory, image, timeout, environment, callback) {
|
run(
|
||||||
|
project_id,
|
||||||
|
command,
|
||||||
|
directory,
|
||||||
|
image,
|
||||||
|
timeout,
|
||||||
|
environment,
|
||||||
|
compileGroup,
|
||||||
|
callback
|
||||||
|
) {
|
||||||
let key, value
|
let key, value
|
||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error) {}
|
callback = function (error) {}
|
||||||
|
} else {
|
||||||
|
callback = _.once(callback)
|
||||||
}
|
}
|
||||||
command = Array.from(command).map(arg =>
|
command = Array.from(command).map((arg) =>
|
||||||
arg.toString().replace('$COMPILE_DIR', directory)
|
arg.toString().replace('$COMPILE_DIR', directory)
|
||||||
)
|
)
|
||||||
logger.log({ project_id, command, directory }, 'running command')
|
logger.log({ project_id, command, directory }, 'running command')
|
||||||
@@ -46,7 +58,7 @@ module.exports = CommandRunner = {
|
|||||||
const proc = spawn(command[0], command.slice(1), { cwd: directory, env })
|
const proc = spawn(command[0], command.slice(1), { cwd: directory, env })
|
||||||
|
|
||||||
let stdout = ''
|
let stdout = ''
|
||||||
proc.stdout.on('data', data => (stdout += data))
|
proc.stdout.setEncoding('utf8').on('data', (data) => (stdout += data))
|
||||||
|
|
||||||
proc.on('error', function (err) {
|
proc.on('error', function (err) {
|
||||||
logger.err(
|
logger.err(
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ const fs = require('fs')
|
|||||||
const fse = require('fs-extra')
|
const fse = require('fs-extra')
|
||||||
const Path = require('path')
|
const Path = require('path')
|
||||||
const logger = require('logger-sharelatex')
|
const logger = require('logger-sharelatex')
|
||||||
const _ = require('underscore')
|
const _ = require('lodash')
|
||||||
const Settings = require('settings-sharelatex')
|
const Settings = require('settings-sharelatex')
|
||||||
const crypto = require('crypto')
|
const crypto = require('crypto')
|
||||||
|
|
||||||
@@ -99,13 +99,16 @@ module.exports = OutputCacheManager = {
|
|||||||
(Settings.clsi != null ? Settings.clsi.archive_logs : undefined) ||
|
(Settings.clsi != null ? Settings.clsi.archive_logs : undefined) ||
|
||||||
(Settings.clsi != null ? Settings.clsi.strace : undefined)
|
(Settings.clsi != null ? Settings.clsi.strace : undefined)
|
||||||
) {
|
) {
|
||||||
OutputCacheManager.archiveLogs(outputFiles, compileDir, buildId, function(
|
OutputCacheManager.archiveLogs(
|
||||||
err
|
outputFiles,
|
||||||
) {
|
compileDir,
|
||||||
|
buildId,
|
||||||
|
function (err) {
|
||||||
if (err != null) {
|
if (err != null) {
|
||||||
return logger.warn({ err }, 'erroring archiving log files')
|
return logger.warn({ err }, 'erroring archiving log files')
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// make the new cache directory
|
// make the new cache directory
|
||||||
@@ -280,7 +283,7 @@ module.exports = OutputCacheManager = {
|
|||||||
// we can get the build time from the first part of the directory name DDDD-RRRR
|
// we can get the build time from the first part of the directory name DDDD-RRRR
|
||||||
// DDDD is date and RRRR is random bytes
|
// DDDD is date and RRRR is random bytes
|
||||||
const dirTime = parseInt(
|
const dirTime = parseInt(
|
||||||
__guard__(dir.split('-'), x => x[0]),
|
__guard__(dir.split('-'), (x) => x[0]),
|
||||||
16
|
16
|
||||||
)
|
)
|
||||||
const age = currentTime - dirTime
|
const age = currentTime - dirTime
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ module.exports = OutputFileFinder = {
|
|||||||
if (!incomingResources[file]) {
|
if (!incomingResources[file]) {
|
||||||
outputFiles.push({
|
outputFiles.push({
|
||||||
path: file,
|
path: file,
|
||||||
type: __guard__(file.match(/\.([^\.]+)$/), x => x[1])
|
type: __guard__(file.match(/\.([^\.]+)$/), (x) => x[1])
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -87,7 +87,7 @@ module.exports = OutputFileFinder = {
|
|||||||
|
|
||||||
const proc = spawn('find', args)
|
const proc = spawn('find', args)
|
||||||
let stdout = ''
|
let stdout = ''
|
||||||
proc.stdout.on('data', chunk => (stdout += chunk.toString()))
|
proc.stdout.setEncoding('utf8').on('data', (chunk) => (stdout += chunk))
|
||||||
proc.on('error', callback)
|
proc.on('error', callback)
|
||||||
return proc.on('close', function (code) {
|
return proc.on('close', function (code) {
|
||||||
if (code !== 0) {
|
if (code !== 0) {
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ const Path = require('path')
|
|||||||
const { spawn } = require('child_process')
|
const { spawn } = require('child_process')
|
||||||
const logger = require('logger-sharelatex')
|
const logger = require('logger-sharelatex')
|
||||||
const Metrics = require('./Metrics')
|
const Metrics = require('./Metrics')
|
||||||
const _ = require('underscore')
|
const _ = require('lodash')
|
||||||
|
|
||||||
module.exports = OutputFileOptimiser = {
|
module.exports = OutputFileOptimiser = {
|
||||||
optimiseFile(src, dst, callback) {
|
optimiseFile(src, dst, callback) {
|
||||||
@@ -45,8 +45,7 @@ module.exports = OutputFileOptimiser = {
|
|||||||
|
|
||||||
checkIfPDFIsOptimised(file, callback) {
|
checkIfPDFIsOptimised(file, callback) {
|
||||||
const SIZE = 16 * 1024 // check the header of the pdf
|
const SIZE = 16 * 1024 // check the header of the pdf
|
||||||
const result = new Buffer(SIZE)
|
const result = Buffer.alloc(SIZE) // fills with zeroes by default
|
||||||
result.fill(0) // prevent leakage of uninitialised buffer
|
|
||||||
return fs.open(file, 'r', function (err, fd) {
|
return fs.open(file, 'r', function (err, fd) {
|
||||||
if (err != null) {
|
if (err != null) {
|
||||||
return callback(err)
|
return callback(err)
|
||||||
@@ -78,7 +77,7 @@ module.exports = OutputFileOptimiser = {
|
|||||||
const timer = new Metrics.Timer('qpdf')
|
const timer = new Metrics.Timer('qpdf')
|
||||||
const proc = spawn('qpdf', args)
|
const proc = spawn('qpdf', args)
|
||||||
let stdout = ''
|
let stdout = ''
|
||||||
proc.stdout.on('data', chunk => (stdout += chunk.toString()))
|
proc.stdout.setEncoding('utf8').on('data', (chunk) => (stdout += chunk))
|
||||||
callback = _.once(callback) // avoid double call back for error and close event
|
callback = _.once(callback) // avoid double call back for error and close event
|
||||||
proc.on('error', function (err) {
|
proc.on('error', function (err) {
|
||||||
logger.warn({ err, args }, 'qpdf failed')
|
logger.warn({ err, args }, 'qpdf failed')
|
||||||
|
|||||||
@@ -20,15 +20,37 @@ const async = require('async')
|
|||||||
const logger = require('logger-sharelatex')
|
const logger = require('logger-sharelatex')
|
||||||
const oneDay = 24 * 60 * 60 * 1000
|
const oneDay = 24 * 60 * 60 * 1000
|
||||||
const Settings = require('settings-sharelatex')
|
const Settings = require('settings-sharelatex')
|
||||||
|
const diskusage = require('diskusage')
|
||||||
|
|
||||||
module.exports = ProjectPersistenceManager = {
|
module.exports = ProjectPersistenceManager = {
|
||||||
EXPIRY_TIMEOUT: Settings.project_cache_length_ms || oneDay * 2.5,
|
EXPIRY_TIMEOUT: Settings.project_cache_length_ms || oneDay * 2.5,
|
||||||
|
|
||||||
|
refreshExpiryTimeout(callback) {
|
||||||
|
if (callback == null) {
|
||||||
|
callback = function (error) {}
|
||||||
|
}
|
||||||
|
diskusage.check('/', function (err, stats) {
|
||||||
|
if (err) {
|
||||||
|
logger.err({ err: err }, 'error getting disk usage')
|
||||||
|
return callback(err)
|
||||||
|
}
|
||||||
|
const lowDisk = stats.available / stats.total < 0.1
|
||||||
|
const lowerExpiry = ProjectPersistenceManager.EXPIRY_TIMEOUT * 0.9
|
||||||
|
if (lowDisk && Settings.project_cache_length_ms / 2 < lowerExpiry) {
|
||||||
|
logger.warn(
|
||||||
|
{ stats: stats },
|
||||||
|
'disk running low on space, modifying EXPIRY_TIMEOUT'
|
||||||
|
)
|
||||||
|
ProjectPersistenceManager.EXPIRY_TIMEOUT = lowerExpiry
|
||||||
|
}
|
||||||
|
callback()
|
||||||
|
})
|
||||||
|
},
|
||||||
markProjectAsJustAccessed(project_id, callback) {
|
markProjectAsJustAccessed(project_id, callback) {
|
||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error) {}
|
callback = function (error) {}
|
||||||
}
|
}
|
||||||
const job = cb =>
|
const job = (cb) =>
|
||||||
db.Project.findOrCreate({ where: { project_id } })
|
db.Project.findOrCreate({ where: { project_id } })
|
||||||
.spread((project, created) =>
|
.spread((project, created) =>
|
||||||
project
|
project
|
||||||
@@ -52,8 +74,8 @@ module.exports = ProjectPersistenceManager = {
|
|||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
logger.log({ project_ids }, 'clearing expired projects')
|
logger.log({ project_ids }, 'clearing expired projects')
|
||||||
const jobs = Array.from(project_ids || []).map(project_id =>
|
const jobs = Array.from(project_ids || []).map((project_id) =>
|
||||||
(project_id => callback =>
|
((project_id) => (callback) =>
|
||||||
ProjectPersistenceManager.clearProjectFromCache(project_id, function (
|
ProjectPersistenceManager.clearProjectFromCache(project_id, function (
|
||||||
err
|
err
|
||||||
) {
|
) {
|
||||||
@@ -69,7 +91,7 @@ module.exports = ProjectPersistenceManager = {
|
|||||||
}
|
}
|
||||||
return CompileManager.clearExpiredProjects(
|
return CompileManager.clearExpiredProjects(
|
||||||
ProjectPersistenceManager.EXPIRY_TIMEOUT,
|
ProjectPersistenceManager.EXPIRY_TIMEOUT,
|
||||||
error => callback()
|
(error) => callback()
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -126,7 +148,7 @@ module.exports = ProjectPersistenceManager = {
|
|||||||
callback = function (error) {}
|
callback = function (error) {}
|
||||||
}
|
}
|
||||||
logger.log({ project_id }, 'clearing project from database')
|
logger.log({ project_id }, 'clearing project from database')
|
||||||
const job = cb =>
|
const job = (cb) =>
|
||||||
db.Project.destroy({ where: { project_id } })
|
db.Project.destroy({ where: { project_id } })
|
||||||
.then(() => cb())
|
.then(() => cb())
|
||||||
.error(cb)
|
.error(cb)
|
||||||
@@ -144,10 +166,10 @@ module.exports = ProjectPersistenceManager = {
|
|||||||
const q = {}
|
const q = {}
|
||||||
q[db.op.lt] = keepProjectsFrom
|
q[db.op.lt] = keepProjectsFrom
|
||||||
return db.Project.findAll({ where: { lastAccessed: q } })
|
return db.Project.findAll({ where: { lastAccessed: q } })
|
||||||
.then(projects =>
|
.then((projects) =>
|
||||||
cb(
|
cb(
|
||||||
null,
|
null,
|
||||||
projects.map(project => project.project_id)
|
projects.map((project) => project.project_id)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
.error(cb)
|
.error(cb)
|
||||||
|
|||||||
@@ -61,7 +61,13 @@ module.exports = RequestParser = {
|
|||||||
response.imageName = this._parseAttribute(
|
response.imageName = this._parseAttribute(
|
||||||
'imageName',
|
'imageName',
|
||||||
compile.options.imageName,
|
compile.options.imageName,
|
||||||
{ type: 'string' }
|
{
|
||||||
|
type: 'string',
|
||||||
|
validValues:
|
||||||
|
settings.clsi &&
|
||||||
|
settings.clsi.docker &&
|
||||||
|
settings.clsi.docker.allowedImages
|
||||||
|
}
|
||||||
)
|
)
|
||||||
response.draft = this._parseAttribute('draft', compile.options.draft, {
|
response.draft = this._parseAttribute('draft', compile.options.draft, {
|
||||||
default: false,
|
default: false,
|
||||||
@@ -74,7 +80,17 @@ module.exports = RequestParser = {
|
|||||||
default: [],
|
default: [],
|
||||||
type: 'object'
|
type: 'object'
|
||||||
})
|
})
|
||||||
|
if (settings.allowedCompileGroups) {
|
||||||
|
response.compileGroup = this._parseAttribute(
|
||||||
|
'compileGroup',
|
||||||
|
compile.options.compileGroup,
|
||||||
|
{
|
||||||
|
validValues: settings.allowedCompileGroups,
|
||||||
|
default: '',
|
||||||
|
type: 'string'
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
// The syncType specifies whether the request contains all
|
// The syncType specifies whether the request contains all
|
||||||
// resources (full) or only those resources to be updated
|
// resources (full) or only those resources to be updated
|
||||||
// in-place (incremental).
|
// in-place (incremental).
|
||||||
|
|||||||
@@ -56,7 +56,9 @@ module.exports = ResourceStateManager = {
|
|||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
logger.log({ state, basePath }, 'writing sync state')
|
logger.log({ state, basePath }, 'writing sync state')
|
||||||
const resourceList = Array.from(resources).map(resource => resource.path)
|
const resourceList = Array.from(resources).map(
|
||||||
|
(resource) => resource.path
|
||||||
|
)
|
||||||
return fs.writeFile(
|
return fs.writeFile(
|
||||||
stateFile,
|
stateFile,
|
||||||
[...Array.from(resourceList), `stateHash:${state}`].join('\n'),
|
[...Array.from(resourceList), `stateHash:${state}`].join('\n'),
|
||||||
@@ -86,7 +88,7 @@ module.exports = ResourceStateManager = {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
const array =
|
const array =
|
||||||
__guard__(result != null ? result.toString() : undefined, x =>
|
__guard__(result != null ? result.toString() : undefined, (x) =>
|
||||||
x.split('\n')
|
x.split('\n')
|
||||||
) || []
|
) || []
|
||||||
const adjustedLength = Math.max(array.length, 1)
|
const adjustedLength = Math.max(array.length, 1)
|
||||||
@@ -102,7 +104,7 @@ module.exports = ResourceStateManager = {
|
|||||||
new Errors.FilesOutOfSyncError('invalid state for incremental update')
|
new Errors.FilesOutOfSyncError('invalid state for incremental update')
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
const resources = Array.from(resourceList).map(path => ({ path }))
|
const resources = Array.from(resourceList).map((path) => ({ path }))
|
||||||
return callback(null, resources)
|
return callback(null, resources)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -116,7 +118,7 @@ module.exports = ResourceStateManager = {
|
|||||||
}
|
}
|
||||||
for (file of Array.from(resources || [])) {
|
for (file of Array.from(resources || [])) {
|
||||||
for (const dir of Array.from(
|
for (const dir of Array.from(
|
||||||
__guard__(file != null ? file.path : undefined, x => x.split('/'))
|
__guard__(file != null ? file.path : undefined, (x) => x.split('/'))
|
||||||
)) {
|
)) {
|
||||||
if (dir === '..') {
|
if (dir === '..') {
|
||||||
return callback(new Error('relative path in resource file list'))
|
return callback(new Error('relative path in resource file list'))
|
||||||
@@ -129,8 +131,8 @@ module.exports = ResourceStateManager = {
|
|||||||
seenFile[file] = true
|
seenFile[file] = true
|
||||||
}
|
}
|
||||||
const missingFiles = Array.from(resources)
|
const missingFiles = Array.from(resources)
|
||||||
.filter(resource => !seenFile[resource.path])
|
.filter((resource) => !seenFile[resource.path])
|
||||||
.map(resource => resource.path)
|
.map((resource) => resource.path)
|
||||||
if ((missingFiles != null ? missingFiles.length : undefined) > 0) {
|
if ((missingFiles != null ? missingFiles.length : undefined) > 0) {
|
||||||
logger.err(
|
logger.err(
|
||||||
{ missingFiles, basePath, allFiles, resources },
|
{ missingFiles, basePath, allFiles, resources },
|
||||||
|
|||||||
@@ -109,13 +109,13 @@ module.exports = ResourceWriter = {
|
|||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error) {}
|
callback = function (error) {}
|
||||||
}
|
}
|
||||||
return this._createDirectory(basePath, error => {
|
return this._createDirectory(basePath, (error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
const jobs = Array.from(resources).map(resource =>
|
const jobs = Array.from(resources).map((resource) =>
|
||||||
(resource => {
|
((resource) => {
|
||||||
return callback =>
|
return (callback) =>
|
||||||
this._writeResourceToDisk(project_id, resource, basePath, callback)
|
this._writeResourceToDisk(project_id, resource, basePath, callback)
|
||||||
})(resource)
|
})(resource)
|
||||||
)
|
)
|
||||||
@@ -127,17 +127,17 @@ module.exports = ResourceWriter = {
|
|||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error) {}
|
callback = function (error) {}
|
||||||
}
|
}
|
||||||
return this._createDirectory(basePath, error => {
|
return this._createDirectory(basePath, (error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return this._removeExtraneousFiles(resources, basePath, error => {
|
return this._removeExtraneousFiles(resources, basePath, (error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
const jobs = Array.from(resources).map(resource =>
|
const jobs = Array.from(resources).map((resource) =>
|
||||||
(resource => {
|
((resource) => {
|
||||||
return callback =>
|
return (callback) =>
|
||||||
this._writeResourceToDisk(
|
this._writeResourceToDisk(
|
||||||
project_id,
|
project_id,
|
||||||
resource,
|
resource,
|
||||||
@@ -231,7 +231,9 @@ module.exports = ResourceWriter = {
|
|||||||
path === 'output.pdf' ||
|
path === 'output.pdf' ||
|
||||||
path === 'output.dvi' ||
|
path === 'output.dvi' ||
|
||||||
path === 'output.log' ||
|
path === 'output.log' ||
|
||||||
path === 'output.xdv'
|
path === 'output.xdv' ||
|
||||||
|
path === 'output.stdout' ||
|
||||||
|
path === 'output.stderr'
|
||||||
) {
|
) {
|
||||||
should_delete = true
|
should_delete = true
|
||||||
}
|
}
|
||||||
@@ -240,7 +242,7 @@ module.exports = ResourceWriter = {
|
|||||||
should_delete = true
|
should_delete = true
|
||||||
}
|
}
|
||||||
if (should_delete) {
|
if (should_delete) {
|
||||||
return jobs.push(callback =>
|
return jobs.push((callback) =>
|
||||||
ResourceWriter._deleteFileIfNotDirectory(
|
ResourceWriter._deleteFileIfNotDirectory(
|
||||||
Path.join(basePath, path),
|
Path.join(basePath, path),
|
||||||
callback
|
callback
|
||||||
@@ -301,7 +303,9 @@ module.exports = ResourceWriter = {
|
|||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return fs.mkdir(Path.dirname(path), { recursive: true }, function(error) {
|
return fs.mkdir(Path.dirname(path), { recursive: true }, function (
|
||||||
|
error
|
||||||
|
) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ module.exports = SafeReader = {
|
|||||||
}
|
}
|
||||||
return callback(null, ...Array.from(result))
|
return callback(null, ...Array.from(result))
|
||||||
})
|
})
|
||||||
const buff = new Buffer(size, 0) // fill with zeros
|
const buff = Buffer.alloc(size) // fills with zeroes by default
|
||||||
return fs.read(fd, buff, 0, buff.length, 0, function (
|
return fs.read(fd, buff, 0, buff.length, 0, function (
|
||||||
err,
|
err,
|
||||||
bytesRead,
|
bytesRead,
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ module.exports = ForbidSymlinks = function(staticFn, root, options) {
|
|||||||
const basePath = Path.resolve(root)
|
const basePath = Path.resolve(root)
|
||||||
return function (req, res, next) {
|
return function (req, res, next) {
|
||||||
let file, project_id, result
|
let file, project_id, result
|
||||||
const path = __guard__(url.parse(req.url), x => x.pathname)
|
const path = __guard__(url.parse(req.url), (x) => x.pathname)
|
||||||
// check that the path is of the form /project_id_or_name/path/to/file.log
|
// check that the path is of the form /project_id_or_name/path/to/file.log
|
||||||
if ((result = path.match(/^\/?([a-zA-Z0-9_-]+)\/(.*)/))) {
|
if ((result = path.match(/^\/?([a-zA-Z0-9_-]+)\/(.*)/))) {
|
||||||
project_id = result[1]
|
project_id = result[1]
|
||||||
|
|||||||
@@ -42,7 +42,10 @@ module.exports = TikzManager = {
|
|||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return SafeReader.readFile(path, 65536, 'utf8', function(error, content) {
|
return SafeReader.readFile(path, 65536, 'utf8', function (
|
||||||
|
error,
|
||||||
|
content
|
||||||
|
) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,8 +60,8 @@ module.exports = UrlCache = {
|
|||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
const jobs = Array.from(urls || []).map(url =>
|
const jobs = Array.from(urls || []).map((url) =>
|
||||||
(url => callback =>
|
((url) => (callback) =>
|
||||||
UrlCache._clearUrlFromCache(project_id, url, function (error) {
|
UrlCache._clearUrlFromCache(project_id, url, function (error) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
logger.error(
|
logger.error(
|
||||||
@@ -95,10 +95,10 @@ module.exports = UrlCache = {
|
|||||||
}
|
}
|
||||||
if (needsDownloading) {
|
if (needsDownloading) {
|
||||||
logger.log({ url, lastModified }, 'downloading URL')
|
logger.log({ url, lastModified }, 'downloading URL')
|
||||||
return UrlFetcher.pipeUrlToFile(
|
return UrlFetcher.pipeUrlToFileWithRetry(
|
||||||
url,
|
url,
|
||||||
UrlCache._cacheFilePathForUrl(project_id, url),
|
UrlCache._cacheFilePathForUrl(project_id, url),
|
||||||
error => {
|
(error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
@@ -106,7 +106,7 @@ module.exports = UrlCache = {
|
|||||||
project_id,
|
project_id,
|
||||||
url,
|
url,
|
||||||
lastModified,
|
lastModified,
|
||||||
error => {
|
(error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
@@ -153,14 +153,7 @@ module.exports = UrlCache = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
_cacheFileNameForUrl(project_id, url) {
|
_cacheFileNameForUrl(project_id, url) {
|
||||||
return (
|
return project_id + ':' + crypto.createHash('md5').update(url).digest('hex')
|
||||||
project_id +
|
|
||||||
':' +
|
|
||||||
crypto
|
|
||||||
.createHash('md5')
|
|
||||||
.update(url)
|
|
||||||
.digest('hex')
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
|
|
||||||
_cacheFilePathForUrl(project_id, url) {
|
_cacheFilePathForUrl(project_id, url) {
|
||||||
@@ -197,7 +190,9 @@ module.exports = UrlCache = {
|
|||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return UrlCache._deleteUrlCacheFromDisk(project_id, url, function(error) {
|
return UrlCache._deleteUrlCacheFromDisk(project_id, url, function (
|
||||||
|
error
|
||||||
|
) {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
@@ -226,9 +221,9 @@ module.exports = UrlCache = {
|
|||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error, urlDetails) {}
|
callback = function (error, urlDetails) {}
|
||||||
}
|
}
|
||||||
const job = cb =>
|
const job = (cb) =>
|
||||||
db.UrlCache.findOne({ where: { url, project_id } })
|
db.UrlCache.findOne({ where: { url, project_id } })
|
||||||
.then(urlDetails => cb(null, urlDetails))
|
.then((urlDetails) => cb(null, urlDetails))
|
||||||
.error(cb)
|
.error(cb)
|
||||||
return dbQueue.queue.push(job, callback)
|
return dbQueue.queue.push(job, callback)
|
||||||
},
|
},
|
||||||
@@ -237,7 +232,7 @@ module.exports = UrlCache = {
|
|||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error) {}
|
callback = function (error) {}
|
||||||
}
|
}
|
||||||
const job = cb =>
|
const job = (cb) =>
|
||||||
db.UrlCache.findOrCreate({ where: { url, project_id } })
|
db.UrlCache.findOrCreate({ where: { url, project_id } })
|
||||||
.spread((urlDetails, created) =>
|
.spread((urlDetails, created) =>
|
||||||
urlDetails
|
urlDetails
|
||||||
@@ -253,7 +248,7 @@ module.exports = UrlCache = {
|
|||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error) {}
|
callback = function (error) {}
|
||||||
}
|
}
|
||||||
const job = cb =>
|
const job = (cb) =>
|
||||||
db.UrlCache.destroy({ where: { url, project_id } })
|
db.UrlCache.destroy({ where: { url, project_id } })
|
||||||
.then(() => cb(null))
|
.then(() => cb(null))
|
||||||
.error(cb)
|
.error(cb)
|
||||||
@@ -264,12 +259,12 @@ module.exports = UrlCache = {
|
|||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error, urls) {}
|
callback = function (error, urls) {}
|
||||||
}
|
}
|
||||||
const job = cb =>
|
const job = (cb) =>
|
||||||
db.UrlCache.findAll({ where: { project_id } })
|
db.UrlCache.findAll({ where: { project_id } })
|
||||||
.then(urlEntries =>
|
.then((urlEntries) =>
|
||||||
cb(
|
cb(
|
||||||
null,
|
null,
|
||||||
urlEntries.map(entry => entry.url)
|
urlEntries.map((entry) => entry.url)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
.error(cb)
|
.error(cb)
|
||||||
|
|||||||
@@ -18,10 +18,18 @@ const fs = require('fs')
|
|||||||
const logger = require('logger-sharelatex')
|
const logger = require('logger-sharelatex')
|
||||||
const settings = require('settings-sharelatex')
|
const settings = require('settings-sharelatex')
|
||||||
const URL = require('url')
|
const URL = require('url')
|
||||||
|
const async = require('async')
|
||||||
|
|
||||||
const oneMinute = 60 * 1000
|
const oneMinute = 60 * 1000
|
||||||
|
|
||||||
module.exports = UrlFetcher = {
|
module.exports = UrlFetcher = {
|
||||||
|
pipeUrlToFileWithRetry(url, filePath, callback) {
|
||||||
|
const doDownload = function (cb) {
|
||||||
|
UrlFetcher.pipeUrlToFile(url, filePath, cb)
|
||||||
|
}
|
||||||
|
async.retry(3, doDownload, callback)
|
||||||
|
},
|
||||||
|
|
||||||
pipeUrlToFile(url, filePath, _callback) {
|
pipeUrlToFile(url, filePath, _callback) {
|
||||||
if (_callback == null) {
|
if (_callback == null) {
|
||||||
_callback = function (error) {}
|
_callback = function (error) {}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
*/
|
*/
|
||||||
const Sequelize = require('sequelize')
|
const Sequelize = require('sequelize')
|
||||||
const Settings = require('settings-sharelatex')
|
const Settings = require('settings-sharelatex')
|
||||||
const _ = require('underscore')
|
const _ = require('lodash')
|
||||||
const logger = require('logger-sharelatex')
|
const logger = require('logger-sharelatex')
|
||||||
|
|
||||||
const options = _.extend({ logging: false }, Settings.mysql.clsi)
|
const options = _.extend({ logging: false }, Settings.mysql.clsi)
|
||||||
@@ -62,6 +62,6 @@ module.exports = {
|
|||||||
return sequelize
|
return sequelize
|
||||||
.sync()
|
.sync()
|
||||||
.then(() => logger.log('db sync complete'))
|
.then(() => logger.log('db sync complete'))
|
||||||
.catch(err => console.log(err, 'error syncing'))
|
.catch((err) => console.log(err, 'error syncing'))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
clsi
|
clsi
|
||||||
--acceptance-creds=None
|
|
||||||
--data-dirs=cache,compiles,db
|
--data-dirs=cache,compiles,db
|
||||||
--dependencies=
|
--dependencies=
|
||||||
--docker-repos=gcr.io/overleaf-ops
|
--docker-repos=gcr.io/overleaf-ops
|
||||||
--env-add=
|
--env-add=
|
||||||
--env-pass-through=TEXLIVE_IMAGE
|
--env-pass-through=TEXLIVE_IMAGE
|
||||||
--language=es
|
--node-version=10.22.1
|
||||||
--node-version=10.19.0
|
|
||||||
--public-repo=True
|
--public-repo=True
|
||||||
--script-version=2.1.0
|
--script-version=3.3.3
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ module.exports = {
|
|||||||
username: 'clsi',
|
username: 'clsi',
|
||||||
dialect: 'sqlite',
|
dialect: 'sqlite',
|
||||||
storage:
|
storage:
|
||||||
process.env.SQLITE_PATH || Path.resolve(__dirname + '/../db/db.sqlite'),
|
process.env.SQLITE_PATH || Path.resolve(__dirname, '../db/db.sqlite'),
|
||||||
pool: {
|
pool: {
|
||||||
max: 1,
|
max: 1,
|
||||||
min: 1
|
min: 1
|
||||||
@@ -26,10 +26,10 @@ module.exports = {
|
|||||||
parseInt(process.env.PROCESS_LIFE_SPAN_LIMIT_MS) || 60 * 60 * 24 * 1000 * 2,
|
parseInt(process.env.PROCESS_LIFE_SPAN_LIMIT_MS) || 60 * 60 * 24 * 1000 * 2,
|
||||||
|
|
||||||
path: {
|
path: {
|
||||||
compilesDir: Path.resolve(__dirname + '/../compiles'),
|
compilesDir: Path.resolve(__dirname, '../compiles'),
|
||||||
clsiCacheDir: Path.resolve(__dirname + '/../cache'),
|
clsiCacheDir: Path.resolve(__dirname, '../cache'),
|
||||||
synctexBaseDir(project_id) {
|
synctexBaseDir(projectId) {
|
||||||
return Path.join(this.compilesDir, project_id)
|
return Path.join(this.compilesDir, projectId)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -57,13 +57,25 @@ module.exports = {
|
|||||||
parallelSqlQueryLimit: process.env.FILESTORE_PARALLEL_SQL_QUERY_LIMIT || 1,
|
parallelSqlQueryLimit: process.env.FILESTORE_PARALLEL_SQL_QUERY_LIMIT || 1,
|
||||||
filestoreDomainOveride: process.env.FILESTORE_DOMAIN_OVERRIDE,
|
filestoreDomainOveride: process.env.FILESTORE_DOMAIN_OVERRIDE,
|
||||||
texliveImageNameOveride: process.env.TEX_LIVE_IMAGE_NAME_OVERRIDE,
|
texliveImageNameOveride: process.env.TEX_LIVE_IMAGE_NAME_OVERRIDE,
|
||||||
|
texliveOpenoutAny: process.env.TEXLIVE_OPENOUT_ANY,
|
||||||
sentry: {
|
sentry: {
|
||||||
dsn: process.env.SENTRY_DSN
|
dsn: process.env.SENTRY_DSN
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (process.env.ALLOWED_COMPILE_GROUPS) {
|
||||||
|
try {
|
||||||
|
module.exports.allowedCompileGroups = process.env.ALLOWED_COMPILE_GROUPS.split(
|
||||||
|
' '
|
||||||
|
)
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error, 'could not apply allowed compile group setting')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (process.env.DOCKER_RUNNER) {
|
if (process.env.DOCKER_RUNNER) {
|
||||||
let seccomp_profile_path
|
let seccompProfilePath
|
||||||
module.exports.clsi = {
|
module.exports.clsi = {
|
||||||
dockerRunner: process.env.DOCKER_RUNNER === 'true',
|
dockerRunner: process.env.DOCKER_RUNNER === 'true',
|
||||||
docker: {
|
docker: {
|
||||||
@@ -71,28 +83,61 @@ if (process.env.DOCKER_RUNNER) {
|
|||||||
image:
|
image:
|
||||||
process.env.TEXLIVE_IMAGE || 'quay.io/sharelatex/texlive-full:2017.1',
|
process.env.TEXLIVE_IMAGE || 'quay.io/sharelatex/texlive-full:2017.1',
|
||||||
env: {
|
env: {
|
||||||
HOME: process.env.TEXLIVE_HOME || '/tmp',
|
HOME: '/tmp'
|
||||||
TMPDIR: process.env.TEXLIVE_TMPDIR || '/tmp'
|
|
||||||
},
|
},
|
||||||
socketPath: '/var/run/docker.sock',
|
socketPath: '/var/run/docker.sock',
|
||||||
user: process.env.TEXLIVE_IMAGE_USER || 'tex'
|
user: process.env.TEXLIVE_IMAGE_USER || 'tex'
|
||||||
},
|
},
|
||||||
|
optimiseInDocker: true,
|
||||||
expireProjectAfterIdleMs: 24 * 60 * 60 * 1000,
|
expireProjectAfterIdleMs: 24 * 60 * 60 * 1000,
|
||||||
checkProjectsIntervalMs: 10 * 60 * 1000
|
checkProjectsIntervalMs: 10 * 60 * 1000
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
seccomp_profile_path = Path.resolve(
|
// Override individual docker settings using path-based keys, e.g.:
|
||||||
__dirname + '/../seccomp/clsi-profile.json'
|
// compileGroupDockerConfigs = {
|
||||||
|
// priority: { 'HostConfig.CpuShares': 100 }
|
||||||
|
// beta: { 'dotted.path.here', 'value'}
|
||||||
|
// }
|
||||||
|
const compileGroupConfig = JSON.parse(
|
||||||
|
process.env.COMPILE_GROUP_DOCKER_CONFIGS || '{}'
|
||||||
)
|
)
|
||||||
module.exports.clsi.docker.seccomp_profile = JSON.stringify(
|
// Automatically clean up wordcount and synctex containers
|
||||||
JSON.parse(require('fs').readFileSync(seccomp_profile_path))
|
const defaultCompileGroupConfig = {
|
||||||
|
wordcount: { 'HostConfig.AutoRemove': true },
|
||||||
|
synctex: { 'HostConfig.AutoRemove': true }
|
||||||
|
}
|
||||||
|
module.exports.clsi.docker.compileGroupConfig = Object.assign(
|
||||||
|
defaultCompileGroupConfig,
|
||||||
|
compileGroupConfig
|
||||||
)
|
)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(
|
console.error(error, 'could not apply compile group docker configs')
|
||||||
error,
|
process.exit(1)
|
||||||
`could not load seccom profile from ${seccomp_profile_path}`
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
seccompProfilePath = Path.resolve(__dirname, '../seccomp/clsi-profile.json')
|
||||||
|
module.exports.clsi.docker.seccomp_profile = JSON.stringify(
|
||||||
|
JSON.parse(require('fs').readFileSync(seccompProfilePath))
|
||||||
)
|
)
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
error,
|
||||||
|
`could not load seccomp profile from ${seccompProfilePath}`
|
||||||
|
)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.env.ALLOWED_IMAGES) {
|
||||||
|
try {
|
||||||
|
module.exports.clsi.docker.allowedImages = process.env.ALLOWED_IMAGES.split(
|
||||||
|
' '
|
||||||
|
)
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error, 'could not apply allowed images setting')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.path.synctexBaseDir = () => '/compile'
|
module.exports.path.synctexBaseDir = () => '/compile'
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ version: "2.3"
|
|||||||
services:
|
services:
|
||||||
dev:
|
dev:
|
||||||
environment:
|
environment:
|
||||||
|
ALLOWED_IMAGES: "quay.io/sharelatex/texlive-full:2017.1"
|
||||||
TEXLIVE_IMAGE: quay.io/sharelatex/texlive-full:2017.1
|
TEXLIVE_IMAGE: quay.io/sharelatex/texlive-full:2017.1
|
||||||
TEXLIVE_IMAGE_USER: "tex"
|
TEXLIVE_IMAGE_USER: "tex"
|
||||||
SHARELATEX_CONFIG: /app/config/settings.defaults.coffee
|
SHARELATEX_CONFIG: /app/config/settings.defaults.coffee
|
||||||
@@ -18,6 +19,7 @@ services:
|
|||||||
|
|
||||||
ci:
|
ci:
|
||||||
environment:
|
environment:
|
||||||
|
ALLOWED_IMAGES: ${TEXLIVE_IMAGE}
|
||||||
TEXLIVE_IMAGE: quay.io/sharelatex/texlive-full:2017.1
|
TEXLIVE_IMAGE: quay.io/sharelatex/texlive-full:2017.1
|
||||||
TEXLIVE_IMAGE_USER: "tex"
|
TEXLIVE_IMAGE_USER: "tex"
|
||||||
SHARELATEX_CONFIG: /app/config/settings.defaults.coffee
|
SHARELATEX_CONFIG: /app/config/settings.defaults.coffee
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ services:
|
|||||||
command: npm run test:unit:_run
|
command: npm run test:unit:_run
|
||||||
environment:
|
environment:
|
||||||
NODE_ENV: test
|
NODE_ENV: test
|
||||||
|
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||||
|
|
||||||
|
|
||||||
test_acceptance:
|
test_acceptance:
|
||||||
@@ -25,6 +26,7 @@ services:
|
|||||||
POSTGRES_HOST: postgres
|
POSTGRES_HOST: postgres
|
||||||
MOCHA_GREP: ${MOCHA_GREP}
|
MOCHA_GREP: ${MOCHA_GREP}
|
||||||
NODE_ENV: test
|
NODE_ENV: test
|
||||||
|
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||||
TEXLIVE_IMAGE:
|
TEXLIVE_IMAGE:
|
||||||
command: npm run test:acceptance:_run
|
command: npm run test:acceptance:_run
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
MOCHA_GREP: ${MOCHA_GREP}
|
MOCHA_GREP: ${MOCHA_GREP}
|
||||||
NODE_ENV: test
|
NODE_ENV: test
|
||||||
command: npm run test:unit
|
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||||
|
command: npm run --silent test:unit
|
||||||
|
|
||||||
test_acceptance:
|
test_acceptance:
|
||||||
build:
|
build:
|
||||||
@@ -35,5 +36,6 @@ services:
|
|||||||
MOCHA_GREP: ${MOCHA_GREP}
|
MOCHA_GREP: ${MOCHA_GREP}
|
||||||
LOG_LEVEL: ERROR
|
LOG_LEVEL: ERROR
|
||||||
NODE_ENV: test
|
NODE_ENV: test
|
||||||
command: npm run test:acceptance
|
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||||
|
command: npm run --silent test:acceptance
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,6 @@
|
|||||||
"execMap": {
|
"execMap": {
|
||||||
"js": "npm run start"
|
"js": "npm run start"
|
||||||
},
|
},
|
||||||
|
|
||||||
"watch": [
|
"watch": [
|
||||||
"app/js/",
|
"app/js/",
|
||||||
"app.js",
|
"app.js",
|
||||||
|
|||||||
857
package-lock.json
generated
857
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
11
package.json
11
package.json
@@ -13,7 +13,7 @@
|
|||||||
"test:unit:_run": "mocha --recursive --reporter spec $@ test/unit/js",
|
"test:unit:_run": "mocha --recursive --reporter spec $@ test/unit/js",
|
||||||
"test:unit": "npm run test:unit:_run -- --grep=$MOCHA_GREP",
|
"test:unit": "npm run test:unit:_run -- --grep=$MOCHA_GREP",
|
||||||
"nodemon": "nodemon --config nodemon.json",
|
"nodemon": "nodemon --config nodemon.json",
|
||||||
"lint": "node_modules/.bin/eslint .",
|
"lint": "node_modules/.bin/eslint --max-warnings 0 .",
|
||||||
"format": "node_modules/.bin/prettier-eslint $PWD'/**/*.js' --list-different",
|
"format": "node_modules/.bin/prettier-eslint $PWD'/**/*.js' --list-different",
|
||||||
"format:fix": "node_modules/.bin/prettier-eslint $PWD'/**/*.js' --write"
|
"format:fix": "node_modules/.bin/prettier-eslint $PWD'/**/*.js' --write"
|
||||||
},
|
},
|
||||||
@@ -21,21 +21,22 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"async": "3.2.0",
|
"async": "3.2.0",
|
||||||
"body-parser": "^1.19.0",
|
"body-parser": "^1.19.0",
|
||||||
|
"diskusage": "^1.1.3",
|
||||||
"dockerode": "^3.1.0",
|
"dockerode": "^3.1.0",
|
||||||
"express": "^4.17.1",
|
"express": "^4.17.1",
|
||||||
"fs-extra": "^8.1.0",
|
"fs-extra": "^8.1.0",
|
||||||
"heapdump": "^0.3.15",
|
"heapdump": "^0.3.15",
|
||||||
"lockfile": "^1.0.4",
|
"lockfile": "^1.0.4",
|
||||||
"logger-sharelatex": "^1.9.1",
|
"lodash": "^4.17.20",
|
||||||
|
"logger-sharelatex": "^2.2.0",
|
||||||
"lynx": "0.2.0",
|
"lynx": "0.2.0",
|
||||||
"metrics-sharelatex": "^2.6.0",
|
"metrics-sharelatex": "^2.6.0",
|
||||||
"mysql": "^2.18.1",
|
"mysql": "^2.18.1",
|
||||||
"request": "^2.88.2",
|
"request": "^2.88.2",
|
||||||
"sequelize": "^5.21.5",
|
"sequelize": "^5.21.5",
|
||||||
"settings-sharelatex": "git+https://github.com/sharelatex/settings-sharelatex.git#v1.1.0",
|
"settings-sharelatex": "git+https://github.com/sharelatex/settings-sharelatex.git#v1.1.0",
|
||||||
"smoke-test-sharelatex": "git+https://github.com/sharelatex/smoke-test-sharelatex.git#v0.2.0",
|
|
||||||
"sqlite3": "^4.1.1",
|
"sqlite3": "^4.1.1",
|
||||||
"underscore": "^1.9.2",
|
"underscore": "^1.11.0",
|
||||||
"v8-profiler-node8": "^6.1.1",
|
"v8-profiler-node8": "^6.1.1",
|
||||||
"wrench": "~1.5.9"
|
"wrench": "~1.5.9"
|
||||||
},
|
},
|
||||||
@@ -59,7 +60,7 @@
|
|||||||
"eslint-plugin-react": "^7.19.0",
|
"eslint-plugin-react": "^7.19.0",
|
||||||
"eslint-plugin-standard": "^4.0.1",
|
"eslint-plugin-standard": "^4.0.1",
|
||||||
"mocha": "^7.1.0",
|
"mocha": "^7.1.0",
|
||||||
"prettier": "^1.19.1",
|
"prettier": "^2.0.0",
|
||||||
"prettier-eslint-cli": "^5.0.0",
|
"prettier-eslint-cli": "^5.0.0",
|
||||||
"sandboxed-module": "^2.0.3",
|
"sandboxed-module": "^2.0.3",
|
||||||
"sinon": "~9.0.1",
|
"sinon": "~9.0.1",
|
||||||
|
|||||||
102
test/acceptance/js/AllowedImageNames.js
Normal file
102
test/acceptance/js/AllowedImageNames.js
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
const Client = require('./helpers/Client')
|
||||||
|
const ClsiApp = require('./helpers/ClsiApp')
|
||||||
|
const { expect } = require('chai')
|
||||||
|
|
||||||
|
describe('AllowedImageNames', function () {
|
||||||
|
beforeEach(function (done) {
|
||||||
|
this.project_id = Client.randomId()
|
||||||
|
this.request = {
|
||||||
|
options: {
|
||||||
|
imageName: undefined
|
||||||
|
},
|
||||||
|
resources: [
|
||||||
|
{
|
||||||
|
path: 'main.tex',
|
||||||
|
content: `\
|
||||||
|
\\documentclass{article}
|
||||||
|
\\begin{document}
|
||||||
|
Hello world
|
||||||
|
\\end{document}\
|
||||||
|
`
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
ClsiApp.ensureRunning(done)
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('with a valid name', function () {
|
||||||
|
beforeEach(function (done) {
|
||||||
|
this.request.options.imageName = process.env.TEXLIVE_IMAGE
|
||||||
|
|
||||||
|
Client.compile(this.project_id, this.request, (error, res, body) => {
|
||||||
|
this.error = error
|
||||||
|
this.res = res
|
||||||
|
this.body = body
|
||||||
|
done(error)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
it('should return success', function () {
|
||||||
|
expect(this.res.statusCode).to.equal(200)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return a PDF', function () {
|
||||||
|
let pdf
|
||||||
|
try {
|
||||||
|
pdf = Client.getOutputFile(this.body, 'pdf')
|
||||||
|
} catch (e) {}
|
||||||
|
expect(pdf).to.exist
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('with an invalid name', function () {
|
||||||
|
beforeEach(function (done) {
|
||||||
|
this.request.options.imageName = 'something/evil:1337'
|
||||||
|
Client.compile(this.project_id, this.request, (error, res, body) => {
|
||||||
|
this.error = error
|
||||||
|
this.res = res
|
||||||
|
this.body = body
|
||||||
|
done(error)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
it('should return non success', function () {
|
||||||
|
expect(this.res.statusCode).to.not.equal(200)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should not return a PDF', function () {
|
||||||
|
let pdf
|
||||||
|
try {
|
||||||
|
pdf = Client.getOutputFile(this.body, 'pdf')
|
||||||
|
} catch (e) {}
|
||||||
|
expect(pdf).to.not.exist
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('wordcount', function () {
|
||||||
|
beforeEach(function (done) {
|
||||||
|
Client.compile(this.project_id, this.request, done)
|
||||||
|
})
|
||||||
|
it('should error out with an invalid imageName', function () {
|
||||||
|
Client.wordcountWithImage(
|
||||||
|
this.project_id,
|
||||||
|
'main.tex',
|
||||||
|
'something/evil:1337',
|
||||||
|
(error, result) => {
|
||||||
|
expect(String(error)).to.include('statusCode=400')
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should produce a texcout a valid imageName', function () {
|
||||||
|
Client.wordcountWithImage(
|
||||||
|
this.project_id,
|
||||||
|
'main.tex',
|
||||||
|
process.env.TEXLIVE_IMAGE,
|
||||||
|
(error, result) => {
|
||||||
|
expect(error).to.not.exist
|
||||||
|
expect(result).to.exist
|
||||||
|
expect(result.texcount).to.exist
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -24,7 +24,7 @@ const ChildProcess = require('child_process')
|
|||||||
const ClsiApp = require('./helpers/ClsiApp')
|
const ClsiApp = require('./helpers/ClsiApp')
|
||||||
const logger = require('logger-sharelatex')
|
const logger = require('logger-sharelatex')
|
||||||
const Path = require('path')
|
const Path = require('path')
|
||||||
const fixturePath = path => {
|
const fixturePath = (path) => {
|
||||||
if (path.slice(0, 3) === 'tmp') {
|
if (path.slice(0, 3) === 'tmp') {
|
||||||
return '/tmp/clsi_acceptance_tests' + path.slice(3)
|
return '/tmp/clsi_acceptance_tests' + path.slice(3)
|
||||||
}
|
}
|
||||||
@@ -50,8 +50,8 @@ const convertToPng = function(pdfPath, pngPath, callback) {
|
|||||||
console.log(command)
|
console.log(command)
|
||||||
const convert = ChildProcess.exec(command)
|
const convert = ChildProcess.exec(command)
|
||||||
const stdout = ''
|
const stdout = ''
|
||||||
convert.stdout.on('data', chunk => console.log('STDOUT', chunk.toString()))
|
convert.stdout.on('data', (chunk) => console.log('STDOUT', chunk.toString()))
|
||||||
convert.stderr.on('data', chunk => console.log('STDERR', chunk.toString()))
|
convert.stderr.on('data', (chunk) => console.log('STDERR', chunk.toString()))
|
||||||
return convert.on('exit', () => callback())
|
return convert.on('exit', () => callback())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,11 +66,11 @@ const compare = function(originalPath, generatedPath, callback) {
|
|||||||
)} ${diff_file}`
|
)} ${diff_file}`
|
||||||
)
|
)
|
||||||
let stderr = ''
|
let stderr = ''
|
||||||
proc.stderr.on('data', chunk => (stderr += chunk))
|
proc.stderr.on('data', (chunk) => (stderr += chunk))
|
||||||
return proc.on('exit', () => {
|
return proc.on('exit', () => {
|
||||||
if (stderr.trim() === '0 (0)') {
|
if (stderr.trim() === '0 (0)') {
|
||||||
// remove output diff if test matches expected image
|
// remove output diff if test matches expected image
|
||||||
fs.unlink(diff_file, err => {
|
fs.unlink(diff_file, (err) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
throw err
|
throw err
|
||||||
}
|
}
|
||||||
@@ -89,8 +89,8 @@ const checkPdfInfo = function(pdfPath, callback) {
|
|||||||
}
|
}
|
||||||
const proc = ChildProcess.exec(`pdfinfo ${fixturePath(pdfPath)}`)
|
const proc = ChildProcess.exec(`pdfinfo ${fixturePath(pdfPath)}`)
|
||||||
let stdout = ''
|
let stdout = ''
|
||||||
proc.stdout.on('data', chunk => (stdout += chunk))
|
proc.stdout.on('data', (chunk) => (stdout += chunk))
|
||||||
proc.stderr.on('data', chunk => console.log('STDERR', chunk.toString()))
|
proc.stderr.on('data', (chunk) => console.log('STDERR', chunk.toString()))
|
||||||
return proc.on('exit', () => {
|
return proc.on('exit', () => {
|
||||||
if (stdout.match(/Optimized:\s+yes/)) {
|
if (stdout.match(/Optimized:\s+yes/)) {
|
||||||
return callback(null, true)
|
return callback(null, true)
|
||||||
@@ -136,14 +136,14 @@ const comparePdf = function(project_id, example_dir, callback) {
|
|||||||
return convertToPng(
|
return convertToPng(
|
||||||
`tmp/${project_id}.pdf`,
|
`tmp/${project_id}.pdf`,
|
||||||
`tmp/${project_id}-generated.png`,
|
`tmp/${project_id}-generated.png`,
|
||||||
error => {
|
(error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
return convertToPng(
|
return convertToPng(
|
||||||
`examples/${example_dir}/output.pdf`,
|
`examples/${example_dir}/output.pdf`,
|
||||||
`tmp/${project_id}-source.png`,
|
`tmp/${project_id}-source.png`,
|
||||||
error => {
|
(error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
@@ -163,7 +163,7 @@ const comparePdf = function(project_id, example_dir, callback) {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
return compareMultiplePages(project_id, error => {
|
return compareMultiplePages(project_id, (error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
@@ -178,7 +178,12 @@ const comparePdf = function(project_id, example_dir, callback) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const downloadAndComparePdf = function(project_id, example_dir, url, callback) {
|
const downloadAndComparePdf = function (
|
||||||
|
project_id,
|
||||||
|
example_dir,
|
||||||
|
url,
|
||||||
|
callback
|
||||||
|
) {
|
||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error) {}
|
callback = function (error) {}
|
||||||
}
|
}
|
||||||
@@ -212,8 +217,9 @@ describe('Example Documents', function() {
|
|||||||
fsExtra.remove(fixturePath('tmp'), done)
|
fsExtra.remove(fixturePath('tmp'), done)
|
||||||
})
|
})
|
||||||
|
|
||||||
return Array.from(fs.readdirSync(fixturePath('examples'))).map(example_dir =>
|
return Array.from(fs.readdirSync(fixturePath('examples'))).map(
|
||||||
(example_dir =>
|
(example_dir) =>
|
||||||
|
((example_dir) =>
|
||||||
describe(example_dir, function () {
|
describe(example_dir, function () {
|
||||||
before(function () {
|
before(function () {
|
||||||
return (this.project_id = Client.randomId() + '_' + example_dir)
|
return (this.project_id = Client.randomId() + '_' + example_dir)
|
||||||
@@ -231,10 +237,16 @@ describe('Example Documents', function() {
|
|||||||
error ||
|
error ||
|
||||||
__guard__(
|
__guard__(
|
||||||
body != null ? body.compile : undefined,
|
body != null ? body.compile : undefined,
|
||||||
x => x.status
|
(x) => x.status
|
||||||
) === 'failure'
|
) === 'failure'
|
||||||
) {
|
) {
|
||||||
console.log('DEBUG: error', error, 'body', JSON.stringify(body))
|
console.log(
|
||||||
|
'DEBUG: error',
|
||||||
|
error,
|
||||||
|
'body',
|
||||||
|
JSON.stringify(body)
|
||||||
|
)
|
||||||
|
return done(new Error('Compile failed'))
|
||||||
}
|
}
|
||||||
const pdf = Client.getOutputFile(body, 'pdf')
|
const pdf = Client.getOutputFile(body, 'pdf')
|
||||||
return downloadAndComparePdf(
|
return downloadAndComparePdf(
|
||||||
@@ -259,10 +271,16 @@ describe('Example Documents', function() {
|
|||||||
error ||
|
error ||
|
||||||
__guard__(
|
__guard__(
|
||||||
body != null ? body.compile : undefined,
|
body != null ? body.compile : undefined,
|
||||||
x => x.status
|
(x) => x.status
|
||||||
) === 'failure'
|
) === 'failure'
|
||||||
) {
|
) {
|
||||||
console.log('DEBUG: error', error, 'body', JSON.stringify(body))
|
console.log(
|
||||||
|
'DEBUG: error',
|
||||||
|
error,
|
||||||
|
'body',
|
||||||
|
JSON.stringify(body)
|
||||||
|
)
|
||||||
|
return done(new Error('Compile failed'))
|
||||||
}
|
}
|
||||||
const pdf = Client.getOutputFile(body, 'pdf')
|
const pdf = Client.getOutputFile(body, 'pdf')
|
||||||
return downloadAndComparePdf(
|
return downloadAndComparePdf(
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ Hello world
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
return describe('from pdf to code', function() {
|
describe('from pdf to code', function () {
|
||||||
return it('should return the correct location', function (done) {
|
return it('should return the correct location', function (done) {
|
||||||
return Client.syncFromPdf(
|
return Client.syncFromPdf(
|
||||||
this.project_id,
|
this.project_id,
|
||||||
@@ -88,4 +88,104 @@ Hello world
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('when the project directory is not available', function () {
|
||||||
|
before(function () {
|
||||||
|
this.other_project_id = Client.randomId()
|
||||||
|
})
|
||||||
|
describe('from code to pdf', function () {
|
||||||
|
it('should return a 404 response', function (done) {
|
||||||
|
return Client.syncFromCode(
|
||||||
|
this.other_project_id,
|
||||||
|
'main.tex',
|
||||||
|
3,
|
||||||
|
5,
|
||||||
|
(error, body) => {
|
||||||
|
if (error != null) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
expect(body).to.equal('Not Found')
|
||||||
|
return done()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
describe('from pdf to code', function () {
|
||||||
|
it('should return a 404 response', function (done) {
|
||||||
|
return Client.syncFromPdf(
|
||||||
|
this.other_project_id,
|
||||||
|
1,
|
||||||
|
100,
|
||||||
|
200,
|
||||||
|
(error, body) => {
|
||||||
|
if (error != null) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
expect(body).to.equal('Not Found')
|
||||||
|
return done()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('when the synctex file is not available', function () {
|
||||||
|
before(function (done) {
|
||||||
|
this.broken_project_id = Client.randomId()
|
||||||
|
const content = 'this is not valid tex' // not a valid tex file
|
||||||
|
this.request = {
|
||||||
|
resources: [
|
||||||
|
{
|
||||||
|
path: 'main.tex',
|
||||||
|
content
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
Client.compile(
|
||||||
|
this.broken_project_id,
|
||||||
|
this.request,
|
||||||
|
(error, res, body) => {
|
||||||
|
this.error = error
|
||||||
|
this.res = res
|
||||||
|
this.body = body
|
||||||
|
return done()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('from code to pdf', function () {
|
||||||
|
it('should return a 404 response', function (done) {
|
||||||
|
return Client.syncFromCode(
|
||||||
|
this.broken_project_id,
|
||||||
|
'main.tex',
|
||||||
|
3,
|
||||||
|
5,
|
||||||
|
(error, body) => {
|
||||||
|
if (error != null) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
expect(body).to.equal('Not Found')
|
||||||
|
return done()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
describe('from pdf to code', function () {
|
||||||
|
it('should return a 404 response', function (done) {
|
||||||
|
return Client.syncFromPdf(
|
||||||
|
this.broken_project_id,
|
||||||
|
1,
|
||||||
|
100,
|
||||||
|
200,
|
||||||
|
(error, body) => {
|
||||||
|
if (error != null) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
expect(body).to.equal('Not Found')
|
||||||
|
return done()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ describe('Timed out compile', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
return it('should return the log output file name', function () {
|
return it('should return the log output file name', function () {
|
||||||
const outputFilePaths = this.body.compile.outputFiles.map(x => x.path)
|
const outputFilePaths = this.body.compile.outputFiles.map((x) => x.path)
|
||||||
return outputFilePaths.should.include('output.log')
|
return outputFilePaths.should.include('output.log')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -11,7 +11,6 @@
|
|||||||
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
|
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
|
||||||
*/
|
*/
|
||||||
const Client = require('./helpers/Client')
|
const Client = require('./helpers/Client')
|
||||||
const request = require('request')
|
|
||||||
require('chai').should()
|
require('chai').should()
|
||||||
const sinon = require('sinon')
|
const sinon = require('sinon')
|
||||||
const ClsiApp = require('./helpers/ClsiApp')
|
const ClsiApp = require('./helpers/ClsiApp')
|
||||||
@@ -36,9 +35,7 @@ const Server = {
|
|||||||
getFile() {},
|
getFile() {},
|
||||||
|
|
||||||
randomId() {
|
randomId() {
|
||||||
return Math.random()
|
return Math.random().toString(16).slice(2)
|
||||||
.toString(16)
|
|
||||||
.slice(2)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -339,7 +336,7 @@ describe('Url Caching', function() {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
return Client.compile(this.project_id, this.request, error => {
|
return Client.compile(this.project_id, this.request, (error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,9 +23,7 @@ module.exports = Client = {
|
|||||||
host: Settings.apis.clsi.url,
|
host: Settings.apis.clsi.url,
|
||||||
|
|
||||||
randomId() {
|
randomId() {
|
||||||
return Math.random()
|
return Math.random().toString(16).slice(2)
|
||||||
.toString(16)
|
|
||||||
.slice(2)
|
|
||||||
},
|
},
|
||||||
|
|
||||||
compile(project_id, data, callback) {
|
compile(project_id, data, callback) {
|
||||||
@@ -64,7 +62,7 @@ module.exports = Client = {
|
|||||||
const app = express()
|
const app = express()
|
||||||
app.use(express.static(directory))
|
app.use(express.static(directory))
|
||||||
console.log('starting test server on', port, host)
|
console.log('starting test server on', port, host)
|
||||||
return app.listen(port, host).on('error', error => {
|
return app.listen(port, host).on('error', (error) => {
|
||||||
console.error('error starting server:', error.message)
|
console.error('error starting server:', error.message)
|
||||||
return process.exit(1)
|
return process.exit(1)
|
||||||
})
|
})
|
||||||
@@ -81,13 +79,14 @@ module.exports = Client = {
|
|||||||
file,
|
file,
|
||||||
line,
|
line,
|
||||||
column
|
column
|
||||||
}
|
},
|
||||||
|
json: true
|
||||||
},
|
},
|
||||||
(error, response, body) => {
|
(error, response, body) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return callback(null, JSON.parse(body))
|
return callback(null, body)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@@ -103,13 +102,14 @@ module.exports = Client = {
|
|||||||
page,
|
page,
|
||||||
h,
|
h,
|
||||||
v
|
v
|
||||||
}
|
},
|
||||||
|
json: true
|
||||||
},
|
},
|
||||||
(error, response, body) => {
|
(error, response, body) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
return callback(null, JSON.parse(body))
|
return callback(null, body)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@@ -128,7 +128,7 @@ module.exports = Client = {
|
|||||||
entities = entities.concat(
|
entities = entities.concat(
|
||||||
fs
|
fs
|
||||||
.readdirSync(`${baseDirectory}/${directory}/${entity}`)
|
.readdirSync(`${baseDirectory}/${directory}/${entity}`)
|
||||||
.map(subEntity => {
|
.map((subEntity) => {
|
||||||
if (subEntity === 'main.tex') {
|
if (subEntity === 'main.tex') {
|
||||||
rootResourcePath = `${entity}/${subEntity}`
|
rootResourcePath = `${entity}/${subEntity}`
|
||||||
}
|
}
|
||||||
@@ -187,6 +187,11 @@ module.exports = Client = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
wordcount(project_id, file, callback) {
|
wordcount(project_id, file, callback) {
|
||||||
|
const image = undefined
|
||||||
|
Client.wordcountWithImage(project_id, file, image, callback)
|
||||||
|
},
|
||||||
|
|
||||||
|
wordcountWithImage(project_id, file, image, callback) {
|
||||||
if (callback == null) {
|
if (callback == null) {
|
||||||
callback = function (error, pdfPositions) {}
|
callback = function (error, pdfPositions) {}
|
||||||
}
|
}
|
||||||
@@ -194,6 +199,7 @@ module.exports = Client = {
|
|||||||
{
|
{
|
||||||
url: `${this.host}/project/${project_id}/wordcount`,
|
url: `${this.host}/project/${project_id}/wordcount`,
|
||||||
qs: {
|
qs: {
|
||||||
|
image,
|
||||||
file
|
file
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -201,6 +207,9 @@ module.exports = Client = {
|
|||||||
if (error != null) {
|
if (error != null) {
|
||||||
return callback(error)
|
return callback(error)
|
||||||
}
|
}
|
||||||
|
if (response.statusCode !== 200) {
|
||||||
|
return callback(new Error(`statusCode=${response.statusCode}`))
|
||||||
|
}
|
||||||
return callback(null, JSON.parse(body))
|
return callback(null, JSON.parse(body))
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -35,10 +35,10 @@ module.exports = {
|
|||||||
return app.listen(
|
return app.listen(
|
||||||
__guard__(
|
__guard__(
|
||||||
Settings.internal != null ? Settings.internal.clsi : undefined,
|
Settings.internal != null ? Settings.internal.clsi : undefined,
|
||||||
x => x.port
|
(x) => x.port
|
||||||
),
|
),
|
||||||
'localhost',
|
'localhost',
|
||||||
error => {
|
(error) => {
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,11 +13,11 @@ const request = require('request')
|
|||||||
const Settings = require('settings-sharelatex')
|
const Settings = require('settings-sharelatex')
|
||||||
const async = require('async')
|
const async = require('async')
|
||||||
const fs = require('fs')
|
const fs = require('fs')
|
||||||
const _ = require('underscore')
|
const _ = require('lodash')
|
||||||
const concurentCompiles = 5
|
const concurentCompiles = 5
|
||||||
const totalCompiles = 50
|
const totalCompiles = 50
|
||||||
|
|
||||||
const buildUrl = path =>
|
const buildUrl = (path) =>
|
||||||
`http://${Settings.internal.clsi.host}:${Settings.internal.clsi.port}/${path}`
|
`http://${Settings.internal.clsi.host}:${Settings.internal.clsi.port}/${path}`
|
||||||
|
|
||||||
const mainTexContent = fs.readFileSync('./bulk.tex', 'utf-8')
|
const mainTexContent = fs.readFileSync('./bulk.tex', 'utf-8')
|
||||||
@@ -74,12 +74,12 @@ ${bodyContent}
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const jobs = _.map(__range__(1, totalCompiles, true), i => cb =>
|
const jobs = _.map(__range__(1, totalCompiles, true), (i) => (cb) =>
|
||||||
makeRequest(i, cb)
|
makeRequest(i, cb)
|
||||||
)
|
)
|
||||||
|
|
||||||
const startTime = new Date()
|
const startTime = new Date()
|
||||||
async.parallelLimit(jobs, concurentCompiles, err => {
|
async.parallelLimit(jobs, concurentCompiles, (err) => {
|
||||||
if (err != null) {
|
if (err != null) {
|
||||||
console.error(err)
|
console.error(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,40 @@
|
|||||||
/* eslint-disable
|
|
||||||
no-unused-vars,
|
|
||||||
*/
|
|
||||||
// TODO: This file was created by bulk-decaffeinate.
|
|
||||||
// Fix any style issues and re-enable lint.
|
|
||||||
/*
|
|
||||||
* decaffeinate suggestions:
|
|
||||||
* DS101: Remove unnecessary use of Array.from
|
|
||||||
* DS102: Remove unnecessary code created because of implicit returns
|
|
||||||
* DS207: Consider shorter variations of null checks
|
|
||||||
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
|
|
||||||
*/
|
|
||||||
const chai = require('chai')
|
|
||||||
if (Object.prototype.should == null) {
|
|
||||||
chai.should()
|
|
||||||
}
|
|
||||||
const { expect } = chai
|
|
||||||
const request = require('request')
|
const request = require('request')
|
||||||
const Settings = require('settings-sharelatex')
|
const Settings = require('settings-sharelatex')
|
||||||
|
|
||||||
const buildUrl = path =>
|
const buildUrl = (path) =>
|
||||||
`http://${Settings.internal.clsi.host}:${Settings.internal.clsi.port}/${path}`
|
`http://${Settings.internal.clsi.host}:${Settings.internal.clsi.port}/${path}`
|
||||||
|
|
||||||
const url = buildUrl(`project/smoketest-${process.pid}/compile`)
|
const url = buildUrl(`project/smoketest-${process.pid}/compile`)
|
||||||
|
|
||||||
describe('Running a compile', function() {
|
module.exports = {
|
||||||
before(function(done) {
|
sendNewResult(res) {
|
||||||
return request.post(
|
this._run((error) => this._sendResponse(res, error))
|
||||||
|
},
|
||||||
|
sendLastResult(res) {
|
||||||
|
this._sendResponse(res, this._lastError)
|
||||||
|
},
|
||||||
|
triggerRun(cb) {
|
||||||
|
this._run((error) => {
|
||||||
|
this._lastError = error
|
||||||
|
cb(error)
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
_lastError: new Error('SmokeTestsPending'),
|
||||||
|
_sendResponse(res, error) {
|
||||||
|
let code, body
|
||||||
|
if (error) {
|
||||||
|
code = 500
|
||||||
|
body = error.message
|
||||||
|
} else {
|
||||||
|
code = 200
|
||||||
|
body = 'OK'
|
||||||
|
}
|
||||||
|
res.contentType('text/plain')
|
||||||
|
res.status(code).send(body)
|
||||||
|
},
|
||||||
|
_run(done) {
|
||||||
|
request.post(
|
||||||
{
|
{
|
||||||
url,
|
url,
|
||||||
json: {
|
json: {
|
||||||
@@ -72,29 +81,22 @@ describe('Running a compile', function() {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
(error, response, body) => {
|
(error, response, body) => {
|
||||||
this.error = error
|
if (error) return done(error)
|
||||||
this.response = response
|
if (!body || !body.compile || !body.compile.outputFiles) {
|
||||||
this.body = body
|
return done(new Error('response payload incomplete'))
|
||||||
return done()
|
}
|
||||||
|
|
||||||
|
let pdfFound = false
|
||||||
|
let logFound = false
|
||||||
|
for (const file of body.compile.outputFiles) {
|
||||||
|
if (file.type === 'pdf') pdfFound = true
|
||||||
|
if (file.type === 'log') logFound = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!pdfFound) return done(new Error('no pdf returned'))
|
||||||
|
if (!logFound) return done(new Error('no log returned'))
|
||||||
|
done()
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
})
|
|
||||||
|
|
||||||
it('should return the pdf', function() {
|
|
||||||
for (const file of Array.from(this.body.compile.outputFiles)) {
|
|
||||||
if (file.type === 'pdf') {
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw new Error('no pdf returned')
|
|
||||||
})
|
|
||||||
|
|
||||||
return it('should return the log', function() {
|
|
||||||
for (const file of Array.from(this.body.compile.outputFiles)) {
|
|
||||||
if (file.type === 'log') {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error('no log returned')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
const SandboxedModule = require('sandboxed-module')
|
const SandboxedModule = require('sandboxed-module')
|
||||||
const sinon = require('sinon')
|
const sinon = require('sinon')
|
||||||
require('chai').should()
|
require('chai').should()
|
||||||
|
const { expect } = require('chai')
|
||||||
const modulePath = require('path').join(
|
const modulePath = require('path').join(
|
||||||
__dirname,
|
__dirname,
|
||||||
'../../../app/js/CompileController'
|
'../../../app/js/CompileController'
|
||||||
@@ -114,7 +115,7 @@ describe('CompileController', function() {
|
|||||||
compile: {
|
compile: {
|
||||||
status: 'success',
|
status: 'success',
|
||||||
error: null,
|
error: null,
|
||||||
outputFiles: this.output_files.map(file => {
|
outputFiles: this.output_files.map((file) => {
|
||||||
return {
|
return {
|
||||||
url: `${this.Settings.apis.clsi.url}/project/${this.project_id}/build/${file.build}/output/${file.path}`,
|
url: `${this.Settings.apis.clsi.url}/project/${this.project_id}/build/${file.build}/output/${file.path}`,
|
||||||
path: file.path,
|
path: file.path,
|
||||||
@@ -287,21 +288,60 @@ describe('CompileController', function() {
|
|||||||
this.CompileManager.wordcount = sinon
|
this.CompileManager.wordcount = sinon
|
||||||
.stub()
|
.stub()
|
||||||
.callsArgWith(4, null, (this.texcount = ['mock-texcount']))
|
.callsArgWith(4, null, (this.texcount = ['mock-texcount']))
|
||||||
return this.CompileController.wordcount(this.req, this.res, this.next)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should return the word count of a file', function () {
|
it('should return the word count of a file', function () {
|
||||||
|
this.CompileController.wordcount(this.req, this.res, this.next)
|
||||||
return this.CompileManager.wordcount
|
return this.CompileManager.wordcount
|
||||||
.calledWith(this.project_id, undefined, this.file, this.image)
|
.calledWith(this.project_id, undefined, this.file, this.image)
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
return it('should return the texcount info', function() {
|
it('should return the texcount info', function () {
|
||||||
|
this.CompileController.wordcount(this.req, this.res, this.next)
|
||||||
return this.res.json
|
return this.res.json
|
||||||
.calledWith({
|
.calledWith({
|
||||||
texcount: this.texcount
|
texcount: this.texcount
|
||||||
})
|
})
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('when allowedImages is set', function () {
|
||||||
|
beforeEach(function () {
|
||||||
|
this.Settings.clsi = { docker: {} }
|
||||||
|
this.Settings.clsi.docker.allowedImages = [
|
||||||
|
'repo/image:tag1',
|
||||||
|
'repo/image:tag2'
|
||||||
|
]
|
||||||
|
this.res.send = sinon.stub()
|
||||||
|
this.res.status = sinon.stub().returns({ send: this.res.send })
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('with an invalid image', function () {
|
||||||
|
beforeEach(function () {
|
||||||
|
this.req.query.image = 'something/evil:1337'
|
||||||
|
this.CompileController.wordcount(this.req, this.res, this.next)
|
||||||
|
})
|
||||||
|
it('should return a 400', function () {
|
||||||
|
expect(this.res.status.calledWith(400)).to.equal(true)
|
||||||
|
})
|
||||||
|
it('should not run the query', function () {
|
||||||
|
expect(this.CompileManager.wordcount.called).to.equal(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('with a valid image', function () {
|
||||||
|
beforeEach(function () {
|
||||||
|
this.req.query.image = 'repo/image:tag1'
|
||||||
|
this.CompileController.wordcount(this.req, this.res, this.next)
|
||||||
|
})
|
||||||
|
it('should not return a 400', function () {
|
||||||
|
expect(this.res.status.calledWith(400)).to.equal(false)
|
||||||
|
})
|
||||||
|
it('should run the query', function () {
|
||||||
|
expect(this.CompileManager.wordcount.called).to.equal(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -160,7 +160,8 @@ describe('CompileManager', function() {
|
|||||||
compiler: (this.compiler = 'pdflatex'),
|
compiler: (this.compiler = 'pdflatex'),
|
||||||
timeout: (this.timeout = 42000),
|
timeout: (this.timeout = 42000),
|
||||||
imageName: (this.image = 'example.com/image'),
|
imageName: (this.image = 'example.com/image'),
|
||||||
flags: (this.flags = ['-file-line-error'])
|
flags: (this.flags = ['-file-line-error']),
|
||||||
|
compileGroup: (this.compileGroup = 'compile-group')
|
||||||
}
|
}
|
||||||
this.env = {}
|
this.env = {}
|
||||||
this.Settings.compileDir = 'compiles'
|
this.Settings.compileDir = 'compiles'
|
||||||
@@ -199,7 +200,8 @@ describe('CompileManager', function() {
|
|||||||
timeout: this.timeout,
|
timeout: this.timeout,
|
||||||
image: this.image,
|
image: this.image,
|
||||||
flags: this.flags,
|
flags: this.flags,
|
||||||
environment: this.env
|
environment: this.env,
|
||||||
|
compileGroup: this.compileGroup
|
||||||
})
|
})
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
})
|
})
|
||||||
@@ -253,7 +255,8 @@ describe('CompileManager', function() {
|
|||||||
CHKTEX_OPTIONS: '-nall -e9 -e10 -w15 -w16',
|
CHKTEX_OPTIONS: '-nall -e9 -e10 -w15 -w16',
|
||||||
CHKTEX_EXIT_ON_ERROR: 1,
|
CHKTEX_EXIT_ON_ERROR: 1,
|
||||||
CHKTEX_ULIMIT_OPTIONS: '-t 5 -v 64000'
|
CHKTEX_ULIMIT_OPTIONS: '-t 5 -v 64000'
|
||||||
}
|
},
|
||||||
|
compileGroup: this.compileGroup
|
||||||
})
|
})
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
})
|
})
|
||||||
@@ -275,7 +278,8 @@ describe('CompileManager', function() {
|
|||||||
timeout: this.timeout,
|
timeout: this.timeout,
|
||||||
image: this.image,
|
image: this.image,
|
||||||
flags: this.flags,
|
flags: this.flags,
|
||||||
environment: this.env
|
environment: this.env,
|
||||||
|
compileGroup: this.compileGroup
|
||||||
})
|
})
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
})
|
})
|
||||||
@@ -294,6 +298,7 @@ describe('CompileManager', function() {
|
|||||||
this.proc = new EventEmitter()
|
this.proc = new EventEmitter()
|
||||||
this.proc.stdout = new EventEmitter()
|
this.proc.stdout = new EventEmitter()
|
||||||
this.proc.stderr = new EventEmitter()
|
this.proc.stderr = new EventEmitter()
|
||||||
|
this.proc.stderr.setEncoding = sinon.stub().returns(this.proc.stderr)
|
||||||
this.child_process.spawn = sinon.stub().returns(this.proc)
|
this.child_process.spawn = sinon.stub().returns(this.proc)
|
||||||
this.CompileManager.clearProject(
|
this.CompileManager.clearProject(
|
||||||
this.project_id,
|
this.project_id,
|
||||||
@@ -328,6 +333,7 @@ describe('CompileManager', function() {
|
|||||||
this.proc = new EventEmitter()
|
this.proc = new EventEmitter()
|
||||||
this.proc.stdout = new EventEmitter()
|
this.proc.stdout = new EventEmitter()
|
||||||
this.proc.stderr = new EventEmitter()
|
this.proc.stderr = new EventEmitter()
|
||||||
|
this.proc.stderr.setEncoding = sinon.stub().returns(this.proc.stderr)
|
||||||
this.child_process.spawn = sinon.stub().returns(this.proc)
|
this.child_process.spawn = sinon.stub().returns(this.proc)
|
||||||
this.CompileManager.clearProject(
|
this.CompileManager.clearProject(
|
||||||
this.project_id,
|
this.project_id,
|
||||||
@@ -368,7 +374,7 @@ describe('CompileManager', function() {
|
|||||||
this.column = 3
|
this.column = 3
|
||||||
this.file_name = 'main.tex'
|
this.file_name = 'main.tex'
|
||||||
this.child_process.execFile = sinon.stub()
|
this.child_process.execFile = sinon.stub()
|
||||||
return (this.Settings.path.synctexBaseDir = project_id =>
|
return (this.Settings.path.synctexBaseDir = (project_id) =>
|
||||||
`${this.Settings.path.compilesDir}/${this.project_id}-${this.user_id}`)
|
`${this.Settings.path.compilesDir}/${this.project_id}-${this.user_id}`)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -382,7 +388,7 @@ describe('CompileManager', function() {
|
|||||||
this.stdout = `NODE\t${this.page}\t${this.h}\t${this.v}\t${this.width}\t${this.height}\n`
|
this.stdout = `NODE\t${this.page}\t${this.h}\t${this.v}\t${this.width}\t${this.height}\n`
|
||||||
this.CommandRunner.run = sinon
|
this.CommandRunner.run = sinon
|
||||||
.stub()
|
.stub()
|
||||||
.callsArgWith(6, null, { stdout: this.stdout })
|
.callsArgWith(7, null, { stdout: this.stdout })
|
||||||
return this.CompileManager.syncFromCode(
|
return this.CompileManager.syncFromCode(
|
||||||
this.project_id,
|
this.project_id,
|
||||||
this.user_id,
|
this.user_id,
|
||||||
@@ -441,7 +447,7 @@ describe('CompileManager', function() {
|
|||||||
this.stdout = `NODE\t${this.Settings.path.compilesDir}/${this.project_id}-${this.user_id}/${this.file_name}\t${this.line}\t${this.column}\n`
|
this.stdout = `NODE\t${this.Settings.path.compilesDir}/${this.project_id}-${this.user_id}/${this.file_name}\t${this.line}\t${this.column}\n`
|
||||||
this.CommandRunner.run = sinon
|
this.CommandRunner.run = sinon
|
||||||
.stub()
|
.stub()
|
||||||
.callsArgWith(6, null, { stdout: this.stdout })
|
.callsArgWith(7, null, { stdout: this.stdout })
|
||||||
return this.CompileManager.syncFromPdf(
|
return this.CompileManager.syncFromPdf(
|
||||||
this.project_id,
|
this.project_id,
|
||||||
this.user_id,
|
this.user_id,
|
||||||
@@ -483,7 +489,7 @@ describe('CompileManager', function() {
|
|||||||
|
|
||||||
return describe('wordcount', function () {
|
return describe('wordcount', function () {
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
this.CommandRunner.run = sinon.stub().callsArg(6)
|
this.CommandRunner.run = sinon.stub().callsArg(7)
|
||||||
this.fs.readFile = sinon
|
this.fs.readFile = sinon
|
||||||
.stub()
|
.stub()
|
||||||
.callsArgWith(
|
.callsArgWith(
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ describe('LockManager', function() {
|
|||||||
this.callback = sinon.stub()
|
this.callback = sinon.stub()
|
||||||
return this.LockManager.runWithLock(
|
return this.LockManager.runWithLock(
|
||||||
'lock-one',
|
'lock-one',
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
setTimeout(() => releaseLock(null, 'hello', 'world'), 100),
|
setTimeout(() => releaseLock(null, 'hello', 'world'), 100),
|
||||||
|
|
||||||
(err, ...args) => {
|
(err, ...args) => {
|
||||||
@@ -59,7 +59,7 @@ describe('LockManager', function() {
|
|||||||
this.callback2 = sinon.stub()
|
this.callback2 = sinon.stub()
|
||||||
this.LockManager.runWithLock(
|
this.LockManager.runWithLock(
|
||||||
'lock-one',
|
'lock-one',
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
setTimeout(() => releaseLock(null, 'hello', 'world', 'one'), 100),
|
setTimeout(() => releaseLock(null, 'hello', 'world', 'one'), 100),
|
||||||
|
|
||||||
(err, ...args) => {
|
(err, ...args) => {
|
||||||
@@ -68,7 +68,7 @@ describe('LockManager', function() {
|
|||||||
)
|
)
|
||||||
return this.LockManager.runWithLock(
|
return this.LockManager.runWithLock(
|
||||||
'lock-two',
|
'lock-two',
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
setTimeout(() => releaseLock(null, 'hello', 'world', 'two'), 200),
|
setTimeout(() => releaseLock(null, 'hello', 'world', 'two'), 200),
|
||||||
|
|
||||||
(err, ...args) => {
|
(err, ...args) => {
|
||||||
@@ -100,7 +100,7 @@ describe('LockManager', function() {
|
|||||||
this.callback2 = sinon.stub()
|
this.callback2 = sinon.stub()
|
||||||
this.LockManager.runWithLock(
|
this.LockManager.runWithLock(
|
||||||
'lock',
|
'lock',
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
setTimeout(() => releaseLock(null, 'hello', 'world', 'one'), 100),
|
setTimeout(() => releaseLock(null, 'hello', 'world', 'one'), 100),
|
||||||
|
|
||||||
(err, ...args) => {
|
(err, ...args) => {
|
||||||
@@ -109,7 +109,7 @@ describe('LockManager', function() {
|
|||||||
)
|
)
|
||||||
return this.LockManager.runWithLock(
|
return this.LockManager.runWithLock(
|
||||||
'lock',
|
'lock',
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
setTimeout(() => releaseLock(null, 'hello', 'world', 'two'), 200),
|
setTimeout(() => releaseLock(null, 'hello', 'world', 'two'), 200),
|
||||||
|
|
||||||
(err, ...args) => {
|
(err, ...args) => {
|
||||||
@@ -154,7 +154,7 @@ describe('LockManager', function() {
|
|||||||
}
|
}
|
||||||
this.LockManager.runWithLock(
|
this.LockManager.runWithLock(
|
||||||
'lock',
|
'lock',
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
setTimeout(
|
setTimeout(
|
||||||
() => releaseLock(null, 'hello', 'world', 'one'),
|
() => releaseLock(null, 'hello', 'world', 'one'),
|
||||||
1100
|
1100
|
||||||
@@ -167,7 +167,7 @@ describe('LockManager', function() {
|
|||||||
)
|
)
|
||||||
return this.LockManager.runWithLock(
|
return this.LockManager.runWithLock(
|
||||||
'lock',
|
'lock',
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
setTimeout(() => releaseLock(null, 'hello', 'world', 'two'), 100),
|
setTimeout(() => releaseLock(null, 'hello', 'world', 'two'), 100),
|
||||||
|
|
||||||
(err, ...args) => {
|
(err, ...args) => {
|
||||||
@@ -211,7 +211,7 @@ describe('LockManager', function() {
|
|||||||
}
|
}
|
||||||
this.LockManager.runWithLock(
|
this.LockManager.runWithLock(
|
||||||
'lock',
|
'lock',
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
setTimeout(
|
setTimeout(
|
||||||
() => releaseLock(null, 'hello', 'world', 'one'),
|
() => releaseLock(null, 'hello', 'world', 'one'),
|
||||||
1500
|
1500
|
||||||
@@ -224,7 +224,7 @@ describe('LockManager', function() {
|
|||||||
)
|
)
|
||||||
return this.LockManager.runWithLock(
|
return this.LockManager.runWithLock(
|
||||||
'lock',
|
'lock',
|
||||||
releaseLock =>
|
(releaseLock) =>
|
||||||
setTimeout(() => releaseLock(null, 'hello', 'world', 'two'), 100),
|
setTimeout(() => releaseLock(null, 'hello', 'world', 'two'), 100),
|
||||||
|
|
||||||
(err, ...args) => {
|
(err, ...args) => {
|
||||||
|
|||||||
@@ -69,7 +69,8 @@ describe('DockerRunner', function() {
|
|||||||
return runner(callback)
|
return runner(callback)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
globals: { Math } // used by lodash
|
||||||
})
|
})
|
||||||
this.Docker = Docker
|
this.Docker = Docker
|
||||||
this.getContainer = Docker.prototype.getContainer
|
this.getContainer = Docker.prototype.getContainer
|
||||||
@@ -85,6 +86,7 @@ describe('DockerRunner', function() {
|
|||||||
this.project_id = 'project-id-123'
|
this.project_id = 'project-id-123'
|
||||||
this.volumes = { '/local/compile/directory': '/compile' }
|
this.volumes = { '/local/compile/directory': '/compile' }
|
||||||
this.Settings.clsi.docker.image = this.defaultImage = 'default-image'
|
this.Settings.clsi.docker.image = this.defaultImage = 'default-image'
|
||||||
|
this.compileGroup = 'compile-group'
|
||||||
return (this.Settings.clsi.docker.env = { PATH: 'mock-path' })
|
return (this.Settings.clsi.docker.env = { PATH: 'mock-path' })
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -121,6 +123,7 @@ describe('DockerRunner', function() {
|
|||||||
this.image,
|
this.image,
|
||||||
this.timeout,
|
this.timeout,
|
||||||
this.env,
|
this.env,
|
||||||
|
this.compileGroup,
|
||||||
(err, output) => {
|
(err, output) => {
|
||||||
this.callback(err, output)
|
this.callback(err, output)
|
||||||
return done()
|
return done()
|
||||||
@@ -170,6 +173,7 @@ describe('DockerRunner', function() {
|
|||||||
this.image,
|
this.image,
|
||||||
this.timeout,
|
this.timeout,
|
||||||
this.env,
|
this.env,
|
||||||
|
this.compileGroup,
|
||||||
this.callback
|
this.callback
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
@@ -218,6 +222,7 @@ describe('DockerRunner', function() {
|
|||||||
this.image,
|
this.image,
|
||||||
this.timeout,
|
this.timeout,
|
||||||
this.env,
|
this.env,
|
||||||
|
this.compileGroup,
|
||||||
this.callback
|
this.callback
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
@@ -251,6 +256,7 @@ describe('DockerRunner', function() {
|
|||||||
null,
|
null,
|
||||||
this.timeout,
|
this.timeout,
|
||||||
this.env,
|
this.env,
|
||||||
|
this.compileGroup,
|
||||||
this.callback
|
this.callback
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
@@ -267,7 +273,7 @@ describe('DockerRunner', function() {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
return describe('with image override', function() {
|
describe('with image override', function () {
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
this.Settings.texliveImageNameOveride = 'overrideimage.com/something'
|
this.Settings.texliveImageNameOveride = 'overrideimage.com/something'
|
||||||
this.DockerRunner._runAndWaitForContainer = sinon
|
this.DockerRunner._runAndWaitForContainer = sinon
|
||||||
@@ -280,6 +286,7 @@ describe('DockerRunner', function() {
|
|||||||
this.image,
|
this.image,
|
||||||
this.timeout,
|
this.timeout,
|
||||||
this.env,
|
this.env,
|
||||||
|
this.compileGroup,
|
||||||
this.callback
|
this.callback
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
@@ -289,6 +296,120 @@ describe('DockerRunner', function() {
|
|||||||
return image.should.equal('overrideimage.com/something/image:2016.2')
|
return image.should.equal('overrideimage.com/something/image:2016.2')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('with image restriction', function () {
|
||||||
|
beforeEach(function () {
|
||||||
|
this.Settings.clsi.docker.allowedImages = [
|
||||||
|
'repo/image:tag1',
|
||||||
|
'repo/image:tag2'
|
||||||
|
]
|
||||||
|
this.DockerRunner._runAndWaitForContainer = sinon
|
||||||
|
.stub()
|
||||||
|
.callsArgWith(3, null, (this.output = 'mock-output'))
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('with a valid image', function () {
|
||||||
|
beforeEach(function () {
|
||||||
|
this.DockerRunner.run(
|
||||||
|
this.project_id,
|
||||||
|
this.command,
|
||||||
|
this.directory,
|
||||||
|
'repo/image:tag1',
|
||||||
|
this.timeout,
|
||||||
|
this.env,
|
||||||
|
this.compileGroup,
|
||||||
|
this.callback
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should setup the container', function () {
|
||||||
|
this.DockerRunner._getContainerOptions.called.should.equal(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('with a invalid image', function () {
|
||||||
|
beforeEach(function () {
|
||||||
|
this.DockerRunner.run(
|
||||||
|
this.project_id,
|
||||||
|
this.command,
|
||||||
|
this.directory,
|
||||||
|
'something/different:evil',
|
||||||
|
this.timeout,
|
||||||
|
this.env,
|
||||||
|
this.compileGroup,
|
||||||
|
this.callback
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should call the callback with an error', function () {
|
||||||
|
const err = new Error('image not allowed')
|
||||||
|
this.callback.called.should.equal(true)
|
||||||
|
this.callback.args[0][0].message.should.equal(err.message)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should not setup the container', function () {
|
||||||
|
this.DockerRunner._getContainerOptions.called.should.equal(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('run with _getOptions', function () {
|
||||||
|
beforeEach(function (done) {
|
||||||
|
// this.DockerRunner._getContainerOptions = sinon
|
||||||
|
// .stub()
|
||||||
|
// .returns((this.options = { mockoptions: 'foo' }))
|
||||||
|
this.DockerRunner._fingerprintContainer = sinon
|
||||||
|
.stub()
|
||||||
|
.returns((this.fingerprint = 'fingerprint'))
|
||||||
|
|
||||||
|
this.name = `project-${this.project_id}-${this.fingerprint}`
|
||||||
|
|
||||||
|
this.command = ['mock', 'command', '--outdir=$COMPILE_DIR']
|
||||||
|
this.command_with_dir = ['mock', 'command', '--outdir=/compile']
|
||||||
|
this.timeout = 42000
|
||||||
|
return done()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('when a compile group config is set', function () {
|
||||||
|
beforeEach(function () {
|
||||||
|
this.Settings.clsi.docker.compileGroupConfig = {
|
||||||
|
'compile-group': {
|
||||||
|
'HostConfig.newProperty': 'new-property'
|
||||||
|
},
|
||||||
|
'other-group': { otherProperty: 'other-property' }
|
||||||
|
}
|
||||||
|
this.DockerRunner._runAndWaitForContainer = sinon
|
||||||
|
.stub()
|
||||||
|
.callsArgWith(3, null, (this.output = 'mock-output'))
|
||||||
|
return this.DockerRunner.run(
|
||||||
|
this.project_id,
|
||||||
|
this.command,
|
||||||
|
this.directory,
|
||||||
|
this.image,
|
||||||
|
this.timeout,
|
||||||
|
this.env,
|
||||||
|
this.compileGroup,
|
||||||
|
this.callback
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should set the docker options for the compile group', function () {
|
||||||
|
const options = this.DockerRunner._runAndWaitForContainer.lastCall
|
||||||
|
.args[0]
|
||||||
|
return expect(options.HostConfig).to.deep.include({
|
||||||
|
Binds: ['/local/compile/directory:/compile:rw'],
|
||||||
|
LogConfig: { Type: 'none', Config: {} },
|
||||||
|
CapDrop: 'ALL',
|
||||||
|
SecurityOpt: ['no-new-privileges'],
|
||||||
|
newProperty: 'new-property'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return it('should call the callback', function () {
|
||||||
|
return this.callback.calledWith(null, this.output).should.equal(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('_runAndWaitForContainer', function () {
|
describe('_runAndWaitForContainer', function () {
|
||||||
@@ -357,8 +478,8 @@ describe('DockerRunner', function() {
|
|||||||
return this.DockerRunner.startContainer(
|
return this.DockerRunner.startContainer(
|
||||||
this.options,
|
this.options,
|
||||||
this.volumes,
|
this.volumes,
|
||||||
this.callback,
|
() => {},
|
||||||
() => {}
|
this.callback
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -617,7 +738,7 @@ describe('DockerRunner', function() {
|
|||||||
this.DockerRunner.MAX_CONTAINER_AGE = oneHourInMilliseconds
|
this.DockerRunner.MAX_CONTAINER_AGE = oneHourInMilliseconds
|
||||||
this.listContainers.callsArgWith(1, null, this.containers)
|
this.listContainers.callsArgWith(1, null, this.containers)
|
||||||
this.DockerRunner.destroyContainer = sinon.stub().callsArg(3)
|
this.DockerRunner.destroyContainer = sinon.stub().callsArg(3)
|
||||||
return this.DockerRunner.destroyOldContainers(error => {
|
return this.DockerRunner.destroyOldContainers((error) => {
|
||||||
this.callback(error)
|
this.callback(error)
|
||||||
return done()
|
return done()
|
||||||
})
|
})
|
||||||
@@ -630,19 +751,19 @@ describe('DockerRunner', function() {
|
|||||||
it('should destroy old containers', function () {
|
it('should destroy old containers', function () {
|
||||||
this.DockerRunner.destroyContainer.callCount.should.equal(1)
|
this.DockerRunner.destroyContainer.callCount.should.equal(1)
|
||||||
return this.DockerRunner.destroyContainer
|
return this.DockerRunner.destroyContainer
|
||||||
.calledWith('/project-old-container-name', 'old-container-id')
|
.calledWith('project-old-container-name', 'old-container-id')
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should not destroy new containers', function () {
|
it('should not destroy new containers', function () {
|
||||||
return this.DockerRunner.destroyContainer
|
return this.DockerRunner.destroyContainer
|
||||||
.calledWith('/project-new-container-name', 'new-container-id')
|
.calledWith('project-new-container-name', 'new-container-id')
|
||||||
.should.equal(false)
|
.should.equal(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should not destroy non-project containers', function () {
|
it('should not destroy non-project containers', function () {
|
||||||
return this.DockerRunner.destroyContainer
|
return this.DockerRunner.destroyContainer
|
||||||
.calledWith('/totally-not-a-project-container', 'some-random-id')
|
.calledWith('totally-not-a-project-container', 'some-random-id')
|
||||||
.should.equal(false)
|
.should.equal(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -664,7 +785,7 @@ describe('DockerRunner', function() {
|
|||||||
return this.DockerRunner._destroyContainer(
|
return this.DockerRunner._destroyContainer(
|
||||||
this.containerId,
|
this.containerId,
|
||||||
false,
|
false,
|
||||||
err => {
|
(err) => {
|
||||||
this.Docker.prototype.getContainer.callCount.should.equal(1)
|
this.Docker.prototype.getContainer.callCount.should.equal(1)
|
||||||
this.Docker.prototype.getContainer
|
this.Docker.prototype.getContainer
|
||||||
.calledWith(this.containerId)
|
.calledWith(this.containerId)
|
||||||
@@ -678,10 +799,10 @@ describe('DockerRunner', function() {
|
|||||||
return this.DockerRunner._destroyContainer(
|
return this.DockerRunner._destroyContainer(
|
||||||
this.containerId,
|
this.containerId,
|
||||||
true,
|
true,
|
||||||
err => {
|
(err) => {
|
||||||
this.fakeContainer.remove.callCount.should.equal(1)
|
this.fakeContainer.remove.callCount.should.equal(1)
|
||||||
this.fakeContainer.remove
|
this.fakeContainer.remove
|
||||||
.calledWith({ force: true })
|
.calledWith({ force: true, v: true })
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
return done()
|
return done()
|
||||||
}
|
}
|
||||||
@@ -692,10 +813,10 @@ describe('DockerRunner', function() {
|
|||||||
return this.DockerRunner._destroyContainer(
|
return this.DockerRunner._destroyContainer(
|
||||||
this.containerId,
|
this.containerId,
|
||||||
false,
|
false,
|
||||||
err => {
|
(err) => {
|
||||||
this.fakeContainer.remove.callCount.should.equal(1)
|
this.fakeContainer.remove.callCount.should.equal(1)
|
||||||
this.fakeContainer.remove
|
this.fakeContainer.remove
|
||||||
.calledWith({ force: false })
|
.calledWith({ force: false, v: true })
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
return done()
|
return done()
|
||||||
}
|
}
|
||||||
@@ -706,7 +827,7 @@ describe('DockerRunner', function() {
|
|||||||
return this.DockerRunner._destroyContainer(
|
return this.DockerRunner._destroyContainer(
|
||||||
this.containerId,
|
this.containerId,
|
||||||
false,
|
false,
|
||||||
err => {
|
(err) => {
|
||||||
expect(err).to.equal(null)
|
expect(err).to.equal(null)
|
||||||
return done()
|
return done()
|
||||||
}
|
}
|
||||||
@@ -729,7 +850,7 @@ describe('DockerRunner', function() {
|
|||||||
return this.DockerRunner._destroyContainer(
|
return this.DockerRunner._destroyContainer(
|
||||||
this.containerId,
|
this.containerId,
|
||||||
false,
|
false,
|
||||||
err => {
|
(err) => {
|
||||||
expect(err).to.equal(null)
|
expect(err).to.equal(null)
|
||||||
return done()
|
return done()
|
||||||
}
|
}
|
||||||
@@ -753,7 +874,7 @@ describe('DockerRunner', function() {
|
|||||||
return this.DockerRunner._destroyContainer(
|
return this.DockerRunner._destroyContainer(
|
||||||
this.containerId,
|
this.containerId,
|
||||||
false,
|
false,
|
||||||
err => {
|
(err) => {
|
||||||
expect(err).to.not.equal(null)
|
expect(err).to.not.equal(null)
|
||||||
expect(err).to.equal(this.fakeError)
|
expect(err).to.equal(this.fakeError)
|
||||||
return done()
|
return done()
|
||||||
@@ -773,7 +894,7 @@ describe('DockerRunner', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should get the container', function (done) {
|
it('should get the container', function (done) {
|
||||||
return this.DockerRunner.kill(this.containerId, err => {
|
return this.DockerRunner.kill(this.containerId, (err) => {
|
||||||
this.Docker.prototype.getContainer.callCount.should.equal(1)
|
this.Docker.prototype.getContainer.callCount.should.equal(1)
|
||||||
this.Docker.prototype.getContainer
|
this.Docker.prototype.getContainer
|
||||||
.calledWith(this.containerId)
|
.calledWith(this.containerId)
|
||||||
@@ -783,14 +904,14 @@ describe('DockerRunner', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should try to force-destroy the container', function (done) {
|
it('should try to force-destroy the container', function (done) {
|
||||||
return this.DockerRunner.kill(this.containerId, err => {
|
return this.DockerRunner.kill(this.containerId, (err) => {
|
||||||
this.fakeContainer.kill.callCount.should.equal(1)
|
this.fakeContainer.kill.callCount.should.equal(1)
|
||||||
return done()
|
return done()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should not produce an error', function (done) {
|
it('should not produce an error', function (done) {
|
||||||
return this.DockerRunner.kill(this.containerId, err => {
|
return this.DockerRunner.kill(this.containerId, (err) => {
|
||||||
expect(err).to.equal(undefined)
|
expect(err).to.equal(undefined)
|
||||||
return done()
|
return done()
|
||||||
})
|
})
|
||||||
@@ -811,7 +932,7 @@ describe('DockerRunner', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
return it('should not produce an error', function (done) {
|
return it('should not produce an error', function (done) {
|
||||||
return this.DockerRunner.kill(this.containerId, err => {
|
return this.DockerRunner.kill(this.containerId, (err) => {
|
||||||
expect(err).to.equal(undefined)
|
expect(err).to.equal(undefined)
|
||||||
return done()
|
return done()
|
||||||
})
|
})
|
||||||
@@ -832,7 +953,7 @@ describe('DockerRunner', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
return it('should produce an error', function (done) {
|
return it('should produce an error', function (done) {
|
||||||
return this.DockerRunner.kill(this.containerId, err => {
|
return this.DockerRunner.kill(this.containerId, (err) => {
|
||||||
expect(err).to.not.equal(undefined)
|
expect(err).to.not.equal(undefined)
|
||||||
expect(err).to.equal(this.fakeError)
|
expect(err).to.equal(this.fakeError)
|
||||||
return done()
|
return done()
|
||||||
|
|||||||
@@ -37,7 +37,10 @@ describe('LatexRunner', function() {
|
|||||||
done() {}
|
done() {}
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
'./CommandRunner': (this.CommandRunner = {})
|
'./CommandRunner': (this.CommandRunner = {}),
|
||||||
|
fs: (this.fs = {
|
||||||
|
writeFile: sinon.stub().callsArg(2)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -45,6 +48,7 @@ describe('LatexRunner', function() {
|
|||||||
this.mainFile = 'main-file.tex'
|
this.mainFile = 'main-file.tex'
|
||||||
this.compiler = 'pdflatex'
|
this.compiler = 'pdflatex'
|
||||||
this.image = 'example.com/image'
|
this.image = 'example.com/image'
|
||||||
|
this.compileGroup = 'compile-group'
|
||||||
this.callback = sinon.stub()
|
this.callback = sinon.stub()
|
||||||
this.project_id = 'project-id-123'
|
this.project_id = 'project-id-123'
|
||||||
return (this.env = { foo: '123' })
|
return (this.env = { foo: '123' })
|
||||||
@@ -52,7 +56,10 @@ describe('LatexRunner', function() {
|
|||||||
|
|
||||||
return describe('runLatex', function () {
|
return describe('runLatex', function () {
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
return (this.CommandRunner.run = sinon.stub().callsArg(6))
|
return (this.CommandRunner.run = sinon.stub().callsArgWith(7, null, {
|
||||||
|
stdout: 'this is stdout',
|
||||||
|
stderr: 'this is stderr'
|
||||||
|
}))
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('normally', function () {
|
describe('normally', function () {
|
||||||
@@ -65,13 +72,14 @@ describe('LatexRunner', function() {
|
|||||||
compiler: this.compiler,
|
compiler: this.compiler,
|
||||||
timeout: (this.timeout = 42000),
|
timeout: (this.timeout = 42000),
|
||||||
image: this.image,
|
image: this.image,
|
||||||
environment: this.env
|
environment: this.env,
|
||||||
|
compileGroup: this.compileGroup
|
||||||
},
|
},
|
||||||
this.callback
|
this.callback
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
return it('should run the latex command', function() {
|
it('should run the latex command', function () {
|
||||||
return this.CommandRunner.run
|
return this.CommandRunner.run
|
||||||
.calledWith(
|
.calledWith(
|
||||||
this.project_id,
|
this.project_id,
|
||||||
@@ -79,10 +87,20 @@ describe('LatexRunner', function() {
|
|||||||
this.directory,
|
this.directory,
|
||||||
this.image,
|
this.image,
|
||||||
this.timeout,
|
this.timeout,
|
||||||
this.env
|
this.env,
|
||||||
|
this.compileGroup
|
||||||
)
|
)
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('should record the stdout and stderr', function () {
|
||||||
|
this.fs.writeFile
|
||||||
|
.calledWith(this.directory + '/' + 'output.stdout', 'this is stdout')
|
||||||
|
.should.equal(true)
|
||||||
|
this.fs.writeFile
|
||||||
|
.calledWith(this.directory + '/' + 'output.stderr', 'this is stderr')
|
||||||
|
.should.equal(true)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('with an .Rtex main file', function () {
|
describe('with an .Rtex main file', function () {
|
||||||
@@ -126,7 +144,7 @@ describe('LatexRunner', function() {
|
|||||||
return it('should include the flags in the command', function () {
|
return it('should include the flags in the command', function () {
|
||||||
const command = this.CommandRunner.run.args[0][1]
|
const command = this.CommandRunner.run.args[0][1]
|
||||||
const flags = command.filter(
|
const flags = command.filter(
|
||||||
arg => arg === '-file-line-error' || arg === '-halt-on-error'
|
(arg) => arg === '-file-line-error' || arg === '-halt-on-error'
|
||||||
)
|
)
|
||||||
flags.length.should.equal(2)
|
flags.length.should.equal(2)
|
||||||
flags[0].should.equal('-file-line-error')
|
flags[0].should.equal('-file-line-error')
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ describe('OutputFileFinder', function() {
|
|||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
this.proc = new EventEmitter()
|
this.proc = new EventEmitter()
|
||||||
this.proc.stdout = new EventEmitter()
|
this.proc.stdout = new EventEmitter()
|
||||||
|
this.proc.stdout.setEncoding = sinon.stub().returns(this.proc.stdout)
|
||||||
this.spawn.returns(this.proc)
|
this.spawn.returns(this.proc)
|
||||||
this.directory = '/base/dir'
|
this.directory = '/base/dir'
|
||||||
return this.OutputFileFinder._getAllFiles(this.directory, this.callback)
|
return this.OutputFileFinder._getAllFiles(this.directory, this.callback)
|
||||||
|
|||||||
@@ -30,7 +30,8 @@ describe('OutputFileOptimiser', function() {
|
|||||||
child_process: { spawn: (this.spawn = sinon.stub()) },
|
child_process: { spawn: (this.spawn = sinon.stub()) },
|
||||||
'logger-sharelatex': { log: sinon.stub(), warn: sinon.stub() },
|
'logger-sharelatex': { log: sinon.stub(), warn: sinon.stub() },
|
||||||
'./Metrics': {}
|
'./Metrics': {}
|
||||||
}
|
},
|
||||||
|
globals: { Math } // used by lodash
|
||||||
})
|
})
|
||||||
this.directory = '/test/dir'
|
this.directory = '/test/dir'
|
||||||
return (this.callback = sinon.stub())
|
return (this.callback = sinon.stub())
|
||||||
@@ -124,11 +125,8 @@ describe('OutputFileOptimiser', function() {
|
|||||||
this.fs.read = sinon
|
this.fs.read = sinon
|
||||||
.stub()
|
.stub()
|
||||||
.withArgs(this.fd)
|
.withArgs(this.fd)
|
||||||
.yields(null, 100, new Buffer('hello /Linearized 1'))
|
.yields(null, 100, Buffer.from('hello /Linearized 1'))
|
||||||
this.fs.close = sinon
|
this.fs.close = sinon.stub().withArgs(this.fd).yields(null)
|
||||||
.stub()
|
|
||||||
.withArgs(this.fd)
|
|
||||||
.yields(null)
|
|
||||||
return this.OutputFileOptimiser.checkIfPDFIsOptimised(
|
return this.OutputFileOptimiser.checkIfPDFIsOptimised(
|
||||||
this.src,
|
this.src,
|
||||||
this.callback
|
this.callback
|
||||||
@@ -140,7 +138,7 @@ describe('OutputFileOptimiser', function() {
|
|||||||
this.fs.read = sinon
|
this.fs.read = sinon
|
||||||
.stub()
|
.stub()
|
||||||
.withArgs(this.fd)
|
.withArgs(this.fd)
|
||||||
.yields(null, 100, new Buffer('hello /Linearized 1'))
|
.yields(null, 100, Buffer.from('hello /Linearized 1'))
|
||||||
return this.OutputFileOptimiser.checkIfPDFIsOptimised(
|
return this.OutputFileOptimiser.checkIfPDFIsOptimised(
|
||||||
this.src,
|
this.src,
|
||||||
this.callback
|
this.callback
|
||||||
@@ -169,7 +167,7 @@ describe('OutputFileOptimiser', function() {
|
|||||||
this.fs.read = sinon
|
this.fs.read = sinon
|
||||||
.stub()
|
.stub()
|
||||||
.withArgs(this.fd)
|
.withArgs(this.fd)
|
||||||
.yields(null, 100, new Buffer('hello not linearized 1'))
|
.yields(null, 100, Buffer.from('hello not linearized 1'))
|
||||||
return this.OutputFileOptimiser.checkIfPDFIsOptimised(
|
return this.OutputFileOptimiser.checkIfPDFIsOptimised(
|
||||||
this.src,
|
this.src,
|
||||||
this.callback
|
this.callback
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
const SandboxedModule = require('sandboxed-module')
|
const SandboxedModule = require('sandboxed-module')
|
||||||
const sinon = require('sinon')
|
const sinon = require('sinon')
|
||||||
require('chai').should()
|
require('chai').should()
|
||||||
|
const assert = require('chai').assert
|
||||||
const modulePath = require('path').join(
|
const modulePath = require('path').join(
|
||||||
__dirname,
|
__dirname,
|
||||||
'../../../app/js/ProjectPersistenceManager'
|
'../../../app/js/ProjectPersistenceManager'
|
||||||
@@ -26,7 +27,15 @@ describe('ProjectPersistenceManager', function() {
|
|||||||
requires: {
|
requires: {
|
||||||
'./UrlCache': (this.UrlCache = {}),
|
'./UrlCache': (this.UrlCache = {}),
|
||||||
'./CompileManager': (this.CompileManager = {}),
|
'./CompileManager': (this.CompileManager = {}),
|
||||||
'logger-sharelatex': (this.logger = { log: sinon.stub() }),
|
diskusage: (this.diskusage = { check: sinon.stub() }),
|
||||||
|
'logger-sharelatex': (this.logger = {
|
||||||
|
log: sinon.stub(),
|
||||||
|
warn: sinon.stub(),
|
||||||
|
err: sinon.stub()
|
||||||
|
}),
|
||||||
|
'settings-sharelatex': (this.settings = {
|
||||||
|
project_cache_length_ms: 1000
|
||||||
|
}),
|
||||||
'./db': (this.db = {})
|
'./db': (this.db = {})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -35,6 +44,57 @@ describe('ProjectPersistenceManager', function() {
|
|||||||
return (this.user_id = '1234')
|
return (this.user_id = '1234')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('refreshExpiryTimeout', function () {
|
||||||
|
it('should leave expiry alone if plenty of disk', function (done) {
|
||||||
|
this.diskusage.check.callsArgWith(1, null, {
|
||||||
|
available: 40,
|
||||||
|
total: 100
|
||||||
|
})
|
||||||
|
|
||||||
|
this.ProjectPersistenceManager.refreshExpiryTimeout(() => {
|
||||||
|
this.ProjectPersistenceManager.EXPIRY_TIMEOUT.should.equal(
|
||||||
|
this.settings.project_cache_length_ms
|
||||||
|
)
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should drop EXPIRY_TIMEOUT 10% if low disk usage', function (done) {
|
||||||
|
this.diskusage.check.callsArgWith(1, null, {
|
||||||
|
available: 5,
|
||||||
|
total: 100
|
||||||
|
})
|
||||||
|
|
||||||
|
this.ProjectPersistenceManager.refreshExpiryTimeout(() => {
|
||||||
|
this.ProjectPersistenceManager.EXPIRY_TIMEOUT.should.equal(900)
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should not drop EXPIRY_TIMEOUT to below 50% of project_cache_length_ms', function (done) {
|
||||||
|
this.diskusage.check.callsArgWith(1, null, {
|
||||||
|
available: 5,
|
||||||
|
total: 100
|
||||||
|
})
|
||||||
|
this.ProjectPersistenceManager.EXPIRY_TIMEOUT = 500
|
||||||
|
this.ProjectPersistenceManager.refreshExpiryTimeout(() => {
|
||||||
|
this.ProjectPersistenceManager.EXPIRY_TIMEOUT.should.equal(500)
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should not modify EXPIRY_TIMEOUT if there is an error getting disk values', function (done) {
|
||||||
|
this.diskusage.check.callsArgWith(1, 'Error', {
|
||||||
|
available: 5,
|
||||||
|
total: 100
|
||||||
|
})
|
||||||
|
this.ProjectPersistenceManager.refreshExpiryTimeout(() => {
|
||||||
|
this.ProjectPersistenceManager.EXPIRY_TIMEOUT.should.equal(1000)
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('clearExpiredProjects', function () {
|
describe('clearExpiredProjects', function () {
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
this.project_ids = ['project-id-1', 'project-id-2']
|
this.project_ids = ['project-id-1', 'project-id-2']
|
||||||
@@ -49,7 +109,7 @@ describe('ProjectPersistenceManager', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should clear each expired project', function () {
|
it('should clear each expired project', function () {
|
||||||
return Array.from(this.project_ids).map(project_id =>
|
return Array.from(this.project_ids).map((project_id) =>
|
||||||
this.ProjectPersistenceManager.clearProjectFromCache
|
this.ProjectPersistenceManager.clearProjectFromCache
|
||||||
.calledWith(project_id)
|
.calledWith(project_id)
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
|
|||||||
@@ -114,6 +114,48 @@ describe('RequestParser', function() {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('when image restrictions are present', function () {
|
||||||
|
beforeEach(function () {
|
||||||
|
this.settings.clsi = { docker: {} }
|
||||||
|
this.settings.clsi.docker.allowedImages = [
|
||||||
|
'repo/name:tag1',
|
||||||
|
'repo/name:tag2'
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('with imageName set to something invalid', function () {
|
||||||
|
beforeEach(function () {
|
||||||
|
const request = this.validRequest
|
||||||
|
request.compile.options.imageName = 'something/different:latest'
|
||||||
|
this.RequestParser.parse(request, (error, data) => {
|
||||||
|
this.error = error
|
||||||
|
this.data = data
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should throw an error for imageName', function () {
|
||||||
|
expect(String(this.error)).to.include(
|
||||||
|
'imageName attribute should be one of'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('with imageName set to something valid', function () {
|
||||||
|
beforeEach(function () {
|
||||||
|
const request = this.validRequest
|
||||||
|
request.compile.options.imageName = 'repo/name:tag1'
|
||||||
|
this.RequestParser.parse(request, (error, data) => {
|
||||||
|
this.error = error
|
||||||
|
this.data = data
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should set the imageName', function () {
|
||||||
|
this.data.imageName.should.equal('repo/name:tag1')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('with flags set', function () {
|
describe('with flags set', function () {
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
this.validRequest.compile.options.flags = ['-file-line-error']
|
this.validRequest.compile.options.flags = ['-file-line-error']
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ describe('ResourceWriter', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should write each resource to disk', function () {
|
it('should write each resource to disk', function () {
|
||||||
return Array.from(this.resources).map(resource =>
|
return Array.from(this.resources).map((resource) =>
|
||||||
this.ResourceWriter._writeResourceToDisk
|
this.ResourceWriter._writeResourceToDisk
|
||||||
.calledWith(this.project_id, resource, this.basePath)
|
.calledWith(this.project_id, resource, this.basePath)
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
@@ -139,7 +139,7 @@ describe('ResourceWriter', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should write each resource to disk', function () {
|
it('should write each resource to disk', function () {
|
||||||
return Array.from(this.resources).map(resource =>
|
return Array.from(this.resources).map((resource) =>
|
||||||
this.ResourceWriter._writeResourceToDisk
|
this.ResourceWriter._writeResourceToDisk
|
||||||
.calledWith(this.project_id, resource, this.basePath)
|
.calledWith(this.project_id, resource, this.basePath)
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
@@ -230,6 +230,12 @@ describe('ResourceWriter', function() {
|
|||||||
{
|
{
|
||||||
path: '_markdown_main/30893013dec5d869a415610079774c2f.md.tex',
|
path: '_markdown_main/30893013dec5d869a415610079774c2f.md.tex',
|
||||||
type: 'tex'
|
type: 'tex'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'output.stdout'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'output.stderr'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
this.resources = 'mock-resources'
|
this.resources = 'mock-resources'
|
||||||
@@ -256,6 +262,18 @@ describe('ResourceWriter', function() {
|
|||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('should delete the stdout log file', function () {
|
||||||
|
return this.ResourceWriter._deleteFileIfNotDirectory
|
||||||
|
.calledWith(path.join(this.basePath, 'output.stdout'))
|
||||||
|
.should.equal(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should delete the stderr log file', function () {
|
||||||
|
return this.ResourceWriter._deleteFileIfNotDirectory
|
||||||
|
.calledWith(path.join(this.basePath, 'output.stderr'))
|
||||||
|
.should.equal(true)
|
||||||
|
})
|
||||||
|
|
||||||
it('should delete the extra files', function () {
|
it('should delete the extra files', function () {
|
||||||
return this.ResourceWriter._deleteFileIfNotDirectory
|
return this.ResourceWriter._deleteFileIfNotDirectory
|
||||||
.calledWith(path.join(this.basePath, 'extra/file.tex'))
|
.calledWith(path.join(this.basePath, 'extra/file.tex'))
|
||||||
|
|||||||
@@ -160,7 +160,7 @@ describe('UrlCache', function() {
|
|||||||
|
|
||||||
describe('_ensureUrlIsInCache', function () {
|
describe('_ensureUrlIsInCache', function () {
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
this.UrlFetcher.pipeUrlToFile = sinon.stub().callsArg(2)
|
this.UrlFetcher.pipeUrlToFileWithRetry = sinon.stub().callsArg(2)
|
||||||
return (this.UrlCache._updateOrCreateUrlDetails = sinon
|
return (this.UrlCache._updateOrCreateUrlDetails = sinon
|
||||||
.stub()
|
.stub()
|
||||||
.callsArg(3))
|
.callsArg(3))
|
||||||
@@ -190,7 +190,7 @@ describe('UrlCache', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should download the URL to the cache file', function () {
|
it('should download the URL to the cache file', function () {
|
||||||
return this.UrlFetcher.pipeUrlToFile
|
return this.UrlFetcher.pipeUrlToFileWithRetry
|
||||||
.calledWith(
|
.calledWith(
|
||||||
this.url,
|
this.url,
|
||||||
this.UrlCache._cacheFilePathForUrl(this.project_id, this.url)
|
this.UrlCache._cacheFilePathForUrl(this.project_id, this.url)
|
||||||
@@ -232,7 +232,7 @@ describe('UrlCache', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should not download the URL to the cache file', function () {
|
it('should not download the URL to the cache file', function () {
|
||||||
return this.UrlFetcher.pipeUrlToFile.called.should.equal(false)
|
return this.UrlFetcher.pipeUrlToFileWithRetry.called.should.equal(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
return it('should return the callback with the cache file path', function () {
|
return it('should return the callback with the cache file path', function () {
|
||||||
@@ -342,7 +342,7 @@ describe('UrlCache', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should clear the cache for each url in the project', function () {
|
it('should clear the cache for each url in the project', function () {
|
||||||
return Array.from(this.urls).map(url =>
|
return Array.from(this.urls).map((url) =>
|
||||||
this.UrlCache._clearUrlFromCache
|
this.UrlCache._clearUrlFromCache
|
||||||
.calledWith(this.project_id, url)
|
.calledWith(this.project_id, url)
|
||||||
.should.equal(true)
|
.should.equal(true)
|
||||||
|
|||||||
@@ -33,7 +33,42 @@ describe('UrlFetcher', function() {
|
|||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
})
|
})
|
||||||
|
describe('pipeUrlToFileWithRetry', function () {
|
||||||
|
this.beforeEach(function () {
|
||||||
|
this.UrlFetcher.pipeUrlToFile = sinon.stub()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should call pipeUrlToFile', function (done) {
|
||||||
|
this.UrlFetcher.pipeUrlToFile.callsArgWith(2)
|
||||||
|
this.UrlFetcher.pipeUrlToFileWithRetry(this.url, this.path, (err) => {
|
||||||
|
expect(err).to.equal(undefined)
|
||||||
|
this.UrlFetcher.pipeUrlToFile.called.should.equal(true)
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should call pipeUrlToFile multiple times on error', function (done) {
|
||||||
|
const error = new Error("couldn't download file")
|
||||||
|
this.UrlFetcher.pipeUrlToFile.callsArgWith(2, error)
|
||||||
|
this.UrlFetcher.pipeUrlToFileWithRetry(this.url, this.path, (err) => {
|
||||||
|
expect(err).to.equal(error)
|
||||||
|
this.UrlFetcher.pipeUrlToFile.callCount.should.equal(3)
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should call pipeUrlToFile twice if only 1 error', function (done) {
|
||||||
|
this.UrlFetcher.pipeUrlToFile.onCall(0).callsArgWith(2, 'error')
|
||||||
|
this.UrlFetcher.pipeUrlToFile.onCall(1).callsArgWith(2)
|
||||||
|
this.UrlFetcher.pipeUrlToFileWithRetry(this.url, this.path, (err) => {
|
||||||
|
expect(err).to.equal(undefined)
|
||||||
|
this.UrlFetcher.pipeUrlToFile.callCount.should.equal(2)
|
||||||
|
done()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('pipeUrlToFile', function () {
|
||||||
it('should turn off the cookie jar in request', function () {
|
it('should turn off the cookie jar in request', function () {
|
||||||
return this.defaults.calledWith({ jar: false }).should.equal(true)
|
return this.defaults.calledWith({ jar: false }).should.equal(true)
|
||||||
})
|
})
|
||||||
@@ -132,7 +167,7 @@ describe('UrlFetcher', function() {
|
|||||||
|
|
||||||
describe('with non success status code', function () {
|
describe('with non success status code', function () {
|
||||||
beforeEach(function (done) {
|
beforeEach(function (done) {
|
||||||
this.UrlFetcher.pipeUrlToFile(this.url, this.path, err => {
|
this.UrlFetcher.pipeUrlToFile(this.url, this.path, (err) => {
|
||||||
this.callback(err)
|
this.callback(err)
|
||||||
return done()
|
return done()
|
||||||
})
|
})
|
||||||
@@ -145,13 +180,15 @@ describe('UrlFetcher', function() {
|
|||||||
this.callback.calledWith(sinon.match(Error)).should.equal(true)
|
this.callback.calledWith(sinon.match(Error)).should.equal(true)
|
||||||
|
|
||||||
const message = this.callback.args[0][0].message
|
const message = this.callback.args[0][0].message
|
||||||
expect(message).to.include('URL returned non-success status code: 404')
|
expect(message).to.include(
|
||||||
|
'URL returned non-success status code: 404'
|
||||||
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
return describe('with error', function () {
|
return describe('with error', function () {
|
||||||
beforeEach(function (done) {
|
beforeEach(function (done) {
|
||||||
this.UrlFetcher.pipeUrlToFile(this.url, this.path, err => {
|
this.UrlFetcher.pipeUrlToFile(this.url, this.path, (err) => {
|
||||||
this.callback(err)
|
this.callback(err)
|
||||||
return done()
|
return done()
|
||||||
})
|
})
|
||||||
@@ -172,3 +209,4 @@ describe('UrlFetcher', function() {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user