Repository: octave-online/octave-online-server
Branch: master
Commit: dea7292195bc
Files: 321
Total size: 1.8 MB
Directory structure:
gitextract_lv487tfw/
├── .dockerignore
├── .editorconfig
├── .eslintignore
├── .eslintrc.yml
├── .gcloudignore
├── .github/
│ └── workflows/
│ └── build-test.yml
├── .gitignore
├── .npmrc
├── COPYING
├── Makefile
├── README.md
├── back-filesystem/
│ ├── .eslintrc.yml
│ ├── .npmrc
│ ├── README.md
│ ├── app.js
│ ├── git/
│ │ ├── create-repo-service.js
│ │ ├── create-repo.service
│ │ └── gitd.service
│ ├── package.json
│ └── src/
│ ├── controller.js
│ ├── fake-socket.js
│ ├── git-util.js
│ ├── logger.js
│ ├── mime.types
│ └── working-util.js
├── back-master/
│ ├── .eslintrc.yml
│ ├── .npmrc
│ ├── README.md
│ ├── app.js
│ ├── package.json
│ └── src/
│ ├── capped-file-system.js
│ ├── docker-handler.js
│ ├── main-flavor.js
│ ├── main-pool.js
│ ├── maintenance-request-manager.js
│ ├── maintenance.js
│ ├── message-translator.js
│ ├── octave-session.js
│ ├── process-handler.js
│ ├── session-impl.js
│ └── session-manager.js
├── back-octave/
│ ├── Makefile
│ ├── README.md
│ ├── host.c
│ └── oo-changesets/
│ ├── 000-README.md
│ ├── 001-d38b7c534496.hg.txt
│ ├── 002-d3de6023e846.hg.txt
│ ├── 003-4d28376c34a8.hg.txt
│ ├── 004-6ff3e34eea77.hg.txt
│ ├── 005-9e73fe0d92d5.hg.txt
│ ├── 006-15d21ceec728.hg.txt
│ ├── 007-4d778d6ebbd0.hg.txt
│ ├── 008-e8ef7f3333bf.hg.txt
│ ├── 009-05f7272c001e.hg.txt
│ ├── 010-4a1afb661c55.hg.txt
│ ├── 011-7327936fa23e.hg.txt
│ ├── 012-84390db50239.hg.txt
│ ├── 013-f4110d638cdb.hg.txt
│ ├── 014-21fd506b7530.hg.txt
│ ├── 100-2d1fd5fdd1d5.hg.txt
│ ├── 100-README.md
│ ├── 101-bc8cd93feec5.hg.txt
│ ├── 102-30d8ba0fbc32.hg.txt
│ ├── 103-352b599bc533.hg.txt
│ ├── 104-9475120a3110.hg.txt
│ ├── 105-ccbef5c9b050.hg.txt
│ ├── 106-91cb270ffac0.hg.txt
│ ├── 107-80081f9d8ff7.hg.txt
│ ├── 108-9b39ca8bcbfd.hg.txt
│ ├── 200-84cbf166497f.hg.txt
│ ├── 200-README.md
│ ├── 201-b993253f19d0.hg.txt
│ ├── 202-d9d23f97ba78.hg.txt
│ ├── 203-d6b5ffb8e4cc.hg.txt
│ ├── 204-e61d7b8918e2.hg.txt
│ ├── 300-d78448f9c483.hg.txt
│ ├── 301-97f7d1f4fe83.hg.txt
│ ├── 302-8900d7cf8554.hg.txt
│ ├── 310-1e1c91e6cddc.hg.txt
│ ├── 320-8d4683a83238.hg.txt
│ ├── 321-faad58416a3a.hg.txt
│ ├── 400-7ade2492e023.hg.txt
│ ├── 401-1b33dc797ec9.hg.txt
│ ├── 402-b01fa2864d4d.hg.txt
│ ├── 403-2813cb96e10f.hg.txt
│ ├── 404-acb523f25bb9.hg.txt
│ ├── 405-6ad34b0b69e1.hg.txt
│ ├── 406-d0df6f16f41e.hg.txt
│ ├── 407-df206dd11399.hg.txt
│ ├── 408-8184a51579f3.hg.txt
│ ├── 420-4c3d80dd9e65.hg.txt
│ ├── 421-de16dd99ab0e.hg.txt
│ ├── 422-de16dd99ab0e.hg.txt
│ └── 430-d2250ae9bddd.hg.patch
├── client/
│ ├── .bowerrc
│ ├── .gitignore
│ ├── .npmrc
│ ├── COPYING
│ ├── Gruntfile.js
│ ├── README.md
│ ├── app/
│ │ ├── .eslintrc.yml
│ │ ├── colab.html
│ │ ├── eula.txt
│ │ ├── fonts/
│ │ │ └── dejavusansmono_book/
│ │ │ ├── DejaVuSansMono-demo.html
│ │ │ ├── specimen_files/
│ │ │ │ ├── easytabs.js
│ │ │ │ ├── grid_12-825-55-15.css
│ │ │ │ └── specimen_stylesheet.css
│ │ │ └── stylesheet.css
│ │ ├── images/
│ │ │ ├── flaticons/
│ │ │ │ └── download-svg.ai
│ │ │ ├── logo_collections/
│ │ │ │ ├── official/
│ │ │ │ │ └── favicon_package/
│ │ │ │ │ ├── README.md
│ │ │ │ │ ├── browserconfig.xml
│ │ │ │ │ └── site.webmanifest
│ │ │ │ └── server/
│ │ │ │ └── favicon_package/
│ │ │ │ ├── README.md
│ │ │ │ ├── browserconfig.xml
│ │ │ │ └── site.webmanifest
│ │ │ └── sanscons/
│ │ │ └── license.txt
│ │ ├── js/
│ │ │ ├── ace-adapter.js
│ │ │ ├── ace-extras.js
│ │ │ ├── anal.js
│ │ │ ├── app.js
│ │ │ ├── base64-toBlob.js
│ │ │ ├── base64v1.module.js
│ │ │ ├── bucket.js
│ │ │ ├── client.js
│ │ │ ├── detectmobilebrowser.js
│ │ │ ├── download.js
│ │ │ ├── flex-resize.js
│ │ │ ├── ko-ace.js
│ │ │ ├── ko-flash.js
│ │ │ ├── ko-takeArray.js
│ │ │ ├── modernizr-201406b.js
│ │ │ ├── octfile.js
│ │ │ ├── onboarding.js
│ │ │ ├── ot-client.js
│ │ │ ├── ot-handler.js
│ │ │ ├── polyfill.js
│ │ │ ├── runtime.js
│ │ │ ├── utils.js
│ │ │ ├── vars.js
│ │ │ └── ws-shared.js
│ │ ├── main.js
│ │ ├── privacy.txt
│ │ ├── privacy_standalone.txt
│ │ └── styl/
│ │ ├── all.styl
│ │ ├── callouts.styl
│ │ ├── editor.styl
│ │ ├── flexbox.styl
│ │ ├── hamburger.styl
│ │ ├── header.styl
│ │ ├── mixins.styl
│ │ ├── modals.styl
│ │ ├── output_panel.styl
│ │ ├── print.styl
│ │ └── themes/
│ │ ├── official/
│ │ │ ├── fire.styl
│ │ │ ├── ice.styl
│ │ │ ├── lava.styl
│ │ │ └── sun.styl
│ │ └── server/
│ │ ├── fire.styl
│ │ ├── ice.styl
│ │ ├── lava.styl
│ │ └── sun.styl
│ ├── bower.json
│ └── package.json
├── config.sample.hjson
├── config_defaults.hjson
├── containers/
│ ├── README.md
│ ├── octave-deps/
│ │ ├── Dockerfile
│ │ └── cloudbuild.yaml
│ ├── octave-oo/
│ │ ├── Dockerfile
│ │ ├── cloudbuild.yaml
│ │ └── java.opts
│ ├── octave-pkg/
│ │ ├── Dockerfile
│ │ ├── README.md
│ │ ├── cloudbuild.yaml
│ │ ├── ltfat.patch
│ │ └── octaverc.m
│ ├── octave-stable/
│ │ ├── Dockerfile
│ │ └── cloudbuild.yaml
│ ├── oo-back/
│ │ ├── Dockerfile
│ │ └── cloudbuild.yaml
│ ├── oo-front/
│ │ ├── Dockerfile
│ │ └── cloudbuild.yaml
│ ├── oo-gith/
│ │ ├── Dockerfile
│ │ ├── cloudbuild.yaml
│ │ ├── nginx.conf
│ │ └── supervisord.conf
│ ├── oo-redirect/
│ │ └── cloudbuild.yaml
│ ├── oos-quick-start/
│ │ └── docker-compose.yaml
│ ├── utils-admin/
│ │ └── cloudbuild.yaml
│ ├── utils-gitd/
│ │ ├── Dockerfile
│ │ ├── cloudbuild.yaml
│ │ └── supervisord.conf
│ └── utils-gith/
│ ├── Dockerfile
│ ├── cloudbuild.yaml
│ └── supervisord.conf
├── entrypoint/
│ ├── .eslintrc.yml
│ ├── README.md
│ ├── back-selinux.js
│ ├── exit.js.sample
│ ├── oo-front.service
│ ├── oo-no-restart.service
│ ├── oo-reinstall.service
│ ├── oo.service
│ └── policy/
│ ├── octave_online.fc
│ ├── octave_online.if
│ ├── octave_online.te
│ ├── octave_online_supplement.if
│ └── octave_online_supplement.te
├── front/
│ ├── .eslintrc.yml
│ ├── .npmrc
│ ├── README.md
│ ├── locales/
│ │ ├── README.md
│ │ ├── en.yaml
│ │ └── qqq.yaml
│ ├── package.json
│ ├── src/
│ │ ├── app.ts
│ │ ├── back_server_handler.ts
│ │ ├── bucket_model.ts
│ │ ├── email.ts
│ │ ├── express_setup.ts
│ │ ├── flavor_record_model.ts
│ │ ├── mongo.ts
│ │ ├── octave_session_helper.ts
│ │ ├── ot_document.ts
│ │ ├── passport_setup.ts
│ │ ├── patreon.ts
│ │ ├── program_model.ts
│ │ ├── session_middleware.ts
│ │ ├── shared_wrap.ts
│ │ ├── socket_connect.ts
│ │ ├── socketio.ts
│ │ ├── user_model.ts
│ │ ├── utils.ts
│ │ ├── views/
│ │ │ ├── captcha_error.ejs
│ │ │ ├── incorrect_page.ejs
│ │ │ ├── index.ejs
│ │ │ ├── login_error.ejs
│ │ │ ├── partials/
│ │ │ │ ├── foot.ejs
│ │ │ │ └── head.ejs
│ │ │ ├── patreon_link_error.ejs
│ │ │ └── token_page.ejs
│ │ ├── workspace_normal.ts
│ │ └── workspace_shared.ts
│ ├── tsconfig.json
│ └── typings/
│ ├── easy-no-password.d.ts
│ ├── i18next-fs-backend.d.ts
│ ├── i18next-http-middleware.d.ts
│ ├── ot.d.ts
│ ├── pseudo-localization.d.ts
│ ├── socketio-file-upload.d.ts
│ └── socketio-wildcard.d.ts
├── package.json
├── redirect/
│ ├── README.md
│ ├── app.js
│ ├── bin/
│ │ └── server.js
│ ├── package.json
│ ├── src/
│ │ └── db.js
│ └── views/
│ └── error.ejs
├── shared/
│ ├── .eslintrc.yml
│ ├── .npmrc
│ ├── README.md
│ ├── async-cache.js
│ ├── config-helper.js
│ ├── config.js
│ ├── gcp/
│ │ ├── .npmrc
│ │ ├── fetch_translations.js
│ │ ├── index.js
│ │ ├── package.json
│ │ └── reboot_or_remove_self.js
│ ├── gitarchive.js
│ ├── hostname.js
│ ├── index.d.ts
│ ├── index.js
│ ├── json-stream-safe.js
│ ├── logger.js
│ ├── lua/
│ │ ├── get-sesscode.lua
│ │ ├── ot.lua
│ │ ├── ot_apply.lua
│ │ ├── ot_set.lua
│ │ └── ot_test.lua
│ ├── metrics.js
│ ├── once-message.js
│ ├── online-offline.js
│ ├── package.json
│ ├── queue.js
│ ├── redis-messenger.js
│ ├── redis-queue.js
│ ├── redis-util.js
│ ├── silent.js
│ ├── stackdriver/
│ │ ├── index.js
│ │ └── package.json
│ ├── stdio-messenger.js
│ └── time-limit.js
├── test/
│ ├── package.json
│ └── small-unit.js
├── utils-admin/
│ ├── .npmrc
│ ├── README.md
│ ├── app.js
│ ├── bin/
│ │ ├── repo-cleanup.js
│ │ └── server.js
│ ├── package.json
│ ├── public/
│ │ └── stylesheets/
│ │ └── style.css
│ ├── routes/
│ │ ├── index.js
│ │ └── users.js
│ ├── src/
│ │ ├── db.js
│ │ └── repo.js
│ └── views/
│ ├── error.ejs
│ ├── find.ejs
│ ├── index.ejs
│ ├── partials/
│ │ ├── footer.ejs
│ │ └── header.ejs
│ ├── user-list.ejs
│ └── user.ejs
└── utils-auth/
├── .eslintrc.yml
├── .npmrc
├── README.md
├── app.js
├── configs/
│ ├── custom_4xx.html
│ ├── gitlist.ini
│ └── oo-utils-auth.service
└── package.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .dockerignore
================================================
.git/
**/_old
**/node_modules
**/tmp
**/vendor
================================================
FILE: .editorconfig
================================================
root = true
[*]
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
charset = utf-8
# Default to tab indentation (narrow 2-column size)
indent_style = tab
indent_size = 2
# Specific exceptions using space indentation
[*.{json,yml}]
indent_style = space
indent_size = 2
================================================
FILE: .eslintignore
================================================
node_modules/
node_modules_1/
vendor/
dist/
build/
client/app/fonts/
_old/
front/
front2/
*.d.ts
================================================
FILE: .eslintrc.yml
================================================
env:
es6: true
node: true
extends: 'eslint:recommended'
parserOptions:
ecmaVersion: 2018
rules:
indent:
- error
- tab
- SwitchCase: 1
linebreak-style:
- error
- unix
quotes:
- error
- double
semi:
- error
- always
================================================
FILE: .gcloudignore
================================================
#!include:.gitignore
.git/
================================================
FILE: .github/workflows/build-test.yml
================================================
name: Node.js CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 10.x
- name: Install
run: |
touch config.hjson
npm ci
(cd test && npm ci)
- name: Test
run: |
(cd test && npm test)
env:
CI: true
- name: Lint
run: npm run lint
================================================
FILE: .gitignore
================================================
# Copyright © 2018, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server. If not, see
# .
# Directory names that should not be tracked
_old/
bundle/
dist/
node_modules/
node_modules_1/
vendor/
tmp/
front/static/
# File extensions that should not be tracked
*.bak
*.log
*.o
*.out
*.pem
*.pub
*.pp
# Specific files to omit
.env
config.hjson
back-octave/octave-host
back-octave/bin/cwd/
entrypoint/exit.js
entrypoint/front_setup.js
================================================
FILE: .npmrc
================================================
# Please keep this in sync with all other .npmrc files
# SEE: https://github.com/npm/feedback/discussions/864
install-links=false
================================================
FILE: COPYING
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
================================================
FILE: Makefile
================================================
# Copyright © 2018, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server. If not, see
# .
SHELL := /bin/bash
NODE = node
# Read options from config file
# \n is replaced with \1 because gnumake removes \n from ${shell}. See: https://stackoverflow.com/q/54067438/1407170
get_config = ${shell $(NODE) -e "console.log(require('./shared').config.$(1))" | tr '\n' '\1'}
GIT_HOST = $(call get_config,git.hostname)
GIT_DIR = $(call get_config,docker.gitdir)
WORK_DIR = $(call get_config,docker.cwd)
OCTAVE_SUFFIX = $(call get_config,docker.images.octaveSuffix)
FILES_SUFFIX = $(call get_config,docker.images.filesystemSuffix)
JSON_MAX_LEN = $(call get_config,session.jsonMaxMessageLength)
CGROUP_CONF = $(call get_config,selinux.cgroup.conf)
install-selinux-policy:
# yum install -y selinux-policy-devel policycoreutils-sandbox selinux-policy-sandbox
cd entrypoint/policy && make -f /usr/share/selinux/devel/Makefile octave_online.pp
semodule -i entrypoint/policy/octave_online.pp
restorecon -R -v /usr/local/lib/octave
restorecon -R -v /tmp
restorecon -R -v /srv/oo
setenforce enforcing
echo "For maximum security, make sure to put SELinux in enforcing mode by default in /etc/selinux/config."
install-selinux-bin:
cp entrypoint/back-selinux.js /usr/local/bin/oo-back-selinux
# TODO: Put in /etc instead of /usr/lib?
cp entrypoint/oo.service /usr/lib/systemd/system/oo.service
systemctl daemon-reload
echo "$(CGROUP_CONF)" | tr '\1' '\n' > /etc/cgconfig.d/oo.conf
echo "Run `systemctl restart cgconfig.service` to load changes to cgroup configurations."
systemctl enable cgconfig
ln -sf $$PWD /usr/local/share/oo
install-site-m:
echo "This command is no longer supported. See containers/octave-pkg/Dockerfile."
enable-graceful-shutdown:
cp entrypoint/oo-no-restart.service /usr/lib/systemd/system/oo.service;
systemctl daemon-reload;
echo "Tip 1: Consider removing entrypoint/exit.js if it could cause disruption";
echo "Tip 2: Consider sending SIGUSR1 to the server process to start a graceful shutdown";
lint:
cd back-filesystem && npm run lint
cd back-master && npm run lint
cd shared && npm run lint
cd utils-auth && npm run lint
clean:
if [[ -e bundle ]]; then rm -rf bundle; fi
================================================
FILE: README.md
================================================
Octave Online Server
====================
This repository contains the full stack of code to run Octave Online Server, the infrastructure that powers [Octave Online](https://octave-online.net).
[](https://github.com/octave-online/octave-online-server/actions)
## High-Level Overview
There are three separate components of Octave Online Server:
1. **Client**: Code that runs in the browser.
2. **Front Server**: Authentication, client session handling.
3. **Back Server**: File I/O, Octave process handling.
*Communication:* The Client and Front Server communicate primarily with WebSockets via [socket.io](https://socket.io); the Front Server and Back Server communicate primarily with [Redis PubSub](https://redis.io/topics/pubsub). User account information is stored in [MongoDB](https://www.mongodb.com) and is accessed primarily from the Front Server. User files are stored in [Git on the Server](https://git-scm.com/book/en/v1/Git-on-the-Server) and are accessed primarily from the Back Server.
*Scaling:* Front Servers and Back Servers can be scaled independently (in general, you need more Back Servers than Front Servers). It is also possible to run both the Front Server and the Back Server on the same computer.
*Languages:* All code is written with JavaScript technologies, although for historical reasons, the three components use different flavors of JavaScript. The Client uses ES5; the Front Server uses TypeScript; and the Back Server uses ES6.
## Quick Start
Read [containers/README.md](containers/README.md) for details on running a containerized version of all of Octave Online Server for use with trusted users. This is the fastest way to get off the ground.
## Manual Installation
*Note:* Octave Online Server has a lot of moving parts. It is recommended that you feel comfortable with basic system administration before attempting an installation.
For more details on operating each of the three components, see the respective README files:
- [back-master/README.md](back-master/README.md) (back server)
- [front/README.md](front/README.md) (front server)
- [client/README.md](client/README.md) (client)
There are also a few more directories for other components:
- [back-filesystem/README.md](back-filesystem/README.md) for filesystem I/O on the back server
- [back-octave/README.md](back-octave/README.md) for GNU Octave bindings for the back server
- [entrypoint/README.md](entrypoint/README.md) for helper scripts to run Octave Online Server
- [shared/README.md](shared/README.md) for code shared by multiple components
- [utils-admin/README.md](utils-admin/README.md) for an optional admin panel
- [utils-auth/README.md](utils-auth/README.md) for an optional standalone user authentication service
Every subdirectory of the top-level Octave Online Server directory has a README file that explains what the contents of the directory is for.
### Prerequisites
[Required] *Operating System:* Octave Online Server is built and tested exclusively on GNU/Linux. It is recommended that you use CentOS 8, although other modern distributions should work also. Most of Octave Online Server should work on macOS, but this has not been tested.
[Required] *Node.js:* Octave Online Server is built and tested with Node.js LTS version 10. This is the default version on CentOS 8.
# Install Node.js 10.x LTS on CentOS 8:
$ sudo yum install nodejs
[Required] *Redis:* Install and run a local Redis instance. Enable expiration events in `redis.conf`:
$ sudo yum install redis
$ sudo emacs redis.conf
# Search for "notify-keyspace-events"
# Set the value to "Ex"
Although it is possible to use a third-party hosted Redis instance, this is not recommended because Redis latency is amplified due to its central role in the Octave Online Server architecture.
[Recommended] *Git Server:* In order to persist user files between sessions, you need to set up a Git file server. It boils down to a server, which could be the current server, with a low-privileged user usually named "git". For more information, see [Git on the Server](https://git-scm.com/book/en/v1/Git-on-the-Server). Also see [back-filesystem/README.md](back-filesystem/README.md) for instructions on how to configure a Git file server for Octave Online Server.
[Recommended] *MongoDB:* Install and run a MongoDB instance. Unlike Redis, MongoDB is not as central of a piece in the infrastructure, so it is possible to use a remotely hosted MongoDB if you do not want to host it locally. My experience is that it takes some time to correctly configure a fast and secure MongoDB installation. Keep in mind that MongoDB will contain personally identifiable information for user accounts.
[Recommended] *Email SaaS:* If you want Octave Online Server to be able to send transactional emails, such as for email-based login, you need a [Mailgun](https://www.mailgun.com) or [Postmark](https://postmarkapp.com) account. Mailgun has a free tier that should cover most experimental and low-traffic usage.
[Recommended] *ReCAPTCHA:* Certain actions, such as when email is sent, require a CAPTCHA to prevent abuse. You should register for a [ReCAPTCHA](https://www.google.com/recaptcha/) v2 Checkbox and put your credentials into your config.hjson file.
[Optional] *Google Analytics:* For aggregated statistics about traffic to your site, you can enable [Google Analytics](https://www.google.com/analytics/) integration.
[Optional] *Nginx:* For better performance with serving static files and easier HTTPS setup, I recommend installing and configuring [Nginx](https://www.nginx.com). However, this is not an essential piece, and it can be done after the rest of the infrastructure is up and running.
### Configuration File
Read `config_defaults.hjson` to learn more about the array of settings available for Octave Online Server. When ready, copy `config.sample.hjson` into `config.hjson`, and fill in the required details. Your own `config.hjson` is ignored by source control.
### Installing Depencencies and Building
In each of the five directories containing Node.js projects, go in and run `npm install`:
$ (cd shared && npm install)
$ (cd back-filesystem && npm install)
$ (cd back-master && npm install)
$ (cd front && npm install)
$ (cd client && npm install)
You also need to install the Bower (client-side) dependencies for the client project:
$ (cd client && npm run bower install)
Finally, build the client and front server projects (the back server runs without needing to be built):
$ (cd client && npm run grunt)
$ (cd front && npm run grunt)
### Configuring GNU Octave
Octave Online Server requires a special version of GNU Octave, which needs to be built. *This is a required step.* For more information, see [back-master/README.md](back-master/README.md).
### Running Octave Online Server
To run the code manually, just open up two terminals and run each of the following two commands:
$ (cd back-master && DEBUG=* node app.js)
$ (cd front && node app.js)
To run the code as a service, you can install the systemd service provided in this repository and enable the code to be automatically run at startup; see *entrypoint/oo.service* and `make install-selinux-bin`.
**Tip:** When debugging, you can modify your hosts file (on macOS, /private/etc/hosts) to create a stable URL that you can add to your Google developer console to allow Google services to work.
## Contributing
You are welcome to send pull requests for consideration for addition to Octave Online Server. Pull requests are not guaranteed to be accepted; if in doubt, you should open an issue to discuss your idea before spending time writing your pull request.
### Contributor License Agreement
Like many projects distributed with copyleft licenses such as AGPL, contributors to Octave Online Server must sign a Contributor License Agreement (CLA). The terms of the [Octave Online CLA](https://cla-assistant.io/octave-online/octave-online-server) are taken from [The Apache Software Foundation CLA](https://www.apache.org/licenses/contributor-agreements.html). Having a CLA in place enables Octave Online Server to be distributed with alternate licensing schemes, including commercial licenses that help keep the project afloat.
### Style
If in doubt on style, follow the convention of the file you are editing.
**Wrapping and Indentation:** Use tab indentation, unless in a file format such as *.yml* that requires space indentation. There is no limit on line length. This gives you full control to configure your editor to your desired width and tab size.
**Naming:** In general, use camelCase for variable names and MACRO_CASE for constants. Prefix private members with an underscore (`_`).
**Quotes:** Use double-quoted strings, unless you are in a context where you need a different quotation style, such as backtick strings in JavaScript.
**Internationalization (i18n/l10n):** If possible, all new UI strings should be extracted into *en.yaml* so that they can be translated. For more details, see [front/locales/README.md](front/locales/README.md).
**Upstream/Downstream:** Throughout the code, there are comments and function names indicating "upstream" and "downstream". "Upstream", or "U", means toward the Octave process, away from the client. "Downstream", or "D", means toward the client, away from the Octave process. So, for example, a message sent from the back server to the front server is considered downstream, and a message sent from the back server to the Octave process is considered upstream.
**ECMAScript Versions:** JavaScript code in the *client* project should conform to the ECMAScript 5 standard, in order to have broad browser support. JavaScript in all other projects can use the latest ECMAScript standard supported by Node.js 6.x LTS. By design, all JavaScript code in Octave Online Server server should be able to be run natively without transcompilation to a different ECMAScript version.
### Linting
The *eslint* tool will catch most style and compatibility issues in JavaScript files. Execute `npm run lint` in the top-level directory to check for errors. If your code does not pass *eslint*, you will also trigger a Travis failure on GitHub.
### Manual Testing
Due to the complexity of Octave Online Server, there is not currently an automated test suite. As a contributor, you are expected to perform some manual testing to ensure that your feature does not accidentally break something else in Octave Online Server.
Here are some critical user journeys that test a fairly wide cross-section of the code base. **Please make sure that all of these journeys continue working after your change.**
1. The core file editor
1. Sign in if necessary
1. Create a new file
1. Open the new file in the editor and make some changes
1. The file should appear dirty (unsaved): its name should be italic and underlined
1. Save the file; it should no longer appear dirty
1. Press the "Refresh Files" button; your file should go away and reappear a few seconds later with the same changes you had made
1. Click the following the buttons in the file toolbar, and make sure they behave as expected:
- "Download File"
- "Print File"
- "Toggle Word Wrap"
- "Save File" (make some changes first)
- "Run Script"
1. Create a file named `.octaverc` with the following content:
```rcx = 5;```
1. Run the `exit` command, then click the reconnect link
1. Once the workspace loads, check that the variable `rcx` exists and has value 5
1. Collaborative workspaces
1. Sign in if necessary
1. Open the side bar menu and enable workspace sharing if necessary
1. Open the sharing link in another window
1. Repeat all of the steps from the "core file editor" journey, mixed between the two windows, and make sure that all state gets updated as expected
1. Plotting and image processing
1. In the main command prompt, make some standard plots like `sombrero()` and `fplot(@sin, [-pi pi])`, and ensure they appear as expected
1. Open the plot window. You should be able to scroll through your plots. Ensure that the two download buttons work as expected (download as PNG and as SVG)
1. Sign in if necessary
1. Download a full-color image from [PNGNQ](http://pngnq.sourceforge.net/pngnqsamples.html); I usually use mandrill.png
1. Drag the PNG file onto the file list until it turns yellow; drop the file to upload it
1. Select the file in the list; make sure "Download File" and "Rename File" work
1. Click the "DELETE File" button to delete the file
1. Upload the file again, this time using the "Upload file" button in the file list toolbar
1. In the command prompt, run the following command: `imshow(imread("mandrill.png"))`; you should see the full-color image appear in the console output window (there is a surprisingly large amount of code that is needed to make this happen)
1. Buckets and Projects
1. Sign in if necessary
1. Create or upload multiple files if you don't already have files in your workspace
1. Open a script file that runs by itself (not a function file)
1. Click the "Share File in new Bucket" button
1. Play around with the options, adding new files and selecting a main file
1. Click "Create Bucket"
1. Ensure that the bucket creates successfully and that the main file runs
1. Click the bucket ID in the title bar. An information panel should appear with details about the bucket. Make sure they look correct
1. Click the pencil icon to edit the shortlink; change it to "test999"
1. Go to "octav.onl/test999"; the redirect should work and the same bucket page should open
1. Click "Fork This Bucket"
1. Enter "test999" as the custom URL in the "Create Project" screen. Click "Create Project"; a second or two later, you should see an alert box saying that there is a duplicate link
1. Change the shortlink so that it contains illegal characters, like "$". Click "Create Project" again; a second or two later, you should see an alert saying that the shortlink has invalid characters
1. Close the "Customize Project" dialog box, then reopen it by clicking "Fork This Bucket" again
1. This time, click "Create Project" without changing any other settings. Your browser should refresh into the new project
1. Ensure that you can edit and save files in the project
1. Open the info panel for the project by clicking it in the title bar. You should see the bucket name under "Forked From"
1. Close the info bar, then open the side bar menu
1. Find the bucket and project you created; ensure that the timestamps is correct
1. Save the links to both the bucket and the project
1. Press the "⌫" button to delete the bucket and then the project
1. Once deleted, go back to the bucket and the project with the links you saved, and ensure that the bucket and project are actaully deleted
1. Small interpreter features
1. Run a few lines of code and then run `clc`; it should clear all output from the console window
1. Run `doc fplot`; it should produce a working link
1. Run `char(randi(256, 1000, 1)' .- 1)`; it should print a nonsense string with a lot of replacement characters
1. Run `O = urlread("http://example.com")`; it should finish without error and print the HTML content of that page
1. Run `O = urlread("https://example.com")`; it should print the same HTML as the previous line (http vs https)
1. Run `O = urlread("http://cnn.com")`; it should print an error saying that the domain is not in the whitelist (unless you added that domain to your custom whitelist)
1. Run `ping`; you should see a response like "Ping time: 75ms"
1. Run `pause; disp("done")`; you should see a message "press enter to continue". Press enter, and then you should see "done" printed out to the console
1. Octave feature coverage
1. Run `gf`; you should see a message "Run 'pkg load communications' to use 'gf'"
1. Run `pkg load communications` and then `help gf`; you should get a help page
1. Run `audioread("dummy.wav")`; you should get an error that the file does not exist (but you should NOT get an error that says libsndfile was not installed)
1. Run `fork`; you should see a message "error: 'fork' undefined near line 1, column 1"
1. Student / instructor features
1. Create two accounts if you do not already have two accounts
1. In one account, add a string to the `instructor` field in mongodb; for example, `"test-course"`
1. Sign in to Octave Online Server using the other account
1. Run `enroll("test-course")` and follow the onscreen instructions
1. Sign out and sign into the first account, the one with the instructor field
1. Ensure that the student is listed in the menu bar
1. Sign out and back into the student account
1. Open the menu and try disabling sharing; it should deny permission
1. Run `enroll("default")` and follow the onscreen instructions
1. Open the menu and try disabling sharing again; it should work this time
1. Network connection and reconnecting to a session
1. Open your Octave Online Server as a guest user (not signed in)
1. Type `x = 5` and press Enter, followed by `x` and Enter, to ensure that the variable is set correctly
1. Terminate (Ctrl-C) your front server process and quickly restart it
1. The loading animation should appear on the browser window, and the animation should go away once the front server has finished restarting. In addition, the phrase "Connection lost. Attempting to reconnect..." should be printed to the console window. When the server reconnects, the prompt should activate
1. Type `x` and Enter; the variable should still have the value 5
1. Type `exit`; it should say "Octave Exited. Message: Shell Exited", and you should get a link that says "Click Here to Reconnect"
1. Terminate (Ctrl-C) your front server process and quickly restart it
1. The loading animation should appear on the browser window, and the animation should go away once the front server has finished restarting. However, you should NOT get the "Connection lost" message printed to the console, and you should NOT get an active prompt automatically after the animation goes away
1. Press the "Click Here to Reconnect" button; you should now get an active command prompt. Run a command or two to make sure the session is working normally
1. For an exhaustive test, repeate this section as (i) a signed-in user, (ii) a session with sharing enabled, and (iii) a bucket session.
1. Reconnecting to and expiring collaborative workspaces
1. Sign in to a user that has sharing enabled
1. *Ensure that no one else is viewing the user's workspace* (for example, there should be no red cursors at the command prompt)
1. Set a variable like `x = 99`
1. Reload the browser window; it should be the same session. Check that `x` is still `99`
1. Close the browser window without exiting explicitly
1. Wait for `config.redis.expire.timeout` milliseconds to ellapse, then open up a new tab for that user; it should be a new session. Check that `x` is no longer set to `99`
1. GUI: Flexbox panels and CSS
1. Hover over the border between panels; a slider should appear. Drag the slider around to resize the panels
1. Open the menu and click "Change/Reset Layout"; the panel sizes should reset to the defaults
1. Open the menu and click "Change Theme"; you should get a dark theme. Clicking the button again should change the theme back
1. GUI: Function arguments and filenames
1. Run the command `edit demo_fn.m`; it should create a new file with that name and open it in the editor
1. Enter the following content for that file:
```
function [o] = demo_fn(x)
o = x*2;
endfunction
```
1. Click the "Run" button. You should get a prompt asking you for the value of x. Enter a value such as 3. You should now see `ans = 6` in the console output window
1. Press Command+R or Control+R. The same prompt should appear
1. Attempt to create another new file with the same name, `demo_fn.m`, using the "Create empty file" button. You should not be able to create a file with that name since it already exists
1. GUI: Command prompt features
1. Type `fpl` into the prompt box, then hit TAB. You should get a menu of auto-completions like `fplot`
1. Run several commands, such as `x=1` then `x=2` then `x=3`. Press the up arrow. You should be able to scroll through your command history
1. You should see "x" in the Vars menu. Click on the x. A dialog should open telling you the current value of x
1. Within the command output panel, click on command text, to the right of the "octave:#>". That command should appear in the URL bar
1. Reload the page. The command you clicked (the one now in the URL) should be automatically executed after the page loads
1. GUI: Legal and account management
1. Open the side bar menu. Click on "Privacy Policy and EULA". A dialog should open showing that content
1. Make sure you are signed in
1. Click "Change Password". Follow the instructions to change the password
1. Sign out and sign back in using your new password to make sure it worked
1. GUI: Folders
1. Use the "Create empty file" button to create a file named "dir1/foo.m". It should create a file in that subdirectory, "dir1", shown in the file list panel
1. Enter the command `cd dir1`; you should now be changed into that directory and there should be a small window reminding you in the top left of the console output window
1. Pushing the limits: File Size
1. Make sure you are *not* signed in
1. Run the following command line; it should finish without any errors:
```A = rand(500); save A.mat; load A.mat```
1. Run the following command line; it should produce the error "load: failed to load matrix constant", due to hitting the 20 MB file size limit per workspace:
```A = rand(5000); save A.mat; load A.mat```
1. Pushing the limits: Message Size
1. Run the following command line; it should finish without any errors and produce a busy line plot:
```plot(rand(100));```
1. Run the following command line; it should produce the error "Warning: Suppressed a large plot", due to hitting the 1 MB limit on message size and therefore plot size:
```plot(rand(300));```
1. Pushing the limits: Countdown / Time Limit
1. Run the following command:
```pause(12)```
1. When the "Add 15 Seconds" link appears, click it
1. Ensure that the time runs out after 12 seconds from the original entry of the command
1. Pushing the limits: Payload and signals
1. Run the following command:
```x = 0; while(true), x += 1, end```
1. The variable `x` should get to somewhere between 1500 and 2000 before being paused for payload
1. Click the "Resume Execution" button, and `x` should climb by approximately the same amount
1. Click the x button to stop execution. There may be a bit more output, but you should soon be returned to the command prompt
1. Repeat the above steps, but instead of clicking the x button, wait for the payload timeout to finish on its own and return you to the command prompt
Tip: A community member like you could implement an automated end-to-end test suite. If this is your area of expertise, please open an issue and engage!
## License
Octave Online Server is licensed under the [GNU Affero General Public License](https://en.wikipedia.org/wiki/Affero_General_Public_License).
> Octave Online Server is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
>
> Octave Online Server is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
A copy of the license can be found in COPYING.
Note: You may contact webmaster@octave-online.net to inquire about other options for licensing Octave Online Server.
================================================
FILE: back-filesystem/.eslintrc.yml
================================================
================================================
FILE: back-filesystem/.npmrc
================================================
# Please keep this in sync with all other .npmrc files
# SEE: https://github.com/npm/feedback/discussions/864
install-links=false
================================================
FILE: back-filesystem/README.md
================================================
Octave Online Server: Back Server, Filesystem Utilities
=======================================================
This directory contains the source code dealing with the filesystem for the Octave Online Server back server. It also contains scripts for interacting with the Git file server.
## Git File Server
The subdirectory *git* contains files for running a Git file server for Octave Online Server.
*gitd.service* is a systemd service that enables the Git daemon with the repository root at */srv/oo/git*, which is expected to contain *repos* and *buckets* subdirectories that are read/write to the *git* user.
*create-repo.service* is a systemd service that runs a tiny server for creating empty repositories. It has the same path expectations as *gitd.service*. It invokes the path */usr/local/bin/create-repo-service*, which is expected to be a copy of *create-repo-service.js* from this project.
**CAUTION:** Neither *gitd.service* nor *create-repo.service* require any authentication. You should therefore run these services behind a firewall.
## History
When using the SELinux backend, the code in this directory is run in the main event loop (Node.js process) along with the *back-master* code. When the Docker backend is used, however, this code runs inside of a Docker container, while *back-master* runs outside of a Docker container.
This separation was done in order to make file permissions work correctly. However, this separation is one reason why the Docker implementation is not able to handle as many concurrent sessions as the SELinux implementation.
================================================
FILE: back-filesystem/app.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
// This is the entrypoint for a standalone version of back-filesystem, used by the Docker mode but NOT the SELinux mode.
const messenger = new (require("@oo/shared").StdioMessenger)();
const log = require("@oo/shared").logger("app");
const FilesController = require("./src/controller");
// Customize options on the logger
require("./src/logger");
// Read command-line arguments
const GIT_DIR = process.argv[2];
const WORK_DIR = process.argv[3];
log.info("Dirs:", GIT_DIR, WORK_DIR);
// Make an instance of controller
var controller = new FilesController(GIT_DIR, WORK_DIR, "");
// Set up the STDIO messenger instance so we can talk to the master
messenger._log = require("@oo/shared").logger("messenger");
messenger.setReadStream(process.stdin);
messenger.setWriteStream(process.stdout);
messenger.on("message", (name, content) => {
controller.receiveMessage(name, content);
});
controller.on("message", (name, content) => {
messenger.sendMessage(name, content);
});
messenger.on("error", (err) => {
log.error("messenger:", err);
});
// Send acknowledgement message downstream
messenger.sendMessage("ack", true);
================================================
FILE: back-filesystem/git/create-repo-service.js
================================================
#!/usr/bin/env node
/*
* Copyright © 2019, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
/* eslint-disable no-console */
const child_process = require("child_process");
const fs = require("fs");
const http = require("http");
const path = require("path");
const url = require("url");
if (process.argv.length !== 4) {
console.error("Usage: node create-repo-service.js /path/to/git/root PORT");
process.exit(1);
}
const gitRoot = process.argv[2];
const port = parseInt(process.argv[3]);
http.createServer((req, res) => {
const { query } = url.parse(req.url, true);
const isoTime = new Date().toISOString();
if (["buckets", "repos"].indexOf(query.type) === -1) {
res.writeHead(400, "Invalid type");
console.log(`create-repo-service: ${isoTime} Invalid type`);
return res.end();
}
if (!query.name || !/^[\w]+$/.test(query.name)) {
res.writeHead(400, "Invalid name");
console.log(`create-repo-service: ${isoTime} Invalid name`);
return res.end();
}
const bareRepoPath = path.join(gitRoot, query.type, query.name + ".git");
fs.stat(bareRepoPath, (err) => {
const exists = !err;
let process;
if (query.action === "delete") {
if (exists) {
process = child_process.spawn("rm", ["-rf", bareRepoPath]);
} else {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Already Deleted\n");
console.log(`create-repo-service: ${isoTime} Already Deleted: ${bareRepoPath}`);
return;
}
} else {
if (exists) {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Already Created\n");
console.log(`create-repo-service: ${isoTime} Already Created: ${bareRepoPath}`);
return;
} else {
process = child_process.spawn("git", ["init", "--bare", bareRepoPath]);
}
}
let resData = Buffer.alloc(0);
process.stdout.on("data", (chunk) => {
resData = Buffer.concat([resData, chunk]);
});
process.stderr.on("data", (chunk) => {
resData = Buffer.concat([resData, chunk]);
});
process.on("exit", (code /* , signal */) => {
const operation = (query.action === "delete") ? "Delete" : "Init";
if (code === 0) {
res.writeHead(200, { "Content-Type": "text/plain" });
res.write(`${operation} Success\n`);
console.log(`create-repo-service: ${isoTime} ${operation} Success: ${bareRepoPath}`);
} else {
res.writeHead(500, { "Content-Type": "text/plain" });
res.write(`${operation} Error\n`);
console.log(`create-repo-service: ${isoTime} ${operation} Error: ${bareRepoPath}`);
console.log(`create-repo-service: ${resData.toString("utf-8")}`);
}
res.write(resData);
res.end();
});
});
}).listen(port);
console.log("create-repo-service: Listening on port", port);
================================================
FILE: back-filesystem/git/create-repo.service
================================================
# Copyright © 2019, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server. If not, see
# .
###############################################################
# NOTE: This systemd service file is here for reference only; #
# it is not currently being used in Octave Online Server. #
###############################################################
[Unit]
Description=Service to create and delete bare git repos
[Service]
ExecStart=/usr/local/bin/create-repo-service /srv/oo/git 3003
Environment=NODE_ENV=production
Restart=always
StandardOutput=syslog
StandardError=syslog
User=git
Group=git
[Install]
WantedBy=multi-user.target
================================================
FILE: back-filesystem/git/gitd.service
================================================
# Copyright © 2019, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server. If not, see
# .
###############################################################
# NOTE: This systemd service file is here for reference only; #
# it is not currently being used in Octave Online Server. #
###############################################################
[Unit]
Description=Start Read-Write Git Daemon
[Service]
ExecStart=/usr/bin/git -c daemon.receivepack=true daemon --verbose --reuseaddr --export-all --base-path=/srv/oo/git /srv/oo/git
Restart=always
RestartSec=500ms
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=git-daemon
User=git
Group=git
[Install]
WantedBy=multi-user.target
================================================
FILE: back-filesystem/package.json
================================================
{
"name": "@oo/files",
"version": "0.0.0",
"description": "Reads and writes to an Octave session working directory",
"main": "app.js",
"scripts": {},
"author": "Octave Online LLC",
"license": "AGPL-3.0",
"private": true,
"engines": {
"node": "18.x"
},
"dependencies": {
"@oo/shared": "file:../shared",
"async": "^1.5.2",
"charset-detector": "0.0.2",
"debug-logger": "^0.4.1",
"iconv": "^3",
"mime": "^1.3.4",
"socketio-file-upload": "^0.4.4",
"sprintf-js": "^1.0.3"
}
}
================================================
FILE: back-filesystem/src/controller.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const async = require("async");
const GitUtil = require("./git-util");
const WorkingUtil = require("./working-util");
const path = require("path");
const SocketIOFileUploadServer = require("socketio-file-upload");
const config = require("@oo/shared").config;
const FakeSocket = require("./fake-socket");
const logger = require("@oo/shared").logger;
const EventEmitter = require("events");
class FilesController extends EventEmitter {
constructor(gitDir, workDir, logMemo) {
super();
this._log = logger(`files-controller:${logMemo}`);
this._mlog = logger(`files-controller:${logMemo}:minor`);
this.gitUtil = new GitUtil(gitDir, logMemo);
this.workingUtil = new WorkingUtil(workDir, logMemo);
this.workDir = workDir;
this.user = null;
this.bucketId = null;
this.ready = false;
this.destroyed = false;
this.fakeSocket = new FakeSocket();
this.fakeSocket.on("_emit", this._sendMessage.bind(this));
this._setupUploader();
}
// Returns whether Git operations are safe to perform.
// Check this.ready for whether file operations (without git) are safe.
_isInitialized() {
return this.ready && (this.user !== null || this.bucketId !== null);
}
// Returns whether either "user-info" or "bucket-info" has been called
_isSetUp() {
return this.user || this.bucketId || this.ready;
}
receiveMessage(name, content) {
switch (name) {
case "user-info": {
if (this._isSetUp()) {
this._log.error("user-info called, but already set up:", content);
return;
}
this.user = content.user;
if (this.user) {
this._log.info("Received user:", this.user.consoleText);
this._legalTime = content.legalTime; // FIXME: For backwards compatibility
} else {
this._log.info("No user this session");
this.ready = true;
this._sendMessage("files-ready", {});
return;
}
async.waterfall([
(_next) => {
this.gitUtil.initialize(this.user, this.workDir, _next);
},
(results, _next) => {
this.workingUtil.hasOctaverc(_next);
},
(hasOctaverc, _next) => {
this.ready = true;
this._sendMessage("files-ready", { hasOctaverc });
_next(null);
},
(_next) => {
this.workingUtil.listAll(_next);
}
], (err, fileData) => {
if (err) {
if (/unable to write file/.test(err.message)) {
return this._fail("filelist", "warn", `Whoops! You are currently exceeding your space limit of ${config.docker.diskQuotaKiB} KiB.\nPlease open a support ticket and we will help you resolve the\nissue. Sorry for the inconvenience!`);
} else {
if (this._logError("initialize", err)) {
this._fail("filelist", "warn", "Unable to load your files from the server: please try again.");
}
return;
}
}
this._mlog.debug("User successfully initialized");
this._sendMessage("filelist", {
success: true,
legalTime: this._legalTime, // FIXME: for backwards compatibility
files: fileData,
refresh: false
});
});
break;
}
case "bucket-info": {
if (this._isSetUp()) {
this._log.error("bucket-info called, but already set up:", content);
return;
}
this.bucketId = content.id;
this._legalTime = content.legalTime; // FIXME: For backwards compatibility
// If content.readonly is false, this request is for a project or for creating the bucket. If content.readonly is true, this request is for reading from the bucket.
this._log.info("Received bucket:", this.bucketId, content.readonly);
async.waterfall([
(_next) => {
this.gitUtil.initializeBucket(this.bucketId, this.workDir, content.readonly, _next);
},
(results, _next) => {
this.workingUtil.hasOctaverc(_next);
},
(hasOctaverc, _next) => {
this.ready = true;
this._sendMessage("files-ready", { hasOctaverc });
_next(null);
},
(_next) => {
this.workingUtil.listAll(_next);
}
], (err, fileData) => {
if (err) return this._logError("bucket", err);
this._mlog.debug("Bucket successfully initialized");
this._sendMessage("filelist", {
success: true,
legalTime: this._legalTime, // FIXME: for backwards compatibility
files: fileData,
refresh: false
});
});
break;
}
case "list": {
if (!this.ready) return this._mlog.warn("list: not ready");
this._mlog.debug("Listing files...");
async.waterfall([
(_next) => {
this.workingUtil.listAll(_next);
}
], (err, fileData) => {
if (err) return this._logError("list", err);
this._log.debug("Files successfully listed");
this._sendMessage("filelist", {
success: true,
legalTime: this._legalTime, // FIXME: for backwards compatibility
files: fileData,
refresh: false
});
});
break;
}
case "refresh": {
if (!this._isInitialized()) return this._mlog.warn("refresh: not initialized");
this._mlog.debug("Refreshing files...");
async.waterfall([
(_next) => {
this.gitUtil.pullPush("Scripted user file commit", _next);
},
(results, _next) => {
this.workingUtil.listAll(_next);
}
], (err, fileData) => {
if (err) return this._logError("refresh", err);
this._log.debug("Files successfully refreshed");
this._sendMessage("filelist", {
success: true,
files: fileData,
refresh: true
});
});
break;
}
case "commit": {
if (!this._isInitialized()) return this._fail("committed", "warn", "Not initialized");
// NOTE: In a readonly repository (buckets), this is a no-op.
const comment = content.comment;
if (!comment) return this._fail("committed", "warn", "Empty comment:", comment);
this._mlog.debug("Committing files...");
async.waterfall([
(_next) => {
this.gitUtil.pullPush(comment, _next);
}
], (err) => {
if (err) return this._fail("committed", "warn", err);
this._log.debug("Files successfully committed (except for readonly)");
return this._sendMessage("committed", { success: true });
});
break;
}
case "save": {
if (!this.ready) return this._fail("save", "warn", "Not ready");
const filename = content.filename;
const value = content.content;
this._mlog.debug("Saving file:", filename);
if (!filename) return this._fail("saved", "warn", "Empty file name:", filename, value);
async.waterfall([
(_next) => {
this.workingUtil.saveFile(filename, value, _next);
}
], (err, md5sum) => {
if (err) {
if (/ENOSPC/.test(err.message)) return this._fail("saved", "warn", `Whoops, you reached your space limit (${config.docker.diskQuotaKiB} KiB).\nYou should free up space to ensure that changes you make get committed.\nRunning the command "system('rm octave-workspace')" might help.`);
else return this._fail("saved", "error", err);
}
this._log.debug("File successfully saved");
return this._sendMessage("saved", {
success: true,
filename,
md5sum
});
});
break;
}
case "rename": {
if (!this.ready) return this._fail("rename", "warn", "Not ready");
const oldname = content.filename;
const newname = content.newname;
if (!oldname || !newname) return this._fail("renamed", "warn", "Empty file name or new name:", oldname, newname);
this._mlog.debug("Renaming file:", oldname, newname);
async.waterfall([
(_next) => {
this.workingUtil.renameFile(oldname, newname, _next);
}
], (err) => {
if (err) return this._fail("renamed", "error", err);
this._log.debug("File successfully renamed");
return this._sendMessage("renamed", { oldname, newname, success: true });
});
break;
}
case "delete": {
if (!this.ready) return this._fail("delete", "warn", "Not ready");
const filename = content.filename;
if (!filename) return this._fail("deleted", "warn", "Empty file name:", filename);
this._mlog.debug("Deleting file:", filename);
async.waterfall([
(_next) => {
this.workingUtil.deleteFile(filename, _next);
}
], (err) => {
if (err) {
if (/ENOENT/.test(err.message)) return this._fail("deleted", "warn", `Whoops, the file ${filename} does not exist any more.\nTry pressing the "refresh files" button in the file manager toolbar.`);
else return this._fail("deleted", "error", err);
}
this._log.debug("File successfully deleted");
return this._sendMessage("deleted", {
success: true,
filename
});
});
break;
}
case "binary": {
if (!this.ready) return this._mlog.warn("binary: not ready");
const filename = content.filename;
if (!filename) return this._fail("binary", "warn", "Empty file name:", filename);
this._mlog.debug("Loading binary file:", filename);
async.waterfall([
(_next) => {
this.workingUtil.readBinary(filename, _next);
}
], (err, base64data, mime) => {
if (err) return this._fail("binary", "error", err);
this._log.debug("File successfully loaded");
return this._sendMessage("binary", {
success: true,
filename,
base64data,
mime
});
});
break;
}
case "read-delete-binary": {
if (!this.ready) return this._mlog.warn("read-delete-binary: not ready");
const filename = content.filename;
if (!filename) return this._fail("deleted-binary", "warn", "Empty file name:", filename);
this._mlog.debug("Loading and deleting binary file:", filename);
async.series([
(_next) => {
this.workingUtil.readBinary(filename, _next);
}, (_next) => {
this.workingUtil.deleteFile(filename, _next);
}
], (err, results) => {
if (err) return this._fail("deleted-binary", "error", err);
const base64data = results[0][0];
const mime = results[0][1];
this._log.debug("File successfully loaded and deleted");
return this._sendMessage("deleted-binary", {
success: true,
filename,
base64data,
mime
});
});
break;
}
case "multi-binary": {
if (!this.ready) return this._mlog.warn("multi-binary: not ready");
const filenames = content.filenames;
const responseName = "multi-binary:" + content.id;
if (!Array.isArray(filenames)) return this._fail(responseName, "warn", "Invalid filename array:", filenames);
this._mlog.debug("Loading multiple files", responseName, filenames);
async.map(filenames, (filename, _next) => {
async.waterfall([
(__next) => {
this.workingUtil.readBinary(filename, __next);
},
(base64data, mime, __next) => {
__next(null, base64data);
}
], _next);
}, (err, results) => {
if (err) return this._fail(responseName, "error", err);
this._mlog.trace("Files finished loading", responseName);
return this._sendMessage(responseName, {
success: true,
results
});
});
break;
}
case "save-multi-binary": {
if (!this.ready) return this._mlog.warn("save-multi-binary: not ready");
const filenames = content.filenames;
const base64datas = content.base64datas;
const responseName = "multi-binary-saved:" + content.id;
if (!Array.isArray(filenames) || !Array.isArray(base64datas) || filenames.length !== base64datas.length) return this._fail(responseName, "warn", "Invalid array:", filenames, base64datas);
this._mlog.debug("Writing multiple files:", responseName, filenames);
async.times(filenames.length, (i, _next) => {
const buffer = new Buffer(base64datas[i], "base64");
this.workingUtil.saveFile(filenames[i], buffer, _next);
}, (err, results) => {
if (err) return this._fail(responseName, "error", err);
this._mlog.trace("Files finished writing", responseName);
return this._sendMessage(responseName, {
success: true,
results
});
});
break;
}
// Send remaining messages to the fakeSocket
default: {
this.fakeSocket.trigger(name, content);
break;
}
}
}
destroy() {
this.destroyed = true;
}
_logError(context, err) {
if (this.destroyed) {
this._mlog.trace("Ignoring git error:", context, err);
return false;
} else {
this._log.error(context, err);
return true;
}
}
// Send messages downstream
_sendMessage(name, content) {
this.emit("message", name, content);
}
// Log and send failure messages
_fail() {
let args = Array.prototype.slice.call(arguments, 2);
let messageString = args.join(" ");
this._log[arguments[1]].apply(this, args);
this._sendMessage(arguments[0], { success: false, message: messageString });
}
// Set up SIOFU
_setupUploader() {
const uploader = new SocketIOFileUploadServer();
uploader.dir = this.workDir;
uploader.emitChunkFail = true;
uploader.on("saved", (event) => {
const filename = path.basename(event.file.pathName);
this.workingUtil.getFileInfo(filename, (err, fileInfo) => {
if (err) return this._log.warn(err);
if (!fileInfo) return this._fail("saved", "warn", "Your file uploaded, but it will not appear in the list due to an illegal file name.");
this._log.debug("File successfully uploaded");
return this._sendMessage("fileadd", fileInfo);
});
});
uploader.on("error", (event) => {
if (/ENOSPC/.test(event.error.message)) return this._fail("saved", "debug", `Uploading ${event.file.name}:\nIf your file is large and causes you to exceed your space limit\n(${config.docker.diskQuotaKiB} KiB), the file may be incomplete.`);
this._log.error("siofu:", event);
});
uploader.listen(this.fakeSocket);
}
}
module.exports = FilesController;
================================================
FILE: back-filesystem/src/fake-socket.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const EventEmitter = require("events");
// Object to replicate the API of a server-side Socket.IO socket instance.
//
// To trigger all local listeners with an emulated socket message, call
// myFakeSocket.trigger(name,data)
//
// To listen for when local methods want to send a message, listen for
// the "_emit" event on your FakeSocket instance.
class FakeSocket extends EventEmitter {
constructor() {
super();
}
}
// Change around some of the methods
const oldEmit = FakeSocket.prototype.emit;
FakeSocket.prototype.trigger = oldEmit;
FakeSocket.prototype.emit = function(){
const args = Array.prototype.slice.call(arguments);
args.unshift("_emit");
oldEmit.apply(this, args);
};
module.exports = FakeSocket;
================================================
FILE: back-filesystem/src/git-util.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const async = require("async");
const child_process = require("child_process");
const logger = require("@oo/shared").logger;
const config = require("@oo/shared").config;
const silent = require("@oo/shared").silent;
class GitUtil {
constructor(gitDir, logMemo) {
this._log = logger(`git-util:${logMemo}`);
this._mlog = logger(`git-util:${logMemo}:minor`);
this.execOptions = { cwd: gitDir };
this.readonly = false;
this._initialized = false;
// TODO: Prevent multiple git operations from taking place simultaneously.
}
initialize(user, workDir, next) {
if (this._initialized) {
this._log.error("Initializing a repository for a user that was already initialized");
return;
}
const remote = this._userToRemote(user);
async.series([
(_next) => {
this._createUserOnRemote(user, _next);
},
(_next) => {
this._initialize(remote, workDir, _next);
}
], next);
}
initializeBucket(bucketId, workDir, readonly, next) {
if (this._initialized) {
this._log.error("Initializing a repository for a bucket that was already initialized");
return;
}
this.readonly = readonly;
const remote = this._bucketToRemote(bucketId);
async.series([
(_next) => {
if (!readonly) {
this._createBucketOnRemote(bucketId, _next);
} else {
_next(null);
}
},
(_next) => {
this._initialize(remote, workDir, _next);
}
], next);
}
_initialize(remote, workDir, next) {
async.series([
(_next) => {
this._mlog.trace("Running git init...");
child_process.execFile("git", ["--git-dir=.", `--work-tree=${workDir}`, "init"], this.execOptions, _next);
},
(_next) => {
// May 2018: Do not log email-based Git URL
const idx = remote.indexOf("_");
const safeOrigin = (idx === -1) ? remote : remote.substr(0, idx) + "_…";
this._mlog.info("Setting origin:", safeOrigin);
child_process.execFile("git", ["remote", "add", "origin", remote], this.execOptions, _next);
},
(_next) => {
this._pull(_next);
},
(_next) => {
this._initialized = true;
_next(null);
}
], next);
}
pullPush(message, next) {
if (!this._initialized) {
// Trying to sync the repo before it has been initialized; do not attempt to push, because no local changes are possible.
return next(null);
}
if (this.readonly) {
return this._pull(next);
} else {
return this._pullPush(message, next);
}
}
_pullPush(message, next) {
async.series([
(_next) => {
this._mlog.debug("Preparing to pull-push...");
_next();
},
(_next) => {
this._commit(message, _next);
},
(_next) => {
// Perform a shallow clone to avoid wasting time and resources downloading old refs from the server
// This command can fail silently for the case when the remote repo is empty
child_process.execFile("git", ["fetch", "--depth=1"], this.execOptions, silent(/no matching remote head/, _next));
},
(_next) => {
// Resolve merge conflicts by committing all the conflicts into the repository, and let the user manually fix the conflict next time the log in.
// This command can fail silently for the case when origin/master does not exist
const mergeArgs = config.git.supportsAllowUnrelatedHistories ? ["merge", "--no-commit", "--allow-unrelated-histories", "origin/master"] : ["merge", "--no-commit", "origin/master"];
child_process.execFile("git", this._gitConfigArgs().concat(mergeArgs), this.execOptions, silent(/fix conflicts|not something we can merge/, _next).stdout);
},
(_next) => {
this._commit("Scripted merge", _next);
},
(_next) => {
// Push the changes up
// This command can fail silently for the case when the local branch "master" is empty
child_process.execFile("git", ["push", "origin", "master"], this.execOptions, silent(/src refspec master does not match any/, _next));
},
(_next) => {
this._mlog.debug("Finished pull-push");
_next(null);
}
], next);
}
_pull(next) {
async.series([
(_next) => {
this._mlog.debug("Preparing to pull...");
_next();
},
(_next) => {
// Perform a shallow clone to avoid wasting time and resources downloading old refs from the server
// This command can fail silently for the case when the remote repo is empty
child_process.execFile("git", ["fetch", "--depth=1"], this.execOptions, silent(/no matching remote head/, _next));
},
(_next) => {
child_process.execFile("git", this._gitConfigArgs().concat(["merge", "origin/master"]), this.execOptions, silent(/not something we can merge/, _next));
},
(_next) => {
this._mlog.debug("Finished pull");
_next();
}
], next);
}
_commit(message, next) {
async.series([
(_next) => {
child_process.execFile("git", ["add", "--all"], this.execOptions, _next);
},
// Remove the following check since the new "capped file system" should take care of this for us
// (_next) => {
// // Do not commit files greater than 1MB in size
// child_process.exec("find . -size +1M -type f -exec git reset {} \\;", this.execOptions, _next);
// },
(_next) => {
// This command can safely fail silently for the case when there are no files to commit (in that case, the error is empty)
// Note that specifying --author here does not seem to work; I have to do -c ... instead
child_process.execFile("git", this._gitConfigArgs().concat(["commit", "-m", message]), this.execOptions, silent(/nothing to commit/, _next).stdout);
}
], next);
}
_createUserOnRemote(user, next) {
async.series([
(_next) => {
this._mlog.debug("Preparing remote repo...");
_next();
},
(_next) => {
fetch(`http://${config.git.hostname}:${config.git.createRepoPort}/?` + new URLSearchParams({
type: "repos",
name: user.parametrized
})).then((response) => {
if (!response.ok) {
return _next(new Error("Not 2xx response", { cause: response }));
}
_next();
}).catch(_next);
}
], next);
}
_createBucketOnRemote(bucketId, next) {
async.series([
(_next) => {
this._mlog.debug("Preparing remote bucket...");
_next();
},
(_next) => {
fetch(`http://${config.git.hostname}:${config.git.createRepoPort}/?` + new URLSearchParams({
type: "buckets",
name: bucketId
})).then((response) => {
if (!response.ok) {
return _next(new Error("Not 2xx response", { cause: response }));
}
_next();
}).catch(_next);
}
], next);
}
_userToRemote(user) {
return `git://${config.git.hostname}:${config.git.gitDaemonPort}/repos/${user.parametrized}.git`;
}
_bucketToRemote(bucketId) {
return `git://${config.git.hostname}:${config.git.gitDaemonPort}/buckets/${bucketId}.git`;
}
_gitConfigArgs() {
return ["-c", `user.name="${config.git.author.name}"`, "-c", `user.email="${config.git.author.email}"`];
}
}
module.exports = GitUtil;
================================================
FILE: back-filesystem/src/logger.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const logger = require("@oo/shared").logger;
// Enable all log levels by default
logger.debug.enable("*");
// Customize formatArgs
// Based on https://github.com/visionmedia/debug/blob/master/node.js
logger.debug.formatArgs = function formatArgs() {
var args = arguments;
var useColors = this.useColors;
var name = this.namespace;
if (useColors) {
var c = this.color;
args[0] = " \u001b[3" + c + ";1m" + name + " " + "\u001b[0m" + args[0] + "\u001b[3" + c + "m" + " +" + logger.debug.humanize(this.diff) + "\u001b[0m";
} else {
args[0] = name + " " + args[0];
}
return args;
};
================================================
FILE: back-filesystem/src/mime.types
================================================
# Copyright © 2018, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server. If not, see
# .
# Additional MIME Types used by the Octave Online application
# GNU Octave Types
# If these haven't ben defined before, then they are now!
text/x-octave m
application/x-octave-data mat
text/plain octaverc
================================================
FILE: back-filesystem/src/working-util.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const async = require("async");
const fs = require("fs");
const path = require("path");
const mime = require("mime");
const charsetDetector = require("charset-detector");
const Iconv = require("iconv").Iconv;
const logger = require("@oo/shared").logger;
const config = require("@oo/shared").config;
const crypto = require("crypto");
// Load extra MIME types
mime.load(path.join(__dirname, "mime.types"));
const ACCEPTABLE_MIME_REGEX = /^(text\/.*)$/;
const UNACCEPTABLE_FILENAME_REGEX = /^(\..*|octave-\w+)$/;
class WorkingUtil {
constructor(workDir, logMemo) {
this._log = logger(`working-util:${logMemo}`);
this._mlog = logger(`working-util:${logMemo}:minor`);
this.cwd = workDir;
}
listAll(next) {
async.waterfall([
(_next) => {
this._recursiveReaddir(this.cwd, 0, _next);
},
(fileInfos, _next) => {
const dict = {};
fileInfos.forEach((fileInfo) => {
if (!fileInfo) return;
let filename = fileInfo.filename;
delete fileInfo.filename;
dict[filename] = fileInfo;
});
_next(null, dict);
}
], next);
}
hasOctaverc(next) {
fs.access(path.join(this.cwd, ".octaverc"), (err) => {
if (err) {
this._mlog.trace(".octaverc does not exist");
return next(null, false);
} else {
this._mlog.trace(".octaverc exists");
return next(null, true);
}
});
}
_recursiveReaddir(directory, depth, next) {
// Don't recurse more than 3 levels deep
if (depth > 3) {
return next(null, []);
}
async.waterfall([
(_next) => {
this._mlog.trace("Entering directory", directory);
fs.readdir(directory, _next);
},
(files, _next) => {
async.map(files, (filename, __next) => {
let pathname = path.join(directory, filename);
let relname = path.relative(this.cwd, pathname);
// TODO: Can the following be removed?
if (pathname === path.join(this.cwd, ".git")) {
this._mlog.debug("Skipping .git in _recursiveReaddir");
return;
}
async.waterfall([
(___next) => {
// lstat to prevent following symlinks
fs.lstat(pathname, ___next);
},
(stats, ___next) => {
this._mlog.trace("Got lstats", relname, stats.isDirectory(), stats.isFile());
if (stats.isDirectory()) {
return this._recursiveReaddir(pathname, depth+1, ___next);
} else if (stats.isFile()) {
return this._getFileInfo(filename, pathname, relname, stats, ___next);
} else {
return ___next(null, []);
}
}
], __next);
}, (err, results) => {
if (err) return _next(err);
this._mlog.trace("Leaving directory", directory);
_next(null, Array.prototype.concat.apply([], results));
});
}
], next);
}
// Endpoint for standalone getFileInfo (used by SIOFU)
getFileInfo(filename, next) {
let pathname = this._safePath(filename);
let relname = path.relative(this.cwd, pathname);
async.waterfall([
(_next) => {
fs.lstat(pathname, _next);
},
(stats, _next) => {
this._getFileInfo(filename, pathname, relname, stats, _next);
},
(arr, _next) => {
_next(null, arr[0]);
}
], next);
}
_getFileInfo(filename, pathname, relname, stats, next) {
this._mlog.trace("Getting file info for", relname);
let _mime = mime.lookup(filename);
if (ACCEPTABLE_MIME_REGEX.test(_mime)) {
if (stats.size > config.session.textFileSizeLimit) {
// This file is too big. Do not perform any further processing on this file.
// FIXME: Show a nice message to the end user to let them know why their file isn't being loaded
this._log.debug("Skipping text file that is too big:", stats.size, filename);
next(null, [{
filename: relname,
isText: false
}]);
} else {
fs.readFile(pathname, (err, buf) => {
if (err) return next(err);
buf = this._convertCharset(buf);
next(null, [{
filename: relname,
isText: true,
content: buf.toString("base64")
}]);
});
}
} else if (!UNACCEPTABLE_FILENAME_REGEX.test(filename)) {
next(null, [{
filename: relname,
isText: false
}]);
} else {
next(null, []);
}
}
_convertCharset(buf) {
var encoding;
// Detect and attempt to convert charset
if (buf.length > 0) {
try {
let charsetResults = charsetDetector(buf);
this._log.debug("Top charset match:", charsetResults?.[0]);
encoding = charsetResults?.[0]?.charsetName || "UTF-8";
if (encoding !== "UTF-8"){
this._log.trace("Converting charset:", encoding);
buf = new Iconv(encoding, "UTF-8").convert(buf);
}
} catch(err) {
this._log.warn("Could not convert encoding:", encoding);
}
}
// Convert line endings
// TODO: Is there a better way than converting to a string here?
buf = new Buffer(buf.toString("utf8").replace(/\r\n/g, "\n"));
return buf;
}
saveFile(filename, value, next) {
// Create backup of file in memory in case there are any I/O errors
async.waterfall([
(_next) => {
let dirname = path.dirname(this._safePath(filename));
// Callback to a function to remove/normalize extra arguments
fs.mkdir(dirname, { recursive: true }, (e) => _next(e));
},
(_next) => {
fs.readFile(
this._safePath(filename),
(err, buf) => {
if (!err) return _next(null, buf);
if (/ENOENT/.test(err.message)) {
this._log.info("Creating new file:", filename);
return _next(null, new Buffer(0));
}
return _next(err);
}
);
},
(buf, _next) => {
fs.writeFile(
this._safePath(filename),
value,
(err) => {
_next(null, buf, err);
});
},
(buf, err, _next) => {
if (err) {
fs.writeFile(
this._safePath(filename),
buf,
() => {
_next(err);
});
} else {
async.nextTick(() => {
_next(null);
});
}
},
(_next) => {
return _next(null, crypto.createHash("md5").update(value, "utf-8").digest("hex"));
}
], next);
}
renameFile(oldname, newname, next) {
fs.rename(
this._safePath(oldname),
this._safePath(newname),
next);
}
deleteFile(filename, next) {
fs.unlink(
this._safePath(filename),
next);
}
readBinary(filename, next) {
async.waterfall([
(_next) => {
fs.readFile(this._safePath(filename), _next);
},
(buf, _next) => {
const base64data = buf.toString("base64");
const _mime = mime.lookup(filename);
_next(null, base64data, _mime);
}
], next);
}
_safePath(filename) {
// Filenames must descend from the working directory. Forbids filenames starting with '..' or similar.
let candidate = path.join(this.cwd, filename);
if (candidate.substring(0, this.cwd.length) !== this.cwd) {
this._log.warn("Processed a fishy filename:", filename);
return path.join(this.cwd, "octave-workspace"); // an arbitrary legal path
}
return candidate;
}
}
module.exports = WorkingUtil;
================================================
FILE: back-master/.eslintrc.yml
================================================
================================================
FILE: back-master/.npmrc
================================================
# Please keep this in sync with all other .npmrc files
# SEE: https://github.com/npm/feedback/discussions/864
install-links=false
================================================
FILE: back-master/README.md
================================================
Octave Online Server: Back Server
=================================
This directory contains the source code for the Octave Online Server back server. This is the "master" process that communicates with the downstream user via Redis and with the GNU Octave subprocess. Commands dealing with the filesystem are in the *back-filesystem* directory parallel to this directory.
## Setup
There are three modes for the back server.
1. SELinux: Fast, and able to handle many concurrent sessions.
2. Unsafe: Fast and easy, but not recommended with untrusted users. Every Octave process is run without any sandboxing or resource limitations.
Previously, a third mode, "docker", worked by creating a new Docker container for each session. This is no longer supported. Instead, if running with trusted users, you can use a single Docker container and Unsafe mode.
### Option 1: SELinux
Ensure that you are running on CentOS or another distribution of Linux that supports SELinux. SELinux should come pre-installed on CentOS.
Make and build Octave from source. Follow a procedure similar to the one put forth in *dockerfiles/build-octave.dockerfile*.
Run `sudo yum install -y selinux-policy-devel policycoreutils-sandbox selinux-policy-sandbox libcgroup-tools`
Ensure that Node.js is installed and the dependencies are downloaded for the shared project:
$ (cd shared && npm install)
Run all of the following make commands from the projects directory.
- `sudo make install-cgroup`
- `sudo make install-selinux-policy`
- `sudo make install-selinux-bin`
- `sudo make install-site-m`
### Option 2: Unsafe
Follow the Option 2 instructions to build and install Octave from source. Stop before installing selinux-policy-devel and other selinux packages.
## Running the Back Server
### Debugging
Go to the *back-master* directory and run `DEBUG=* node app.js` to start the back server. The `DEBUG=*` enables debug logging.
### Production
`node app.js` can be run directly, but consider using `oo.service` in the *entrypoint* directory parallel to this directory.
## Stopping the Back Server
By default, after the back server receives a successful maintenance request, it will wait for all sessions to close, and then cleanup and exit with code 0.
If you wish to cause the back server process to gracefully release all sessions without exiting, you can send the signal SIGUSR1 to the process.
## To-do list
- Update /usr/bin/sandbox according to https://github.com/SELinuxProject/selinux/commit/0f4620d6111838ce78bf5a591bb80c99c9d88730
- If using RHEL, the line "Defaults requiretty" must be commented out.
================================================
FILE: back-master/app.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const log = require("@oo/shared").logger("app");
const mlog = require("@oo/shared").logger("app:minor");
const hostname = require("@oo/shared").hostname();
const MessageTranslator = require("./src/message-translator");
const RedisMessenger = require("@oo/shared").RedisMessenger;
const SessionManager = require("./src/session-manager");
const config = require("@oo/shared").config;
const gcStats = (require("@sematext/gc-stats"))();
const fs = require("fs");
const path = require("path");
const async = require("async");
const http = require("http");
process.stdout.write("Process ID: " + process.pid + "\n");
process.stderr.write("Process ID: " + process.pid + "\n");
log.info("Process ID:", process.pid);
log.info("Hostname:", hostname);
log.log(process.env);
var sessionManager, mainImpl, personality;
if (fs.existsSync(config.rackspace.personality_filename)) {
personality = JSON.parse(fs.readFileSync(config.rackspace.personality_filename, "utf8"));
log.info("Personality:", personality.flavor, personality);
sessionManager = new SessionManager(true);
mainImpl = require("./src/main-flavor");
} else if (process.env["OO_FLAVOR_OVERRIDE"]) {
personality = { flavor: process.env["OO_FLAVOR_OVERRIDE"] };
log.info("Flavor override:", personality.flavor);
sessionManager = new SessionManager(true);
mainImpl = require("./src/main-flavor");
} else {
log.info("No personality file found");
personality = null;
sessionManager = new SessionManager(false);
mainImpl = require("./src/main-pool");
}
let sessionLogDirCount = 0;
function makeSessionLogDir(tokens) {
if (tokens.length === config.worker.sessionLogs.depth) {
const dirname = path.join(config.worker.logDir, config.worker.sessionLogs.subdir, ...tokens);
if (sessionLogDirCount % 1000 === 0) {
mlog.trace(dirname);
}
sessionLogDirCount++;
fs.mkdirSync(dirname, { recursive: true });
} else {
for (let a of "0123456789abcdef") {
makeSessionLogDir(tokens.concat([a]));
}
}
}
log.info("Creating session log dirs…");
makeSessionLogDir([]);
log.info(sessionLogDirCount, "dirs touched");
const redisInputHandler = new RedisMessenger().subscribeToInput();
const redisDestroyDHandler = new RedisMessenger().subscribeToDestroyD();
const redisExpireHandler = new RedisMessenger().subscribeToExpired();
const redisScriptHandler = new RedisMessenger().enableSessCodeScriptsSync();
const redisMessenger = new RedisMessenger();
const translator = new MessageTranslator();
redisInputHandler.on("message", translator.fromDownstream.bind(translator));
sessionManager.on("message", translator.fromUpstream.bind(translator));
translator.on("for-upstream", (sessCode, name, getData) => {
const session = sessionManager.get(sessCode);
// Stop processing this message if it doesn't have to do with a session running on this node.
if (!session) return;
// Now we can safely continue. The following method will download the data from Redis.
session.enqueueMessage(name, getData);
});
translator.on("for-downstream", (sessCode, name, content) => {
log.trace("Sending Downstream:", sessCode, name);
redisMessenger.output(sessCode, name, content);
});
translator.on("destroy", (sessCode, reason) => {
log.debug("Received Destroy:", sessCode);
sessionManager.destroy(sessCode, reason);
});
translator.on("ping", (code) => {
// Not currently used
log.debug("Received Ping:", code);
redisMessenger.output(code, "pong", { hostname });
});
redisDestroyDHandler.on("destroy-d", (sessCode, reason) => {
if (!sessionManager.get(sessCode)) return;
log.info("Received Destroy-D:", sessCode, reason);
sessionManager.destroy(sessCode, reason);
});
redisExpireHandler.on("expired", (sessCode, channel) => {
if (!sessionManager.get(sessCode)) return;
log.info("Received Expire:", sessCode, channel);
sessionManager.destroy(sessCode, "Octave Session Expired (downstream)");
});
sessionManager.on("touch", (sessCode, start) => {
redisMessenger.touchOutput(sessCode);
if (personality) {
redisMessenger.output(sessCode, "oo.touch-flavor", {
start,
current: new Date().valueOf(),
flavor: personality.flavor
});
}
});
sessionManager.on("live", (sessCode) => {
redisMessenger.setLive(sessCode);
});
sessionManager.on("destroy-u", (sessCode, reason) => {
log.info("Sending Destroy-U:", reason, sessCode);
redisMessenger.destroyU(sessCode, reason);
});
gcStats.on("stats", (stats) => {
mlog.trace(`Garbage Collected (type ${stats.gctype}, ${stats.pause/1e6} ms)`);
});
const healthServer = http.createServer((req, res) => {
if (sessionManager.isHealthy()) {
res.writeHead(200);
} else {
res.writeHead(503);
}
res.end();
}).listen(config.gcp.health_check_port);
mainImpl.start({
sessionManager,
redisScriptHandler,
redisMessenger,
personality
}, (err) => {
log.error("Main-impl ended", err);
doExit();
});
function doExit() {
sessionManager.terminate("Server Maintenance");
mainImpl.doExit();
setTimeout(() => {
redisInputHandler.close();
redisDestroyDHandler.close();
redisExpireHandler.close();
redisScriptHandler.close();
redisMessenger.close();
healthServer.close();
}, 5000);
}
function doGracefulExit() {
log.info("RECEIVED SIGUSR1. Will not accept any further sessions.");
mainImpl.doExit();
sessionManager.disablePool();
async.series([
(_next) => {
async.whilst(
() => { return sessionManager.numActiveSessions() > 0; },
(next) => { setTimeout(next, config.maintenance.pauseDuration); },
_next
);
},
(_next) => {
log.info("All user sessions are closed. Send SIGINT to fully terminate.");
_next(null);
}
], (err) => {
if (err) log.error("Error during graceful exit:", err);
});
}
function doFastExit() {
log.info("RECEIVED SIGNAL. Starting exit procedure.");
doExit();
}
process.on("SIGINT", doFastExit);
process.on("SIGHUP", doFastExit);
process.on("SIGTERM", doFastExit);
process.on("SIGUSR1", doGracefulExit);
//const heapdump = require("heapdump");
//setInterval(() => { heapdump.writeSnapshot("/srv/oo/logs/heap/" + hostname + "." + process.pid + "." + Date.now() + ".heapsnapshot"); }, 30000);
================================================
FILE: back-master/package.json
================================================
{
"name": "@oo/back",
"version": "0.0.0",
"description": "Spawns Octave sessions and passes messages",
"main": "app.js",
"scripts": {},
"author": "Octave Online LLC",
"license": "AGPL-3.0",
"private": true,
"engines": {
"node": "18.x"
},
"dependencies": {
"@oo/shared": "file:../shared",
"@sematext/gc-stats": "^1.5.8",
"async": "^1.5.2",
"base-x": "^3.0.8",
"ps-tree": "^1.2.0",
"temp": "^0.8.4",
"tmp": "0.0.28",
"uuid": "^2.0.1"
}
}
================================================
FILE: back-master/src/capped-file-system.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const async = require("async");
const temp = require("temp");
const child_process = require("child_process");
const fs = require("fs");
const path = require("path");
const logger = require("@oo/shared").logger;
const OnlineOffline = require("@oo/shared").OnlineOffline;
const config = require("@oo/shared").config;
// This file is based on http://souptonuts.sourceforge.net/quota_tutorial.html
const IMG_FILE_NAME = "img.ext3";
const IMG_MNT_DIR = "mnt";
const IMG_DATA_DIR = "data";
class CappedFileSystem extends OnlineOffline {
constructor(sessCode, size) {
super();
this.sessCode = sessCode;
this._log = logger("capped-file-system:" + sessCode);
this._mlog = logger("capped-file-system:" + sessCode + ":minor");
this._size = size;
}
_doCreate(next) {
this._cleanups = [];
async.series([
(_next) => {
this._mlog.trace("Making temp dir...");
temp.mkdir("oo-", (err, tmpdir) => {
if (tmpdir) this._tmpdir = tmpdir;
if (!err) this._cleanups.unshift((__next) => {
this._mlog.trace("Removing temp dir...");
fs.rmdir(tmpdir, __next);
});
_next(err);
});
},
(_next) => {
this._mlog.debug("Created temp dir:", this._tmpdir);
this._mlog.trace("Allocating space for filesystem...");
const imgFileName = path.join(this._tmpdir, IMG_FILE_NAME);
// eslint-disable-next-line no-unused-vars
child_process.execFile("dd", ["if=/dev/zero", `of=${imgFileName}`, "bs=1k", `count=${this._size}`], (err, stdout, stderr) => {
if (!err) this._cleanups.unshift((__next) => {
this._mlog.trace("Removing file system...");
fs.unlink(imgFileName, __next);
});
_next(err);
});
},
(_next) => {
this._mlog.trace("Formatting file system...");
const imgFileName = path.join(this._tmpdir, IMG_FILE_NAME);
child_process.execFile("mkfs", ["-t", "ext3", "-q", imgFileName, "-F"], (err, stdout, stderr) => {
if (stderr) err = new Error(stderr);
_next(err);
});
},
(_next) => {
this._mlog.trace("Creating mount directory...");
const imgMntDir = path.join(this._tmpdir, IMG_MNT_DIR);
fs.mkdir(imgMntDir, 0o700, (err) => {
if (!err) this._cleanups.unshift((__next) => {
this._mlog.trace("Removing mount directory...");
fs.rmdir(imgMntDir, __next);
});
_next(err);
});
},
(_next) => {
this._mlog.trace("Mounting file system...");
const imgFileName = path.join(this._tmpdir, IMG_FILE_NAME);
const imgMntDir = path.join(this._tmpdir, IMG_MNT_DIR);
child_process.execFile("sudo", ["mount", "-o", "loop,rw", imgFileName, imgMntDir], (err, stdout, stderr) => {
if (stderr) err = new Error(stderr);
if (!err) this._cleanups.unshift((__next) => {
this._mlog.trace("Unmounting file system...");
child_process.execFile("sudo", ["umount", imgMntDir], __next);
});
_next(err);
});
},
(_next) => {
this._mlog.trace("Claiming ownership of file system root...");
const imgMntDir = path.join(this._tmpdir, IMG_MNT_DIR);
child_process.execFile("sudo", ["chown", config.worker.uid+":"+config.worker.uid, imgMntDir], (err, stdout, stderr) => {
if (stderr) err = new Error(stderr);
_next(err);
});
},
(_next) => {
this._mlog.trace("Creating data directory...");
const imgDataDir = path.join(this._tmpdir, IMG_MNT_DIR, IMG_DATA_DIR);
fs.mkdir(imgDataDir, 0o700, (err) => {
// Cleanup function not necessary here because the directory resides in the guest filesystem
_next(err);
});
}
], (err) => {
const imgDataDir = path.join(this._tmpdir, IMG_MNT_DIR, IMG_DATA_DIR);
this.dir = imgDataDir;
return next(err, imgDataDir);
});
}
_doDestroy(next) {
async.series(this._cleanups, (err) => {
if (err) return next(err);
this._enabled = false;
this._cleanups = null;
this._tmpdir = null;
this.dir = null;
return next(null);
});
}
}
/// An alternative to CappedFileSystem when sudo is unavailable.
/// This class does *not* limit file sizes.
class TmpWorkDirectory extends OnlineOffline {
constructor(sessCode) {
super();
this.sessCode = sessCode;
this._mlog = logger("tmp-work-directory:" + sessCode + ":minor");
}
_doCreate(next) {
this._cleanups = [];
async.series([
(_next) => {
this._mlog.trace("Making directory...");
temp.mkdir("oo-", (err, tmpdir) => {
if (tmpdir) this.dir = tmpdir;
if (!err) this._cleanups.unshift((__next) => {
this._mlog.trace("Removing directory...");
child_process.execFile("rm", ["-rf", tmpdir], __next);
});
this._mlog.debug("Created directory:", this.dir);
_next(err);
});
},
], (err) => {
return next(err, this.dir);
});
}
_doDestroy(next) {
async.series(this._cleanups, (err) => {
if (err) return next(err);
this._enabled = false;
this._cleanups = null;
this.dir = null;
return next(null);
});
}
}
module.exports = {
CappedFileSystem,
TmpWorkDirectory
};
================================================
FILE: back-master/src/docker-handler.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const async = require("async");
const child_process = require("child_process");
const logger = require("@oo/shared").logger;
const StdioMessenger = require("@oo/shared").StdioMessenger;
class DockerHandler extends StdioMessenger {
constructor(sessCode, dockerImage) {
super();
this._log = logger(`docker-handler:${dockerImage}:${sessCode}`);
this.sessCode = sessCode;
}
_doCreate(next, dockerArgs) {
async.series([
(_next) => {
// Create the session
this._spwn = child_process.spawn("docker", dockerArgs);
this._log.trace("Docker args:", dockerArgs.join(" "));
this._log.debug("Launched process with ID:", this._spwn.pid);
// Create stderr listener
this._spwn.stderr.on("data", this._handleLog.bind(this));
// Create exit listener
this._spwn.on("exit", this._handleExit.bind(this));
// Listen to main read stream
this.setReadStream(this._spwn.stdout);
// Wait until we get an acknowledgement before continuing. Two conditions: receipt of the acknowledgement message, and premature exit.
var ack = false;
this.once("message", (name /*, content */) => {
if (ack) return;
ack = true;
// Error if the message is docker-exit
if (name === "docker-exit") return _next(new Error("Process exited prematurely"));
// Don't enable the write stream until down here because we don't want to write messages to the child's STDIN until we've acknowledged that it is online
this.setWriteStream(this._spwn.stdin);
_next(null);
});
}
], (err) => {
if (err) return next(err);
this._log.debug("Finished creating");
return next(null);
});
}
_doDestroy(next) {
// Since the child process is actually the docker client and not the daemon, the SIGKILL will never get forwarded to the actual octave host process. We need to delegate the task to docker.
child_process.execFile("docker", ["stop", "-t", 0, this._dockerName], (err, stdout, stderr) => {
// child_process.execFile("docker", ["rm", "-f", this._dockerName], (err, stdout, stderr) => {
if (err) this._log.warn(err, stderr);
this._log.debug("Finished destroying");
return next(null);
});
}
signal(name) {
if (this._state !== "ONLINE") return this._log.warn("Will not send SIGINT to child process: process not online");
// Although the child process is actually the docker client and not the daemon, the client will forward simple signals like SIGINT to the actual octave host process.
this._spwn.kill(name);
this._log.debug("Sent " + name + " to child process");
}
_handleLog(data) {
// Log message to console
data.toString().trim().split("\n").forEach((line) => {
this._log.log(line);
});
// Special handling of certain messages
// TODO: Make this message get sent from host.c instead of from here
if (/Process exited with status 0, signal 9/.test(data)) {
this.emit("message", "octave-killed");
}
}
_handleExit(code, signal) {
this._log.debug("Docker Exit:", code, signal);
this.emit("message", "docker-exit", { code, signal });
}
}
module.exports = DockerHandler;
================================================
FILE: back-master/src/main-flavor.js
================================================
/*
* Copyright © 2019, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
// This file contains the main loop for flavor (dedicated) servers.
const log = require("@oo/shared").logger("main-flavor");
const mlog = require("@oo/shared").logger("main-flavor:minor");
const config = require("@oo/shared").config;
const config2 = require("@oo/shared").config2;
const RedisMessenger = require("@oo/shared").RedisMessenger;
const MaintenanceRequestFlavorManager = require("./maintenance-request-manager");
const runMaintenance = require("./maintenance");
const async = require("async");
const rackOperations = require("@oo/shared/rack/operations");
var redisFlavorStatusHandler,
flavorStatusManager;
var ACCEPT_CONS = true;
var statusTimer;
function start(globals, next) {
async.parallel([
(_next) => {
startConnectionAcceptLoop(globals, _next);
},
(_next) => {
startLifetimeLoop(globals, _next);
}
], next);
}
function startConnectionAcceptLoop(globals, next) {
let { sessionManager, redisScriptHandler, personality } = globals;
async.during(
(_next) => {
if (!ACCEPT_CONS) return _next(null, false);
async.waterfall([
(__next) => {
if (sessionManager.canAcceptNewSessions()) {
redisScriptHandler.getSessCodeFlavor(personality.flavor, (err, sessCode, content) => {
if (err) log.error("Error getting sessCode:", err);
__next(null, sessCode, content);
});
} else {
process.nextTick(() => {
__next(null, null, null);
});
}
},
(sessCode, content, __next) => {
if (sessCode) {
async.waterfall([
(___next) => {
log.info("Received Session:", sessCode);
content.tier = "_maxima";
sessionManager.attach(sessCode, content);
sessionManager.disablePool();
flavorStatusManager.stop();
flavorStatusManager.ignoreAll();
clearTimeout(statusTimer);
sessionManager.once("destroy-done", (_sessCode) => {
___next(null, _sessCode);
});
},
(_sessCode, ___next) => {
if (sessionManager.numActiveSessions() !== 0) {
log.error("Active sessions when session was closed");
}
if (sessCode !== _sessCode) {
log.error("sessCode changed:", sessCode, _sessCode);
}
sessionManager.terminate("Server Maintenance");
setTimeout(___next, config.maintenance.pauseDuration);
},
(___next) => {
runMaintenance(___next);
}
], (err) => {
__next(err, false);
});
} else {
__next(null, true);
}
},
], _next);
},
(_next) => {
let delay = Math.floor(config.worker.clockInterval.min + Math.random()*(config.worker.clockInterval.max-config.worker.clockInterval.min));
setTimeout(_next, delay);
},
(err) => {
mlog.info("Connection-accepting loop ended");
return next(err);
}
);
}
function startLifetimeLoop(globals, next) {
let { sessionManager, redisMessenger, personality } = globals;
const flavorConfig = config2.flavor(personality.flavor);
flavorStatusManager = new MaintenanceRequestFlavorManager(flavorConfig.defaultClusterSize);
redisFlavorStatusHandler = new RedisMessenger().subscribeToFlavorStatus(personality.flavor);
redisFlavorStatusHandler.on("flavor-status", (...args) => {
flavorStatusManager.onMessage(...args);
});
flavorStatusManager.on("request-maintenance", (...args) => {
redisMessenger.requestFlavorStatus(personality.flavor, ...args);
});
flavorStatusManager.on("reply-to-maintenance-request", (...args) => {
redisMessenger.replyToFlavorStatus(personality.flavor, ...args);
});
// In a flavor cluster, when we get approval from peers, we remove ourself from the cluster permanently in order to save on idle time costs. New servers will be added to the cluster when needed (on demand).
async.forever(
(_next) => {
async.series([
(__next) => {
statusTimer = setTimeout(__next, flavorConfig.idleTime);
},
(__next) => {
flavorStatusManager.beginRequesting(flavorConfig.statusInterval);
flavorStatusManager.once("maintenance-accepted", __next);
},
(__next) => {
sessionManager.disablePool();
if (sessionManager.numActiveSessions() !== 0) {
log.warn("Active sessions when flavor maintenance was approved");
return;
}
sessionManager.terminate("Server Maintenance");
statusTimer = setTimeout(__next, config.maintenance.pauseDuration);
},
(__next) => {
// TODO: Move this call somewhere it could be configurable.
rackOperations.deleteSelf(personality, __next);
}
], (err) => {
_next(err);
});
},
(err) => {
log.info("Lifetime loop ended");
return next(err);
}
);
}
function doExit() {
clearTimeout(statusTimer);
flavorStatusManager.stop();
ACCEPT_CONS = false;
setTimeout(() => {
redisFlavorStatusHandler.close();
}, 5000);
}
module.exports = {
start,
doExit
};
================================================
FILE: back-master/src/main-pool.js
================================================
/*
* Copyright © 2019, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
// This file contains the main loop for normal pool servers.
const log = require("@oo/shared").logger("main-pool");
const config = require("@oo/shared").config;
const RedisMessenger = require("@oo/shared").RedisMessenger;
const MaintenanceRequestFlavorManager = require("./maintenance-request-manager");
const runMaintenance = require("./maintenance");
const async = require("async");
const redisMaintenanceHandler = new RedisMessenger().subscribeToRebootRequests();
const maintenanceRequestManager = new MaintenanceRequestFlavorManager();
var ACCEPT_CONS = true;
var maintenanceTimer;
// Main loops
function start(globals, next) {
async.parallel([
(_next) => {
startConnectionAcceptLoop(globals, _next);
},
(_next) => {
startMaintenanceLoop(globals, _next);
}
], next);
}
function startConnectionAcceptLoop(globals, next) {
let { sessionManager, redisScriptHandler } = globals;
async.forever(
(_next) => {
if (!ACCEPT_CONS) return;
async.waterfall([
(__next) => {
let fraction;
if (config.worker.clockStrategy === "random") {
fraction = Math.random();
} else {
fraction = sessionManager.usagePercent();
}
let delay = Math.floor(config.worker.clockInterval.min + fraction * (config.worker.clockInterval.max-config.worker.clockInterval.min));
setTimeout(__next, delay);
},
(__next) => {
if (sessionManager.canAcceptNewSessions()) {
redisScriptHandler.getSessCode((err, sessCode, content) => {
if (err) log.error("Error getting sessCode:", err);
__next(null, sessCode, content);
});
} else {
process.nextTick(() => {
__next(null, null, null);
});
}
},
(sessCode, content, __next) => {
if (sessCode) {
log.info("Received Session:", sessCode);
sessionManager.attach(sessCode, content);
}
__next(null);
}
], _next);
},
(err) => {
log.error("Connection-accepting loop ended");
return next(err);
}
);
}
function startMaintenanceLoop(globals, next) {
let { sessionManager, redisMessenger } = globals;
redisMaintenanceHandler.on("reboot-request", maintenanceRequestManager.onMessage.bind(maintenanceRequestManager));
maintenanceRequestManager.on("request-maintenance", redisMessenger.requestReboot.bind(redisMessenger));
maintenanceRequestManager.on("reply-to-maintenance-request", redisMessenger.replyToRebootRequest.bind(redisMessenger));
async.forever(
(_next) => {
async.series([
(__next) => {
maintenanceTimer = setTimeout(__next, config.maintenance.interval);
},
(__next) => {
maintenanceRequestManager.beginRequesting(config.maintenance.requestInterval);
maintenanceRequestManager.once("maintenance-accepted", __next);
},
(__next) => {
sessionManager.disablePool();
async.whilst(
() => { return sessionManager.numActiveSessions() > 0; },
(__next) => { maintenanceTimer = setTimeout(__next, config.maintenance.pauseDuration); },
__next
);
},
(__next) => {
sessionManager.terminate();
maintenanceTimer = setTimeout(__next, config.maintenance.pauseDuration);
},
(__next) => {
runMaintenance(__next);
},
(__next) => {
sessionManager.restart();
maintenanceTimer = setTimeout(__next, config.maintenance.pauseDuration);
},
(__next) => {
maintenanceRequestManager.reset();
__next();
}
], (err) => {
_next(err);
});
},
(err) => {
log.error("Maintenance loop ended");
return next(err);
}
);
}
function doExit() {
clearTimeout(maintenanceTimer);
maintenanceRequestManager.stop();
ACCEPT_CONS = false;
setTimeout(() => {
redisMaintenanceHandler.close();
}, 5000);
}
module.exports = {
start,
doExit
};
================================================
FILE: back-master/src/maintenance-request-manager.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const uuid = require("uuid");
const EventEmitter = require("events");
const log = require("@oo/shared").logger("maint-req-manager");
const config = require("@oo/shared").config;
class MaintenanceRequestFlavorManager extends EventEmitter {
constructor(clusterSize) {
super();
if (clusterSize) {
this._forFlavor = true;
this._clusterSize = clusterSize;
this._priority = Math.random();
log.debug("Flavor Priority:", this._priority);
}
this.reset();
}
reset() {
this._responses = {};
this._ignoreAll = false;
if (!this._forFlavor) {
this._priority = 0;
}
}
ignoreAll() {
this._ignoreAll = true;
}
beginRequesting(intervalTime) {
log.info("Beginning maintenance requests");
this.reset();
this._requestInterval = setInterval(this._requestMaintenance.bind(this), intervalTime);
}
onMessage(id, isRequest, message) {
// Has the server has removed itself from the actively responding cluster?
if (this._ignoreAll) {
return;
}
let isOwnRequest = Object.keys(this._responses).indexOf(id) !== -1;
if (isRequest && !isOwnRequest) {
// Reply to the maintenance request. Reply "yes" only if the requester's priority is higher than our own priority.
let response = (message.priority > this._priority);
this.emit("reply-to-maintenance-request", id, response);
} else if (!isRequest && isOwnRequest) {
// Someone replied to our own maintenance request.
this._responses[id].push(message.response);
}
}
stop() {
if (this._requestInterval) {
clearInterval(this._requestInterval);
}
this._requestInterval = null;
}
_requestMaintenance() {
let id = uuid.v4();
if (!this._forFlavor) {
// In flavor status mode, keep a fixed priority at all times. This creates stability and uniqueness that is easy to reason about.
// In maintenance request mode, make the priority grow as time goes on. This means older servers get first priority to maintenance.
this._priority += 1;
}
this._responses[id] = [];
this.emit("request-maintenance", id, this._priority);
log.trace("Sent maintenance request:", id, this._priority);
setTimeout(() => {
// Count the number of yeses and nos.
let numYes = this._responses[id].reduce((s,v) => {
return s + (v ? 1 : 0);
}, 0);
let numNo = this._responses[id].length - numYes;
let success;
if (this._forFlavor) {
// Policy: Guarantee at least _clusterSize online nodes
success = numYes >= this._clusterSize;
} else {
// Policy: Guarantee at least minNodesInCluster online nodes and no more than maxNodesInMaintenance maintenance nodes.
success = numNo < config.maintenance.maxNodesInMaintenance && numYes >= config.maintenance.minNodesInCluster;
}
// Were we successful?
if (success) {
log.info("Maintenance request was approved");
this.emit("maintenance-accepted");
this._priority = Number.MAX_VALUE;
clearInterval(this._requestInterval);
}
else {
log.trace("Maintenance request failed; trying again:", id);
}
// Dereference responses array
delete this._responses[id];
}, config.maintenance.responseWaitTime);
}
}
module.exports = MaintenanceRequestFlavorManager;
================================================
FILE: back-master/src/maintenance.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const child_process = require("child_process");
const log = require("@oo/shared").logger("maintenance");
const config = require("@oo/shared").config;
function runMaintenance(next) {
log.info("Starting Maintenance Routine");
switch (config.session.implementation) {
case "docker": {
let MAINTENANCE_COMMAND = "docker ps -a --filter \"status=exited\" --filter \"ancestor=oo/" + config.docker.images.octaveSuffix + "\" | cut -c -12 | xargs -n 1 docker rm -f; docker ps -a --filter \"status=exited\" --filter \"ancestor=oo/" + config.docker.images.filesystemSuffix + "\" | cut -c -12 | xargs -n 1 docker rm -f";
log.trace("Running command:", MAINTENANCE_COMMAND);
child_process.exec(MAINTENANCE_COMMAND, (err, stdout, stderr) => {
log.info("Finished Maintenance Routine");
if (err) log.warn(err);
log.trace(stdout);
log.trace(stderr);
next();
});
break;
}
case "selinux":
case "unsafe":
// Exit this process and let the daemon running it clean up and restart
process.exit(0);
break;
default: {
log.error("Please provide a maintenance command for your implementation");
break;
}
}
}
module.exports = runMaintenance;
================================================
FILE: back-master/src/message-translator.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const EventEmitter = require("events");
const log = require("@oo/shared").logger("message-translator");
const crypto = require("crypto");
const uuid = require("uuid");
const config = require("@oo/shared").config;
// This class "translates" messages between the older format expected by the downstream front end and the newer format expected by the upstream back ends (Octave host and file manager).
class MessageTranslator extends EventEmitter {
// When the upstream back ends send us a message:
fromUpstream(sessCode, name, content) {
switch(name) {
// MESSAGES NEEDING TRANSLATION:
// "request-input" is the newer version of "prompt", which provided a line number as an integer. The line number needs to be extracted via regex for backwards compatibility.
case "request-input": {
let match = content.match(/^octave:(\d+)>\s+$/);
let line_number = -1;
if (match) {
line_number = parseInt(match[1]);
} else {
this._forDownstream(sessCode, "data", {
type: "stdout",
data: content
});
}
this._forDownstream(sessCode, "prompt", { line_number, prompt: content });
break;
}
// "out" and "err" need to be translated to "data" events
case "out": {
this._forDownstream(sessCode, "data", {
type: "stdout",
data: content
});
break;
}
case "err": {
// Send the error text doenstream
this._forDownstream(sessCode, "data", {
type: "stderr",
data: content
});
break;
}
// We need only the "ws" part of the "set-workspace" message
case "set-workspace": {
this._forDownstream(sessCode, "workspace", {
vars: content.ws
});
break;
}
// The new "show-static-plot" needs to be broken into "plotd" (plot data) and "plote" (plot finished)
case "show-static-plot": {
let id = uuid.v4();
this._forDownstream(sessCode, "plotd", {
id: id,
content: content.content
});
this._forDownstream(sessCode, "plote", {
id: id,
md5: crypto.createHash("md5").update(content.content).digest("hex"),
command_number: content.command_number
});
break;
}
// "clc" control command:
case "clear-screen": {
this._forDownstream(sessCode, "ctrl", {
command: "clc"
});
break;
}
// "doc" control command:
case "show-doc": {
var url = content ? `https://octave.sourceforge.io/list_functions.php?q=${encodeURIComponent(content)}` : "https://octave.sourceforge.io/octave/overview.html";
this._forDownstream(sessCode, "ctrl", {
command: `url=${url}`
});
break;
}
// When come other command was suppressed due to length:
case "message-too-long": {
if (content.name === "show-static-plot") {
log.trace("Plot message too long:", content);
this._forDownstream(sessCode, "data", {
type: "stderr",
data: `Warning: Suppressed a large plot (${content.length} bytes).\nMaximum allowable length is ${content.max_length} bytes.\nTip: Try running "clf". If that does not work,\ntry generating a rasterized plot (e.g., imagesc)\ninstead of a vector plot.\n`
});
} else {
log.warn("Unknown message too long:", content);
}
break;
}
// The "exit" event from octave_link:
case "exit": {
this._forDownstream(sessCode, "data", {
type: "exit",
code: content
});
break;
}
// The "exit" event from the child process:
case "docker-exit":
case "process-exit": {
this.emit("destroy", sessCode, "Shell Exited");
break;
}
// The event for when the Octave process is killed:
case "octave-killed": {
this._forDownstream(sessCode, "data", {
type: "stderr",
data: "Error: Octave process killed.\nYou may have been using too much memory.\nYour memory cap is: " + config.docker.memoryShares + "\n"
});
break;
}
// Turn "destroy" into "destroy" on this instance
case "destroy": {
this.emit("destroy", sessCode, content);
break;
}
// Filesystem events: if any of them fail, do not let the events bubble up, but show their error messages on stderr
case "saved":
case "renamed":
case "deleted": {
// FIXME: The rendering of error messages should occur on the client side, not here.
if (content && !content.success) {
this._forDownstream(sessCode, "data", {
type: "stderr",
data: content.message+"\n"
});
break;
} else {
this._forDownstream(sessCode, name, content);
break;
}
}
// File list event (change name from "filelist" to "user")
case "filelist": {
this._forDownstream(sessCode, "user", content);
break;
}
// MESSAGES THAT CAN BE IGNORED:
case "ack":
case "set-history": {
break;
}
// REMAINING MESSAGES:
default: {
this._forDownstream(sessCode, name, content);
break;
}
}
}
// When the downstream client sends us a message:
fromDownstream(sessCode, name, getData) {
switch(name) {
// MESSAGES NEEDING TRANSLATION:
// "data" needs to be translated to the "cmd" event (which is a synonym for "request-input-answer")
case "data":
this._forUpstream(sessCode, "cmd", getData);
break;
// Translate "signal" to "interrupt"
case "signal":
this._forUpstream(sessCode, "interrupt", getData);
break;
// Emit ping/pong as an event
case "oo.ping":
this.emit("ping", sessCode, getData);
break;
case "oo.pong":
this.emit("pong", sessCode, getData);
break;
// MESSAGES THAT CAN BE IGNORED:
case "init":
case "ot.cursor":
case "ot.change":
case "oo.reconnect":
break;
// REMAINING MESSAGES:
default:
this._forUpstream(sessCode, name, getData);
break;
}
}
_forDownstream(sessCode, name, content) {
this.emit("for-downstream", sessCode, name, content);
}
_forUpstream(sessCode, name, getData) {
this.emit("for-upstream", sessCode, name, getData);
}
}
module.exports = MessageTranslator;
================================================
FILE: back-master/src/octave-session.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
// The code in this file is shared among all implementations of the Octave session. See session-impl.js for examples of implementations.
const logger = require("@oo/shared").logger;
const OnlineOffline = require("@oo/shared").OnlineOffline;
const config = require("@oo/shared").config;
const config2 = require("@oo/shared").config2;
const timeLimit = require("@oo/shared").timeLimit;
const fs = require("fs");
const path = require("path");
const async = require("async");
const url = require("url");
const http = require("http");
const https = require("https");
const querystring = require("querystring");
const uuid = require("uuid");
const RedisQueue = require("@oo/shared").RedisQueue;
const base58 = require("base-x")("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
const temp = require("temp");
const onceMessage = require("@oo/shared").onceMessage;
const child_process = require("child_process");
class OctaveSession extends OnlineOffline {
constructor(sessCode, options) {
super();
this.sessCode = sessCode;
this._options = options;
this._log = logger("octave-session:" + sessCode);
this._mlog = logger("octave-session:" + sessCode + ":minor");
this._log.debug("Tier:", this._options.tier);
this._extraTime = 0;
this._countdownExtraTime = config2.tier(this._options.tier)["session.countdownExtraTime"];
this._countdownRequestTime = config2.tier(this._options.tier)["session.countdownRequestTime"];
this._legalTime = config.session.legalTime.guest;
this._payloadLimit = config.session.payloadLimit.guest;
this._resetPayload();
this._plotPngStore = {};
this._plotSvgStore = {};
this._suppressedWarningsStore = {};
this._redisQueue = new RedisQueue(sessCode);
this._redisQueue.on("message", this.sendMessage.bind(this));
this._throttleCounter = 0;
this._throttleTime = process.hrtime();
this.on("error", this._handleError.bind(this));
}
_doCreate(next) {
let subdir = path.join(config.worker.logDir, config.worker.sessionLogs.subdir);
for (let i=0; i {
if (this._countdownTimer) clearTimeout(this._countdownTimer);
if (this._timewarnTimer) clearTimeout(this._timewarnTimer);
if (this._timeoutTimer) clearTimeout(this._timeoutTimer);
if (this._autoCommitTimer) clearInterval(this._autoCommitTimer);
if (this._payloadInterruptTimer) clearTimeout(this._payloadInterruptTimer);
_next(null);
},
(_next) => {
this._doDestroyImpl(_next, reason);
},
(_next) => {
if (this._sessionLogStream) this._sessionLogStream.end(reason);
_next(null);
}
], next);
}
interrupt() {
this._signal("SIGINT");
}
enqueueMessage(name, getData) {
this._redisQueue.enqueueMessage(name, getData);
}
// COUNTDOWN METHODS: For interrupting the Octave kernel after a fixed number of seconds to ensure a fair distribution of CPU time.
// Use an interval to signal Octave once after the first timeout and then repeatedly after that, until the kernel sends us a "request-input" event to signal that it is done processing commands.
_startCountdown() {
if (this._countdownTimer) return;
if (this._state !== "ONLINE") return;
this._countdownTimer = setTimeout(this._onCountdownEnd.bind(this), this._legalTime);
}
_endCountdown() {
if (this._countdownTimer) {
clearTimeout(this._countdownTimer);
this._countdownTimer = null;
}
}
_onCountdownEnd() {
if (new Date().valueOf() - this._extraTime < this._countdownRequestTime + config.session.countdownRequestTimeBuffer) {
// Add 15 seconds and don't send an interrupt signal
this._log.trace("Extending countdown with extra time");
this._countdownTimer = setTimeout(this._onCountdownEnd.bind(this), this._countdownExtraTime);
} else {
// Send an interrupt signal now and again in 5 seconds
this._log.trace("Interrupting execution due to countdown");
this.interrupt();
this.emit("message", "err", "!!! OUT OF TIME !!!\n");
this._countdownTimer = setTimeout(this._onCountdownEnd.bind(this), 5000);
}
}
_addTime() {
// This method gets called when the user clicks the "Add 15 Seconds" button on the front end.
this._extraTime = new Date().valueOf();
}
// TIMEOUT METHODS: For killing the Octave kernel after a fixed number of seconds to clear server resources when the client is inactive.
resetTimeout() {
if (this._state !== "ONLINE") return;
if (this._timewarnTimer) clearTimeout(this._timewarnTimer);
if (this._timeoutTimer) clearTimeout(this._timeoutTimer);
const timewarnTime = config2.tier(this._options.tier)["session.timewarnTime"];
const timeoutTime = config2.tier(this._options.tier)["session.timeoutTime"];
this._mlog.trace("Resetting timeout:", timewarnTime, timeoutTime);
this._timewarnTimer = setTimeout(() => {
this.emit("message", "err", config.session.timewarnMessage+"\n");
}, timewarnTime);
this._timeoutTimer = setTimeout(() => {
this._log.info("Session Timeout");
this.emit("message", "destroy", "Session Timeout");
}, timeoutTime);
}
// PAYLOAD METHODS: For interrupting the Octave kernel after a large amount of stdout/stderr data to prevent infinite loops from using too much bandwidth.
_resetPayload() {
this._payloadSize = 0;
this._payloadInterrupted = false;
}
_appendToPayload(content) {
this._payloadSize += content.length;
if (this._payloadSize > this._payloadLimit && !this._payloadInterrupted) {
this._payloadInterrupted = true;
// End the countdown, and instead give the user a specified amount of time to allow the process to continue from where it left off.
this._signal("SIGSTOP");
this._endCountdown();
let payloadDelay = config.session.payloadAcknowledgeDelay;
this._payloadInterruptTimer = setTimeout(() => {
this._signal("SIGCONT");
this._signal("SIGINT");
// Send the error message after a small delay in order to let the output buffers flush first
setTimeout(() => {
this.emit("message", "err", "!!! PAYLOAD TOO LARGE !!!\n");
// Octave sometimes gets confused with the interrupt signal, so send an empty command to reset things.
this._sendMessageToHost("cmd", "");
}, config.session.payloadMessageDelay);
}, payloadDelay);
// Tell the user how much time they have.
this.emit("message", "payload-paused", {
delay: payloadDelay
});
}
}
_acknowledgePayload() {
if (!this._payloadInterrupted) return this._log.warn("Attempting to acknowledge payload, but process is not currently paused");
this._log.trace("User manually acknowledged payload");
this._continueIfPaused();
this._resetPayload();
}
_continueIfPaused() {
if (!this._payloadInterrupted) return;
this._log.trace("Continuing execution");
clearTimeout(this._payloadInterruptTimer);
this._signal("SIGCONT");
this._startCountdown();
}
// AUTO-COMMIT METHODS: For auto-committing the user's files on a fixed interval.
_startAutoCommitLoop() {
this._autoCommitTimer = setInterval(() => {
this._log.debug("Requesting auto-commit...");
this._commit("Scripted auto-commit", this._handleError.bind(this));
}, config.git.autoCommitInterval);
}
_commit(comment, next) {
// Set a 60-second time limit
let _next = timeLimit(config.git.commitTimeLimit, [new Error("Out of time")], next);
// Call the callback when a "committed" message is received
this._onceMessageFromFiles("committed", () => { _next(null); });
// Request the commit
this._sendMessageToFiles("commit", { comment });
}
// SESSION LOG: Log all commands, input, and output to a log file
_appendToSessionLog(type, content) {
if (!this._sessionLogStream) return this._log.warn("Cannot log before created", { type, content });
if (this._sessionLogStream.closed) return this._log.warn("Cannot log to a closed stream:", { type, content });
this._sessionLogStream.write(type + ": " + content.replace(/\n/g, "\n" + type + ": ") + "\n");
}
// PLOTTED PNG IMAGE METHODS: Convert image links to base-64 data URIs
// TODO: A better way to do this would be to modify GNUPlot to directly save PNG images as base-64 URIs. I did it this way because I wanted to avoid having to maintain a fork from another major project.
_convertPlotImages(content) {
// Search the plot SVG for local PNG files that we need to load
let imageNames = [];
let regex = /xlink:href='(\w+).png'/g;
let match;
while ((match = regex.exec(content.content))) {
imageNames.push(match[1]);
}
if (imageNames.length === 0) return false;
// Enqueue the images for loading
let id = uuid.v4();
let svgObj = {
content: content.content,
command_number: (content.command_number || -1),
waitCount: 0
};
imageNames.forEach((name) => {
let filename = name + ".png";
if (filename in this._plotPngStore) {
return this._log.error("Plot image is already in the queue:", filename);
}
this._plotPngStore[filename] = id;
svgObj.waitCount++;
// Actually send the read-image job upstream:
this._sendMessageToFiles("read-delete-binary", { filename });
});
this._plotSvgStore[id] = svgObj;
this._log.debug(`Loading ${svgObj.waitCount} images for plot`, id);
return true;
}
_onDeletedBinary(content) {
if (content.filename in this._plotPngStore) {
this._resolvePng(content);
return true;
} else if (!content.success) {
// TODO: Implement a better way to resolve load errors.
this._log.warn("Failed loading a plot image; discarding all pending plots");
this._plotPngStore = {};
this._plotSvgStore = {};
} else {
return false;
}
}
_resolvePng(content) {
let filename = content.filename;
let base64data = content.base64data;
let id = this._plotPngStore[filename];
delete this._plotPngStore[filename];
let svgObj = this._plotSvgStore[id];
this._log.trace(`Loaded image '${filename}' for plot`, id);
// Perform the substitution
svgObj.content = svgObj.content.replace(`xlink:href='${filename}'`, `xlink:href='data:image/png;base64,${base64data}'`);
// Have we loaded all of the images we need to replace?
svgObj.waitCount--;
if (svgObj.waitCount === 0) {
this._log.debug("Loaded all images for plot", id);
this.emit("message", "show-static-plot", {
content: svgObj.content,
command_number: svgObj.command_number
});
delete this._plotSvgStore[id];
}
}
// URL METHODS: Perform URL requests on behalf of the user. Uses a hard-coded whitelist in the config file for filtering out legal URLs.
_handleRequestUrl(content) {
try {
let urlObj = url.parse(content.url);
// Check if the hostname is legal
if (urlObj.hostname === null) {
this._sendMessageToHost("request-url-answer", [false, "You must specify a URL of the form http://example.com/"]);
return;
}
let isLegal = false;
for (let pattern of config.session.urlreadPatterns) {
if (new RegExp(pattern).test(urlObj.hostname)) {
isLegal = true;
break;
}
}
if (!isLegal) {
this._sendMessageToHost("request-url-answer", [false, `The hostname ${urlObj.hostname} is not whitelisted\nfor access by Octave Online. If you think this hostname\nshould be whitelisted, please open a support ticket.`]);
return;
}
// Convert from the query param list to a query string
let paramObj = {};
for (let i=0; i {
this._log.trace("Received URL response:", res.statusCode, urlObj.href);
res.setEncoding("base64");
let fullResult = "";
let errmsg = "";
res.on("data", (chunk) => {
if (chunk.length + fullResult.length > config.session.urlreadMaxBytes) {
errmsg = `Requested URL exceeds maximum of ${config.session.urlreadMaxBytes} bytes`;
} else {
fullResult += chunk;
}
});
res.on("end", () => {
this._log.trace("URL response after processing:", errmsg, fullResult.length);
if (errmsg) {
this._sendMessageToHost("request-url-answer", [false, errmsg]);
} else {
this._sendMessageToHost("request-url-answer", [true, fullResult]);
}
});
});
req.on("error", (err) => {
this._log.trace("Problem with URL request:", err.message);
this._sendMessageToHost("request-url-answer", [false, err.message]);
});
req.write(payload);
req.end();
} catch(err) {
this._sendMessageToHost("request-url-answer", [false, err.message]);
}
}
// BUCKET METHODS: Create (and destroy) buckets with snapshots of static files that can be published.
_createBucket(bucketInfo) {
let filenames = bucketInfo.filenames;
if (!Array.isArray(filenames)) return;
// Create the bucket ID.
// Note: Starting 2021-08-07, the bucket ID is generated on the front server instead. The if statement here is for backwards compatibility.
let bucketId = bucketInfo.bucket_id;
if (!bucketId) {
const bucketIdBuffer = new Buffer(16);
uuid.v4({}, bucketIdBuffer, 0);
bucketId = base58.encode(bucketIdBuffer);
bucketInfo.bucket_id = bucketId;
}
this._log.debug("Creating new bucket:", bucketId, filenames);
async.auto({
"read_files": (_next) => {
// Load the bucket files into memory.
this._mlog.trace("Reading files for bucket");
let jobId = uuid.v4();
this._onceMessageFromFiles("multi-binary:" + jobId, (err, data) => {
if (!data.success) return _next(new Error("Unsuccessful call to multi-binary"));
_next(null, data.results);
}, _next);
this._sendMessageToFiles("multi-binary", {
id: jobId,
filenames: filenames
});
},
"tmpdir": (_next) => {
// We need to create a working directory for the bucket git
this._mlog.trace("Creating tmpdir for bucket");
temp.mkdir("oo-", _next);
},
"session": (_next) => {
// Create a Git session for the new bucket.
const session = this._makeNewFileSession("create-bucket:" + bucketId);
session.on("message", (name /*, content */) => {
this._mlog.trace("Bucket file session message:", name);
});
session.on("error", (err) => {
this._log.error("Bucket file session error:", err);
});
_next(null, session);
},
// NOTE: In Async 1.5.x, the version used here, the argument order is (_next, results), but in Async 2.x, the argument order changed to (results, _next).
"session_create": ["tmpdir", "session", (_next, results) => {
this._mlog.trace("Creating session for bucket");
results.session.create(_next, results.tmpdir);
}],
"session_init": ["session_create", (_next, results) => {
this._mlog.trace("Initializing session for bucket");
onceMessage(results.session, "filelist", _next);
results.session.sendMessage("bucket-info", {
id: bucketId,
readonly: false
});
}],
"write_files": ["read_files", "session_init", (_next, results) => {
this._mlog.trace("Writing files for bucket");
let jobId = uuid.v4();
onceMessage(results.session, "multi-binary-saved:" + jobId, (err, data) => {
if (!data.success) return _next(new Error("Unsuccessful call to save-multi-binary"));
_next(null);
});
results.session.sendMessage("save-multi-binary", {
id: jobId,
filenames: filenames,
base64datas: results.read_files
});
}],
"commit": ["write_files", (_next, results) => {
this._mlog.trace("Committing files for bucket");
onceMessage(results.session, "committed", _next);
results.session.sendMessage("commit", {
comment: "Scripted bucket creation: " + bucketId
});
}],
"destroy_session": ["commit", (_next, results) => {
this._mlog.trace("Destroying session for bucket");
results.session.destroy(_next);
}],
"destroy_tmpdir": ["destroy_session", (_next, results) => {
this._mlog.trace("Destroying working dir bucket");
child_process.exec(`rm -rf ${results.tmpdir}`, _next);
}]
}, (err) => {
if (err) {
this._log.error("Error creating bucket:", err);
this.emit("message", "err", "Encountered an error creating the bucket.\n");
} else {
this._log.info("Finished creating new bucket:", bucketId);
this.emit("message", "bucket-repo-created", bucketInfo);
}
});
}
// Prevent spammy messages from clogging up the server.
// TODO: It would be better if this were done deeper in the stack, such as host.c, so that message spamming doesn't reach all the way into the main event loop.
_checkThrottle() {
// FIXME: Make these config values.
// Nominal values: 100 messages per 100 milliseconds (1000 messages/second) = spam.
// INTERVAL_DURATION should be less than 1e9.
let MSGS_PER_INTERVAL = 100;
let INTERVAL_DURATION = 1e8;
if (++this._throttleCounter < MSGS_PER_INTERVAL) return;
this._throttleCounter = 0;
let diff = process.hrtime(this._throttleTime);
this._throttleTime = process.hrtime();
if (diff[0] === 0 && diff[1] < INTERVAL_DURATION) {
this._log.warn("Messages too rapid! Killing process!", diff);
this.emit("message", "destroy", "Too Many Packets");
}
}
sendMessage(name, content) {
switch (name) {
// Messages requiring special handling
case "interrupt":
this._continueIfPaused();
this.interrupt();
break;
case "oo.add_time":
this._addTime();
this.resetTimeout();
break;
case "oo.acknowledge_payload":
this._acknowledgePayload();
this.resetTimeout();
break;
case "cmd":
// FIXME: The following translation (from content to content.data) should be performed in message-translator.js, but we're unable to do so because the data isn't downloaded from Redis until after message-translator is run. Is there a more elegant place to put this? Maybe all message translation should happen here in octave-session.js instead?
content = content.data || "";
if (typeof content !== "string") {
this._log.error("content is not a string:", content);
break;
}
this._startCountdown();
this.resetTimeout();
this._appendToSessionLog(name, content);
// Split the command into individual lines and send them to Octave one-by-one.
content.split("\n").forEach((line) => {
this._sendMessageToHost(name, line);
});
break;
case "user-info":
if (content && content.user) {
this._startAutoCommitLoop();
this._legalTime = content.user.legalTime;
this._payloadLimit = content.user.payloadLimit;
this._countdownExtraTime = content.user.countdownExtraTime;
this._countdownRequestTime = content.user.countdownRequestTime;
}
if (content.bucketId && !content.bucket) {
// For backwards compatibility
content.bucket = {
bucket_id: content.bucketId,
butype: "readonly",
};
}
if (content.bucket) {
if (!content.bucket.butype) {
this._log.error("butype not present in bucket", content);
content.butype = "readonly";
}
this._sendMessageToFiles("bucket-info", {
id: content.bucket.bucket_id,
legalTime: this._legalTime, // For backwards compatibility
readonly: content.bucket.butype === "readonly",
});
} else {
this._sendMessageToFiles(name, content);
}
break;
case "oo.create_bucket":
this._createBucket(content);
break;
// Messages to forward to the file manager
case "list":
case "refresh":
case "commit":
case "save":
case "rename":
case "delete":
case "binary":
case "read-delete-binary":
case "siofu_start":
case "siofu_progress":
case "siofu_done":
this._sendMessageToFiles(name, content);
break;
// Messages to forward to the Octave host
case "request-input-answer":
case "request-url-answer":
case "confirm-shutdown-answer":
case "prompt-new-edit-file-answer":
case "message-dialog-answer":
case "question-dialog-answer":
case "list-dialog-answer":
case "input-dialog-answer":
case "file-dialog-answer":
case "debug-cd-or-addpath-error-answer":
this._sendMessageToHost(name, content);
break;
// Unknown messages
default:
this._log.debug("Message ignored:", name);
break;
}
}
_handleMessage(name, content) {
// Check for message throttling, except for "out" and "err" messages, which are throttled via payload.
if (name !== "out" && name !== "err") this._checkThrottle();
// Special pre-processing of a few events here
switch (name) {
case "show-static-plot":
// Convert PNG file links to embedded base 64 data
if (this._convertPlotImages(content)) return;
break;
case "deleted-binary":
// If we're waiting for any binary files, capture them here rather than sending them downstream
if (this._onDeletedBinary(content)) return;
break;
case "display-warning":
let opWarningMatch = /(the '.*' operator)/.exec(content.message);
if (opWarningMatch) {
if (this._suppressedWarningsStore[opWarningMatch[0]]) {
this._mlog.trace("Suppressed duplicate warning:", content.id);
return;
}
this._suppressedWarningsStore[opWarningMatch[0]] = true;
}
name = "err";
content = content.formatted;
break;
case "display-exception":
name = "err";
content = content.ee_str;
break;
default:
break;
}
if (name === "err") {
// Filter out some error messages
if (/warning: readline is not linked/.test(content)) return;
if (/warning: docstring file/.test(content)) return;
if (/error: unable to open .+macros\.texi/.test(content)) return;
if (/^\/tmp\/octave-help-/.test(content)) return;
if (/built-in-docstrings' not found/.test(content)) return;
}
if (/^multi-binary:[\w-]+$/.test(name)) return;
// Forward remaining events downstream
this.emit("message", name, content);
this.emit(`msg:${name}`, content);
// Special post-processing of a few more events here
switch (name) {
case "request-input":
this._endCountdown();
this.resetTimeout();
this._resetPayload();
break;
case "err":
case "out":
this._appendToPayload(content);
this._appendToSessionLog(name, content);
break;
case "request-url":
this._handleRequestUrl(content);
break;
// UNIMPLEMENTED FEATURES REQUIRING RESPONSE:
case "confirm-shutdown":
this._sendMessageToHost("confirm-shutdown-answer", true);
break;
case "prompt-new-edit-file":
this._sendMessageToHost("prompt-new-edit-file-answer", true);
break;
case "message-dialog":
this._sendMessageToHost("message-dialog-answer", 0);
break;
case "question-dialog":
this._sendMessageToHost("question-dialog-answer", "");
break;
case "list-dialog":
this._sendMessageToHost("list-dialog-answer", [[],0]);
break;
case "input-dialog":
this._sendMessageToHost("input-dialog-answer", []);
break;
case "file-dialog":
this._sendMessageToHost("file-dialog-answer", []);
break;
case "debug-cd-or-addpath-error":
this._sendMessageToHost("debug-cd-or-addpath-error-answer", 0);
break;
default:
break;
}
}
_handleError(err) {
if (err) this._log.error(err);
}
}
module.exports = OctaveSession;
================================================
FILE: back-master/src/process-handler.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const async = require("async");
const logger = require("@oo/shared").logger;
const StdioMessenger = require("@oo/shared").StdioMessenger;
class ProcessHandler extends StdioMessenger {
constructor(sessCode) {
super();
this._log = logger(`process-handler:${sessCode}`);
this._mlog = logger(`process-handler:${sessCode}:minor`);
this.sessCode = sessCode;
}
_doCreate(next, fn) {
async.series([
(_next) => {
// Spawn the process
let args = Array.prototype.slice.call(arguments, 2);
this._mlog.trace("Spawning process:", args[0], args[1].join(" "), args[2]);
this._spwn = fn.apply(this, args);
// Create all unexpected error listeners
this._spwn.on("error", (err) => { this._log.error("spwn:", err); });
this._spwn.stdin.on("error", (err) => { this._log.error("stdin:", err); });
this._spwn.stdout.on("error", (err) => { this._log.error("stdout:", err); });
this._spwn.stderr.on("error", (err) => { this._log.error("stderr:", err); });
// Create stderr listener
this._spwn.stderr.on("data", this._handleLog.bind(this));
// Create exit listener
this._spwn.on("exit", this._handleExit.bind(this));
// Listen to main read stream
this.setReadStream(this._spwn.stdout);
// Wait until we get an acknowledgement before continuing. Two conditions: receipt of the acknowledgement message, and premature exit.
var ack = false;
this.once("message", (name /*, content */) => {
if (ack) return;
ack = true;
// Error if the message is process-exit
if (name === "process-exit") return _next(new Error("Process exited prematurely"));
// Don't enable the write stream until down here because we don't want to write messages to the child's STDIN until we've acknowledged that it is online
this.setWriteStream(this._spwn.stdin);
_next(null);
});
}
], (err) => {
if (err) return next(err);
this._mlog.debug("Finished creating");
return next(null);
});
}
_doDestroy(next) {
// This method wont't be called unless the process state is ONLINE, so we don't need to check.
if (this._spwn) {
// We can ignore the "next" callback because it will be implicitly called by _handleExit()
this._mlog.trace("this._spwn exists");
this._doDestroyProcess();
} else {
this._mlog.trace("this._spwn does not exist");
next(null);
}
}
signal(name) {
if (!this._spwn) return this._log.warn("Tried to signal child process, but it does not exist");
if (this._spwn.exitCode !== null || this._spwn.signalCode !== null) return this._log.warn("Tried to signal child process, but it is exited");
this._signal(name);
this._log.debug("Sent " + name + " to child process");
}
_signal(name) {
this._spwn.kill(name);
}
_handleLog(data) {
// Log message to console
data.toString().trim().split("\n").forEach((line) => {
this._mlog.log(line);
});
}
_handleExit(code, signal) {
this._log.debug("Process Exit:", code, signal);
this._spwn = null;
this.emit("message", "process-exit", { code, signal });
this._internalDestroyed(null);
// TODO: when to emit this.emit("message", "octave-killed") ?
}
}
module.exports = ProcessHandler;
================================================
FILE: back-master/src/session-impl.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const OctaveSession = require("./octave-session");
const { CappedFileSystem, TmpWorkDirectory } = require("./capped-file-system");
const DockerHandler = require("./docker-handler");
const ProcessHandler = require("./process-handler");
const config = require("@oo/shared").config;
const config2 = require("@oo/shared").config2;
const async = require("async");
const silent = require("@oo/shared").silent;
const child_process = require("child_process");
const logger = require("@oo/shared").logger;
const pstree = require("ps-tree");
const temp = require("temp");
const OnlineOffline = require("@oo/shared").OnlineOffline;
const Queue = require("@oo/shared").Queue;
const onceMessage = require("@oo/shared").onceMessage;
const FilesController = require("../../back-filesystem/src/controller");
class SessionImpl extends OctaveSession {
constructor(sessCode, options) {
super(sessCode, options);
this.options = options;
this._makeSessions();
if (config.session.implementation === "unsafe") {
this._cfs = new TmpWorkDirectory(this.sessCode);
} else {
this._cfs = new CappedFileSystem(this.sessCode, config.docker.diskQuotaKiB);
}
this._filesSession.on("message", this._handleMessage.bind(this));
this._hostSession.on("message", this._handleMessage.bind(this));
this._cfs.on("error", this._handleError.bind(this));
this._filesSession.on("error", this._handleError.bind(this));
this._hostSession.on("error", this._handleError.bind(this));
}
_doCreateImpl(next) {
async.auto({
"cfs": (_next) => {
this._mlog.trace("Requesting creation of capped file system");
this._cfs.create((err, dataDir) => {
if (!err) this._dataDir = dataDir;
_next(err);
});
},
"files": ["cfs", (_next) => {
this._mlog.trace("Requesting creation of file manager process");
this._filesSession.create(_next, this._dataDir);
}],
"host": ["cfs", (_next) => {
this._mlog.trace("Requesting creation of Octave host process");
this._hostSession.create(_next, this._dataDir);
}]
}, (err) => {
if (err) return next(err);
this._log.info("Session successfully created");
this.resetTimeout();
return next(null);
});
}
_doDestroyImpl(next, reason) {
// TODO: Add an alternative destroy implementation that is synchronous, so that it can be run in an exit handler.
async.auto({
"commit": (_next) => {
this._mlog.trace("Requesting to commit changes to Git");
this._commit("Scripted user file commit", silent(/Out of time/, _next));
},
"host": ["commit", (_next) => {
this._mlog.trace("Requesting termination of Octave host process");
this._hostSession.destroy(_next);
}],
"files": ["commit", (_next) => {
this._mlog.trace("Requesting termination of file manager process");
this._filesSession.destroy(_next);
}],
"cfs": ["host", "files", (_next) => {
this._mlog.trace("Requesting deletion of capped file system");
this._cfs.destroy(_next);
}]
}, (err) => {
if (err) return next(err);
this._log.info("Session successfully destroyed:", reason);
return next(null);
});
}
_signal(name) {
this._hostSession.signal(name);
}
_sendMessageToFiles(name, content) {
this._filesSession.sendMessage(name, content);
}
_sendMessageToHost(name, content) {
this._mlog.trace("Sending message to Octave host:", name, content);
this._hostSession.sendMessage(name, content);
}
_onceMessageFromFiles(name, next) {
onceMessage(this._filesSession, name, next);
}
}
class HostProcessHandler extends ProcessHandler {
constructor(sessCode, options) {
super(sessCode);
this.options = options;
// Override default logger with something that says "host"
this._log = logger(`host-handler:${sessCode}`);
this._mlog = logger(`host-handler:${sessCode}:minor`);
}
_doCreate(next, dataDir) {
const tier = this.options.tier;
let cgroupName = config2.tier(tier)["selinux.cgroup.name"];
let addressSpace = config2.tier(tier)["selinux.prlimit.addressSpace"];
const envVars = [
"env", "GNUTERM=svg",
"env", "LD_LIBRARY_PATH=/usr/local/lib",
"env", "OO_SESSCODE="+this.sessCode,
"env", "OO_TIER="+this.options.tier
];
async.series([
(_next) => {
temp.mkdir("oo-", (err, tmpdir) => {
this._mlog.debug("Created tmpdir:", tmpdir);
this.tmpdir = tmpdir;
_next(err);
});
},
(_next) => {
if (config.session.implementation === "unsafe") {
// Spawn un-sandboxed process
super._doCreate(_next, child_process.spawn, "env", [].concat(envVars.slice(1)).concat(["/usr/local/bin/octave-host", config.session.jsonMaxMessageLength]), {
cwd: dataDir
});
} else {
// Spawn sandboxed process
// The CWD is set to /tmp in order to make the child process not hold a reference to the mount that the application happens to be running under.
super._doCreate(_next, child_process.spawn, "/usr/bin/prlimit", [
"--as="+addressSpace,
"/usr/bin/cgexec",
"-g", "cpu:"+cgroupName,
"/usr/bin/sandbox",
"-M",
"-H", dataDir,
"-T", this.tmpdir,
"--level", "s0"]
.concat(envVars)
.concat([
"/usr/local/bin/octave-host", config.session.jsonMaxMessageLength
]),
{
cwd: "/tmp"
});
}
},
(_next) => {
// We need to get the octave-cli PID for signalling, because sandbox handles signals strangely.
this.octavePID = null;
async.whilst(
() => { return !this.octavePID && this._state !== "DESTROYED"; },
(__next) => {
async.waterfall([
(___next) => {
setTimeout(___next, 250);
},
(___next) => {
this._mlog.trace("Attempting to get Octave PID...");
pstree(this._spwn.pid, ___next);
},
(children, ___next) => {
let child = children.find((_child) => { return /octave-cli/.test(_child.COMMAND); });
if (child) {
this.octavePID = child.PID;
this._mlog.debug("Got Octave PID:", this.octavePID);
}
___next(null);
}
], __next);
},
_next
);
}
], next);
}
_doDestroy(next) {
async.series([
super._doDestroy.bind(this),
(_next) => {
if (this.tmpdir) {
this._mlog.trace("Destroying tmpdir");
child_process.exec(`rm -rf ${this.tmpdir}`, _next);
} else {
process.nextTick(_next);
}
}
], next);
}
_doDestroyProcess() {
// Starting with Octave 4.4, sending SIGTERM is insufficient to make Octave exit.
this._log.trace("Executing 'exit' in Octave process");
this.sendMessage("cmd", "exit");
setTimeout(() => {
if (!this._spwn) {
this._mlog.trace("Not sending SIGKILL: Process is already exited");
return;
}
this._log.trace("Sending SIGKILL");
this._signal("SIGKILL");
}, 10000);
}
_signal(name) {
if (!this.octavePID) return this._log.error("Cannot signal Octave process yet");
child_process.exec(`kill -s ${name.slice(3)} ${this.octavePID}`, (err) => {
if (err) this._log.error("signalling octave:", err);
});
}
}
class FilesControllerHandler extends OnlineOffline {
constructor(sessCode) {
super();
this._log = logger(`files-handler:${sessCode}`);
this._mlog = logger(`files-handler:${sessCode}:minor`);
this.sessCode = sessCode;
this._messageQueue = new Queue();
}
_doCreate(next, dataDir) {
async.series([
(_next) => {
// Make the gitdir
temp.mkdir("oo-", (err, tmpdir) => {
this._mlog.debug("Created gitdir:", tmpdir);
this.gitdir = tmpdir;
_next(err);
});
},
(_next) => {
// Make the controller
this.controller = new FilesController(this.gitdir, dataDir, this.sessCode);
// Flush messages to the controller
while (!this._messageQueue.isEmpty()) this._flush();
this._messageQueue.on("enqueue", this._flush.bind(this));
// Emit messages from the controller
this.controller.on("message", (name, content) => {
this.emit("message", name, content);
});
_next(null);
}
], next);
}
_doDestroy(next) {
async.series([
(_next) => {
if (this.controller) {
this.controller.destroy();
}
if (this.gitdir) {
this._mlog.trace("Destroying gitdir");
child_process.exec(`rm -rf ${this.gitdir}`, _next);
} else {
process.nextTick(_next);
}
}
], next);
}
sendMessage(name, content) {
this._messageQueue.enqueue([name, content]);
}
_flush() {
this.controller.receiveMessage.apply(this.controller, this._messageQueue.dequeue());
}
}
class SessionSELinux extends SessionImpl {
_makeSessions() {
this._filesSession = new FilesControllerHandler(this.sessCode);
this._hostSession = new HostProcessHandler(this.sessCode, this.options);
}
_makeNewFileSession(sessCode) {
return new FilesControllerHandler(sessCode);
}
}
class HostDockerHandler extends DockerHandler {
constructor(sessCode) {
super(sessCode);
this._dockerImage = config.docker.images.octaveSuffix;
this._dockerName = `oo-host-${sessCode}`;
// Override default logger with something that says "host"
this._log = logger(`host-handler:${sessCode}`);
this._mlog = logger(`host-handler:${sessCode}:minor`);
}
_doCreate(next, dataDir) {
// More about resource management: https://goldmann.pl/blog/2014/09/11/resource-management-in-docker/
const dockerArgs = [
"run", "-i",
"-v", `${dataDir}:${config.docker.cwd}`,
"--cpu-shares", config.docker.cpuShares,
"-m", config.docker.memoryShares,
"--name", this._dockerName,
`oo/${this._dockerImage}`
];
super._doCreate(next, dockerArgs);
}
}
class FilesDockerHandler extends DockerHandler {
constructor(sessCode) {
super(sessCode);
this._dockerImage = config.docker.images.filesystemSuffix;
this._dockerName = `oo-files-${sessCode}`;
// Override default logger with something that says "files"
this._log = logger(`files-handler:${sessCode}`);
this._mlog = logger(`files-handler:${sessCode}:minor`);
}
_doCreate(next, dataDir) {
const dockerArgs = [
"run", "-i",
"-v", `${dataDir}:${config.docker.cwd}`,
"--name", this._dockerName,
`oo/${this._dockerImage}`
];
super._doCreate(next, dockerArgs);
}
}
class SessionDocker extends SessionImpl {
_makeSessions() {
this._filesSession = new FilesDockerHandler(this.sessCode);
this._hostSession = new HostDockerHandler(this.sessCode);
}
_makeNewFileSession(sessCode) {
return new FilesDockerHandler(sessCode);
}
}
module.exports = {
docker: SessionDocker,
selinux: SessionSELinux,
docker_handler: HostDockerHandler,
selinux_handler: HostProcessHandler
};
================================================
FILE: back-master/src/session-manager.js
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
"use strict";
const log = require("@oo/shared").logger("session-manager");
const mlog = require("@oo/shared").logger("session-manager:minor");
const EventEmitter = require("events");
const impls = require("./session-impl");
const uuid = require("uuid");
const Queue = require("@oo/shared").Queue;
const config = require("@oo/shared").config;
const config2 = require("@oo/shared").config2;
const metrics = require("@oo/shared").metrics;
const timeLimit = require("@oo/shared").timeLimit;
class SessionManager extends EventEmitter {
constructor(maxOnly) {
super();
this._pool = {};
this._poolSizes = {};
let tiersEnabled;
if (maxOnly) {
tiersEnabled = ["_maxima"];
} else {
tiersEnabled = Object.keys(config.tiers);
tiersEnabled.splice(tiersEnabled.indexOf("_maxima"), 1);
}
tiersEnabled.forEach((tier) => {
if (config2.tier(tier)["sessionManager.poolTier"]) {
mlog.info("Skipping tier with poolTier:", tier);
// continue
} else {
mlog.info("Enabling tier:", tier);
this._pool[tier] = {};
this._poolSizes[tier] = config2.tier(tier)["sessionManager.poolSize"];
}
});
log.info("Enabled tiers:", Object.keys(this._pool));
this._online = {};
this._monitor_session = null;
this._setup();
this.startPool();
this.recordMetrics();
}
_setup() {
// Log the session index on a fixed interval
this._logInterval = setInterval(() => {
Object.keys(this._pool).forEach((tier) => {
log.debug("Current Number of Pooled Sessions, tier " + tier + ":", Object.keys(this._pool[tier]).length);
log.trace(Object.keys(this._pool[tier]).join("; "));
});
log.debug("Current Number of Online Sessions:", Object.keys(this._online).length);
log.trace(Object.keys(this._online).join("; "));
// Time an arbitrary command to test server health
if (this._monitor_session) {
let t1 = new Date().valueOf();
this._monitor_session.sendMessage("cmd", { data: "pinv(magic(500));" });
this._monitor_session.once("msg:request-input", () => {
const elapsed = new Date().valueOf() - t1;
log.debug("Monitor Time (ms):", elapsed);
metrics.gauge("oo.monitor_time_ms", elapsed);
});
}
}, config.sessionManager.logInterval);
// Keep pool sessions alive
this._keepAliveInterval = setInterval(() => {
Object.keys(this._pool).forEach((tier) => {
Object.keys(this._pool[tier]).forEach((localCode) => {
this._pool[tier][localCode].session.resetTimeout();
});
});
}, config.session.timewarnTime/2);
}
numActiveSessions() {
return Object.keys(this._online).length;
}
canAcceptNewSessions() {
if (!this._poolVar.enabled) {
return false;
}
if (this.numActiveSessions() >= config.worker.maxSessions) {
return false;
}
for (let tier of Object.keys(this._pool)) {
// Require every tier to have at least 1 session in the pool
if (Object.keys(this._pool[tier]).length === 0) {
return false;
}
}
return true;
}
usagePercent() {
return this.numActiveSessions() / config.worker.maxSessions;
}
isHealthy() {
return this._monitor_session && this._monitor_session.isOnline();
}
_create(next, options) {
// Get the correct implementation
const SessionImpl = config.session.implementation === "docker" ? impls.docker : impls.selinux;
// Create the session object
const localCode = uuid.v4(null, new Buffer(16)).toString("hex");
const session = new SessionImpl(localCode, options);
// Add messages to a cache when they are created
const cache = new Queue();
session.on("message", (name, content) => {
cache.enqueue([name, content]);
});
session.create(timeLimit(config.sessionManager.startupTimeLimit, [new Error("Time limit reached")], (err) => {
// Get rid of the session if it failed to create
if (err) {
log.warn("Session failed to create:", localCode, err);
session.destroy(null, "Failed To Create");
next();
return;
}
// Call the callback
next(localCode, session, cache, options);
}));
}
attach(remoteCode, content) { // Move pool session to online session
if (!this.canAcceptNewSessions()) return log.warn("Cannot accept any new sessions right now");
// TODO: Backwards compatibility with old front server: the message content can be the user itself; if null, it is a guest user.
if (!content) {
content = { user: null };
} else if (content.parametrized) {
content = { user: content };
}
// Determine which tier to use
// Important: the user in content.user is not necesarilly the currently authenticated user; it could be the owner of a shared workspace.
const user = content.user;
const tier = content.tier ? content.tier : user ? user.tier : Object.keys(this._pool)[0];
const poolTier = config2.tier(tier)["sessionManager.poolTier"] || tier;
// eslint-disable-next-line no-console
console.assert(Object.keys(this._pool).includes(poolTier), poolTier);
// Pull from the pool
const localCode = Object.keys(this._pool[poolTier])[0];
this._online[remoteCode] = this._pool[poolTier][localCode];
delete this._pool[poolTier][localCode];
log.info("Upgraded pool session", poolTier, localCode, remoteCode);
this.recordMetrics();
// Convenience references
const session = this._online[remoteCode].session;
const cache = this._online[remoteCode].cache;
// Reset the session timeout to leave the user with a full allotment of time
session.resetTimeout();
// Send payload upstream
session.sendMessage("user-info", content);
// Forward future messages
cache.on("enqueue", () => {
const message = cache.dequeue();
this.emit("message", remoteCode, message[0], message[1]);
});
// Save the start time to keep a record of the time spent on flavor servers
var startTime = new Date().valueOf();
// Create touch interval for Redis and save reference
const touchInterval = setInterval(() => {
this.emit("touch", remoteCode, startTime);
}, config.redis.expire.interval);
// Emit an event to set to live in Redis (required for OT)
this.emit("live", remoteCode);
// Add user and touchInterval to store
this._online[remoteCode].user = user;
this._online[remoteCode].touchInterval = touchInterval;
// Flush cached messages
// Do this at the end in case any of the messages are "exit" messages
while (!cache.isEmpty()) {
const message = cache.dequeue();
mlog.trace("Flushing message:", remoteCode, message[0]);
if (/exit/.test(message[0])) log.warn("Exit message:", message[1]);
this.emit("message", remoteCode, message[0], message[1]);
}
}
get(sessCode) {
// Look up session
const meta = this._online[sessCode];
if (!meta) return null;
// Return it
return meta.session;
}
destroy(sessCode, reason) {
// Look up session
const meta = this._online[sessCode];
if (!meta) {
if (/Shell Exited/.test(reason)) return;
else return log.warn("Cannot find session to destroy:", sessCode, reason);
}
// Destroy the session
const session = meta.session;
session.destroy((err) => {
if (err) {
log.error("Error destroying session:", sessCode, err);
}
this.emit("destroy-done", sessCode);
}, reason);
// Send destroy-u message
this.emit("destroy-u", sessCode, reason);
// Dereference pointers
meta.session = null;
meta.cache = null;
meta.user = null;
clearInterval(meta.touchInterval);
// Remove it from the index
delete this._online[sessCode];
log.debug("Removed session from index", sessCode);
this.recordMetrics();
}
startPool() {
if (this._poolVar && this._poolVar.enabled) {
throw new Error("Another pool is already running");
}
// I made poolVar a local variable so that there will be one instance for each startPool closure. Each pool creation loop should be independent from any other pool creation loops that might start or stop. (Potential problem that this approach prevents: if a session is in the middle of creating, and the pool is disabled and then immediately enabled again, the first pool might not be destroyed if the "pool enabled" variable were singleton.)
let poolVar = { enabled: true };
this._poolVar = poolVar;
let _poolCb = (localCode, session, cache, options) => {
// If we need to disable the pool...
if (!poolVar.enabled) {
if (session) session.destroy(null, "Pool Disabled");
return;
}
// If the session was created successfully...
if (session) {
if (!this._monitor_session) {
log.info("Created monitor session:", localCode);
this._monitor_session = session;
cache.enabled = false;
cache.removeAll();
} else {
this._pool[options.tier][localCode] = { session, cache };
this.recordMetrics();
}
}
// If we need to put another session in our pool...
for (let tier of Object.keys(this._pool)) {
if (Object.keys(this._pool[tier]).length < this._poolSizes[tier]) {
log.trace("Creating new session in tier", tier);
this._create(_poolCb, { tier });
return;
}
}
// No more sessions were required.
setTimeout(_poolCb, config.sessionManager.poolInterval);
};
process.nextTick(_poolCb);
}
disablePool() {
if (!this._poolVar || !this._poolVar.enabled) return;
this._poolVar.enabled = false;
Object.keys(this._pool).forEach((tier) => {
Object.keys(this._pool[tier]).forEach((localCode) => {
this._pool[tier][localCode].session.destroy(null, "Pool Disabled");
this._pool[tier][localCode].session = null;
this._pool[tier][localCode].cache = null;
delete this._pool[tier][localCode];
});
});
this.recordMetrics();
}
terminate(reason) {
this.disablePool();
clearInterval(this._logInterval);
clearInterval(this._keepAliveInterval);
if (this._monitor_session) {
this._monitor_session.destroy(null, reason);
this._monitor_session = null;
}
Object.keys(this._online).forEach((remoteCode) => {
this.destroy(remoteCode, reason);
});
}
restart() {
this.startPool();
this._setup();
}
recordMetrics() {
metrics.gauge("oo.online_sessions", Object.keys(this._online).length);
Object.keys(this._pool).forEach((tier) => {
metrics.gauge(`oo.pool_sessions.${tier}`, Object.keys(this._pool[tier]).length);
});
}
}
module.exports = SessionManager;
================================================
FILE: back-octave/Makefile
================================================
# Copyright © 2018, Octave Online LLC
#
# This file is part of Octave Online Server.
#
# Octave Online Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Octave Online Server is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Octave Online Server. If not, see
# .
CC = gcc
CFLAGS = -Wall -pthread -I/usr/local/include -L/usr/local/lib
DEPS =
OBJ = host.o
LIBS = -luv -ljson-c
EXE = octave-host
%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)
$(EXE): $(OBJ)
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
install: $(EXE)
cp $(EXE) /usr/local/bin
clean:
rm $(OBJ) $(EXE)
run: $(EXE)
./$(EXE)
================================================
FILE: back-octave/README.md
================================================
Octave Online Server: GNU Octave Utilities
==========================================
This directory contains machinery for talking to the GNU Octave process.
See [containers/README.md](../containers/README.md) for instructions on how to build the custom GNU Octave for Octave Online Server.
The *oo-changesets* directory contains patches against GNU Octave to add features required for Octave Online. The primary feature added is a new flag `--json-sock`, which uses a UNIX Socket for passing messages back and forth between the Octave process and the outside world.
The file *host.c* is a thin GNU Octave wrapper process that creates the UNIX Socket for talking to GNU Octave. It reads messages from STDIN and marshals them into the UNIX Socket, and when it receives a message from the socket, it prints the message to STDOUT.
The *Makefile* is used for building *host.c* into an executable.
The file *octaverc.m* is the default site-wide octaverc file for Octave Online Server. It is installed either into the Docker instance or into the current local server via the *install-site-m* make target in the top-level directory.
================================================
FILE: back-octave/host.c
================================================
/*
* Copyright © 2018, Octave Online LLC
*
* This file is part of Octave Online Server.
*
* Octave Online Server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Octave Online Server is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Octave Online Server. If not, see
* .
*/
#include
#include
#include
#include
#include
#include
#include
// MACROS, CONSTANTS, GLOBALS, AND TYPEDEFS
int r;
#define CATCH(expr){ \
r = expr; \
if(r){ \
fprintf(stderr, "@ %s (%d): ", __FILE__, __LINE__); \
fprintf(stderr, "%d: %s\n", r, uv_strerror(r)); \
fflush(stderr); \
return r; \
} \
}
#define LOG(...){ \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
fflush(stderr); \
}
#define TMP_DIR_STRLEN 14
#define TMP_DIR_FORMAT "/tmp/octXXXXXX"
#define TMP_COM_STRLEN 19
#define TMP_COM_FORMAT "/tmp/octXXXXXX/sock"
uv_loop_t* loop = NULL;
uv_tcp_t* sock_client = NULL;
uv_process_t child_req;
uv_process_options_t options;
char* tmp_path;
char* com_path;
uv_pipe_t worker_com_p;
uv_pipe_t worker_out_p;
uv_pipe_t worker_err_p;
uv_pipe_t host_in_p;
uv_pipe_t host_out_p;
uv_signal_t sigint_s;
uv_signal_t sigterm_s;
uv_signal_t sighup_s;
typedef struct {
uv_write_t req;
uv_buf_t buf;
} write_req_t;
enum STD_STREAM {
STD_STREAM_SOCKET_OUT,
STD_STREAM_SOCKET_ERR,
STD_STREAM_HOST_IN,
STD_STREAM_SOCKET
};
// UTILITY CALLBACKS
void cb_walk(uv_handle_t* handle, void* arg) {
uv_close(handle, NULL);
}
void cleanup() {
// Close all remaining file descriptors
uv_walk(loop, cb_walk, NULL);
// End the loop
uv_loop_close(loop);
}
void cb_cleanup_write_req(uv_write_t *req, int status) {
write_req_t *wr = (write_req_t*) req;
free(wr->buf.base);
free(wr);
}
void cb_alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
*buf = uv_buf_init((char*) malloc(suggested_size), suggested_size);
}
void cb_sigfwd(uv_signal_t *handle, int signum) {
LOG("Forwarding signal %d", signum);
kill(child_req.pid, signum);
}
void cb_exit(uv_process_t* req, int64_t exit_status, int term_signal) {
LOG("Process exited with status %" PRId64 ", signal %d", exit_status, term_signal);
cleanup();
}
// UTILITY FUNCTIONS
// write_to_socket and write_to_stdout copy the memory so that other parts of the program cannot asynchronously mess with the writing process.
void write_to_socket(const char* str, size_t len) {
write_req_t* req = malloc(sizeof(write_req_t));
req->buf = uv_buf_init((char*) malloc(len), len);
memcpy(req->buf.base, str, len);
uv_write((uv_write_t*) req, (uv_stream_t*) sock_client, &req->buf, 1, cb_cleanup_write_req);
}
void write_to_stdout(const char* str, size_t len) {
write_req_t* req = malloc(sizeof(write_req_t));
req->buf = uv_buf_init((char*) malloc(len), len);
memcpy(req->buf.base, str, len);
uv_write((uv_write_t*) req, (uv_stream_t*) &host_out_p, &req->buf, 1, cb_cleanup_write_req);
}
void print_json_msg_str(const char* name, const char* str, size_t len) {
// Make the object
json_object* nameobj = json_object_new_string(name);
json_object* strobj = json_object_new_string_len(str, len);
json_object* obj = json_object_new_array();
json_object_array_add(obj, nameobj);
json_object_array_add(obj, strobj);
// Make the string and print it
const char* jstr = json_object_to_json_string(obj);
write_to_stdout(jstr, strlen(jstr));
// Relese memory
// jstr is automatically released along with obj: https://github.com/json-c/json-c/issues/83
json_object_put(obj);
}
// Process all messages received from the streams: child out, child err, stdin, and socket.
// - "nread" is the number of bytes in the output.
// - "buf" is the buffer, which was originally created by "alloc_buffer".
// It may be longer than "nread".
void process_std_stream(enum STD_STREAM type, uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
// Is the stream closed?
if (nread < 0) {
if (nread == UV_EOF) {
uv_close((uv_handle_t*) stream, NULL);
}
}
// What to do with the data?
else if (nread > 0) {
switch (type) {
case STD_STREAM_SOCKET_OUT:
print_json_msg_str("out", buf->base, nread);
break;
case STD_STREAM_SOCKET_ERR:
print_json_msg_str("err", buf->base, nread);
break;
case STD_STREAM_HOST_IN:
write_to_socket(buf->base, nread);
break;
case STD_STREAM_SOCKET:
write_to_stdout(buf->base, nread);
break;
default:
break;
}
}
// Free memory (corresponding malloc: cb_alloc_buffer)
if (buf->base) free(buf->base);
}
// MAIN CALLBACKS
void cb_stdmsg(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
process_std_stream(STD_STREAM_SOCKET, stream, nread, buf);
}
void cb_stdout(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
process_std_stream(STD_STREAM_SOCKET_OUT, stream, nread, buf);
}
void cb_stderr(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
process_std_stream(STD_STREAM_SOCKET_ERR, stream, nread, buf);
}
void cb_stdin(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
process_std_stream(STD_STREAM_HOST_IN, stream, nread, buf);
}
void cb_connect(uv_stream_t* comm, int status) {
if (status == -1) return;
LOG("Connection received");
// Ignore connection if we already have one
if (sock_client != NULL) return;
sock_client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
uv_tcp_init(loop, sock_client);
if (uv_accept(comm, (uv_stream_t*) sock_client) == 0) {
uv_read_start((uv_stream_t*) sock_client, cb_alloc_buffer, cb_stdmsg);
}
else {
uv_close((uv_handle_t*) sock_client, NULL);
sock_client = NULL;
}
}
// MAIN FUNCTION
int main(int argc, char* argv[]) {
signal(SIGPIPE, SIG_IGN);
loop = uv_default_loop();
tmp_path = malloc(TMP_DIR_STRLEN); strcpy(tmp_path, TMP_DIR_FORMAT);
com_path = malloc(TMP_COM_STRLEN); strcpy(com_path, TMP_COM_FORMAT);
mkdtemp(tmp_path);
memcpy(com_path, tmp_path, TMP_DIR_STRLEN);
LOG("tmpdir: %s", com_path);
// FIXME: Delete the temp dir before the process exits.
CATCH(uv_pipe_init(loop, &worker_com_p, 0));
CATCH(uv_pipe_init(loop, &worker_out_p, 0));
CATCH(uv_pipe_init(loop, &worker_err_p, 0));
CATCH(uv_pipe_init(loop, &host_in_p, 0));
CATCH(uv_pipe_init(loop, &host_out_p, 0));
CATCH(uv_pipe_open(&host_in_p, 0));
CATCH(uv_pipe_open(&host_out_p, 1));
CATCH(uv_signal_init(loop, &sigint_s));
CATCH(uv_signal_init(loop, &sigterm_s));
CATCH(uv_signal_init(loop, &sighup_s));
// Let the command line argument translate into "--json-max-len"
char* args[9];
args[0] = "octave";
args[1] = "--json-sock";
args[2] = com_path;
args[3] = "--interactive";
args[4] = "--quiet";
args[5] = "--no-window-system";
args[6] = "--json-max-len";
if (argc > 1) {
args[7] = argv[1];
} else {
args[7] = "0";
}
args[8] = NULL;
options.exit_cb = cb_exit;
options.file = "/usr/local/bin/octave";
// options.file = "/vagrant/octave/octave/build-no-docs/run-octave";
options.args = args;
options.stdio_count = 3;
uv_stdio_container_t child_stdio[3];
child_stdio[0].flags = UV_IGNORE;
child_stdio[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE;
child_stdio[1].data.stream = (uv_stream_t*) &worker_out_p;
child_stdio[2].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE;
child_stdio[2].data.stream = (uv_stream_t*) &worker_err_p;
options.stdio = child_stdio;
CATCH(uv_spawn(loop, &child_req, &options));
CATCH(uv_pipe_bind(&worker_com_p, com_path));
CATCH(uv_listen((uv_stream_t*) &worker_com_p, 128, cb_connect));
CATCH(uv_read_start((uv_stream_t*) &worker_out_p, cb_alloc_buffer, cb_stdout));
CATCH(uv_read_start((uv_stream_t*) &worker_err_p, cb_alloc_buffer, cb_stderr));
CATCH(uv_read_start((uv_stream_t*) &host_in_p, cb_alloc_buffer, cb_stdin));
CATCH(uv_signal_start(&sigint_s, cb_sigfwd, SIGINT));
CATCH(uv_signal_start(&sigterm_s, cb_sigfwd, SIGTERM));
CATCH(uv_signal_start(&sighup_s, cb_sigfwd, SIGHUP));
LOG("Launched process with ID %d", child_req.pid);
free(tmp_path);
free(com_path);
return uv_run(loop, UV_RUN_DEFAULT);
}
================================================
FILE: back-octave/oo-changesets/000-README.md
================================================
Patch files from `001` until `100` are based on commit `323e92c4589f` in the GNU Octave mercurial repository, which is in the stable branch of version *4.1rc*.
================================================
FILE: back-octave/oo-changesets/001-d38b7c534496.hg.txt
================================================
# HG changeset patch
# User Shane F. Carr
# Date 1453104462 21600
# Mon Jan 18 02:07:42 2016 -0600
# Branch oo
# Node ID d38b7c534496ca887f197901cf4fea75788ea579
# Parent 323e92c4589f7a47d67033e689e61dfa510cf911
Adding octave link binding "request_input". When enabled, the binding will be called whenever the user is prompted for input, and it should return a string corresponding to what the user entered in response. It should be enabled on an instance of octave_link by setting the private field _request_input_enabled=true.
diff -r 323e92c4589f -r d38b7c534496 libinterp/corefcn/input.cc
--- a/libinterp/corefcn/input.cc Sat Jan 16 18:14:35 2016 -0800
+++ b/libinterp/corefcn/input.cc Mon Jan 18 02:07:42 2016 -0600
@@ -184,7 +184,11 @@
eof = false;
- std::string retval = command_editor::readline (s, eof);
+ std::string retval;
+ if (octave_link::request_input_enabled ())
+ retval = octave_link::request_input (s);
+ else
+ retval = command_editor::readline (s, eof);
if (! eof && retval.empty ())
retval = "\n";
diff -r 323e92c4589f -r d38b7c534496 libinterp/corefcn/octave-link.h
--- a/libinterp/corefcn/octave-link.h Sat Jan 16 18:14:35 2016 -0800
+++ b/libinterp/corefcn/octave-link.h Mon Jan 18 02:07:42 2016 -0600
@@ -276,6 +276,13 @@
instance->do_post_input_event ();
}
+ static std::string request_input (const std::string& prompt)
+ {
+ return request_input_enabled ()
+ ? instance->do_request_input (prompt)
+ : std::string ();
+ }
+
static void enter_debugger_event (const std::string& file, int line)
{
if (enabled ())
@@ -323,6 +330,11 @@
return instance_ok () ? instance->link_enabled : false;
}
+ static bool request_input_enabled (void)
+ {
+ return enabled () ? instance->_request_input_enabled : false;
+ }
+
static bool
show_preferences ()
{
@@ -396,6 +408,9 @@
void do_entered_readline_hook (void) { }
void do_finished_readline_hook (void) { }
+ bool _request_input_enabled;
+ virtual std::string do_request_input (const std::string&) = 0;
+
virtual bool do_confirm_shutdown (void) = 0;
virtual bool do_exit (int status) = 0;
================================================
FILE: back-octave/oo-changesets/002-d3de6023e846.hg.txt
================================================
# HG changeset patch
# User Shane F. Carr
# Date 1453119478 21600
# Mon Jan 18 06:17:58 2016 -0600
# Branch oo
# Node ID d3de6023e84666d9db08e00e3417d2601d05989e
# Parent d38b7c534496ca887f197901cf4fea75788ea579
Adding "show_static_plot" endpoint in octave link and synchronizing with GNUPlot when creating output files upon redraw plot commands.
diff -r d38b7c534496 -r d3de6023e846 libinterp/corefcn/octave-link.cc
--- a/libinterp/corefcn/octave-link.cc Mon Jan 18 02:07:42 2016 -0600
+++ b/libinterp/corefcn/octave-link.cc Mon Jan 18 06:17:58 2016 -0600
@@ -448,5 +448,30 @@
return retval;
}
+DEFUN (__octave_link_plot_destination__, , ,
+ "-*- texinfo -*-\n\
+@deftypefn {} {} __octave_link_plot_destination__ ()\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+ return octave_value (octave_link::plot_destination ());
+}
+DEFUN (__octave_link_show_static_plot__, args, ,
+ "-*- texinfo -*-\n\
+@deftypefn {} {} __octave_link_show_static_plot__ (@var{term}, @var{content})\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+ if (args.length () != 2) {
+ octave_value retval; return retval; // v4.0
+ // return ovl (); // v4.1.0+
+ }
+ std::string term = args(0).string_value();
+ std::string content = args(1).string_value();
+ return octave_value (octave_link::show_static_plot (term, content));
+}
+
+
+
diff -r d38b7c534496 -r d3de6023e846 libinterp/corefcn/octave-link.h
--- a/libinterp/corefcn/octave-link.h Mon Jan 18 02:07:42 2016 -0600
+++ b/libinterp/corefcn/octave-link.h Mon Jan 18 06:17:58 2016 -0600
@@ -335,6 +335,29 @@
return enabled () ? instance->_request_input_enabled : false;
}
+ enum plot_destination_t {
+ TERMINAL_ONLY = 0,
+ STATIC_ONLY = 1,
+ TERMINAL_AND_STATIC = 2
+ };
+
+ static plot_destination_t plot_destination (void)
+ {
+ return enabled () ? instance->_plot_destination : TERMINAL_ONLY;
+ }
+
+ static bool
+ show_static_plot (const std::string& term, const std::string& content)
+ {
+ if (enabled ())
+ {
+ instance->do_show_static_plot (term, content);
+ return true;
+ }
+ else
+ return false;
+ }
+
static bool
show_preferences ()
{
@@ -488,7 +511,11 @@
virtual void do_show_preferences (void) = 0;
- virtual void do_show_doc (const std::string &file) = 0;
+ virtual void do_show_doc (const std::string& file) = 0;
+
+ plot_destination_t _plot_destination;
+ virtual void do_show_static_plot (const std::string& term,
+ const std::string& content) = 0;
};
#endif // OCTAVELINK_H
diff -r d38b7c534496 -r d3de6023e846 scripts/plot/util/__gnuplot_drawnow__.m
--- a/scripts/plot/util/__gnuplot_drawnow__.m Mon Jan 18 02:07:42 2016 -0600
+++ b/scripts/plot/util/__gnuplot_drawnow__.m Mon Jan 18 06:17:58 2016 -0600
@@ -27,9 +27,75 @@
if (nargin < 1 || nargin > 5 || nargin == 2)
print_usage ();
+
+ elseif (nargin >= 3 && nargin <= 5)
+ ## Write the plot to the given file (e.g., via the "print" command)
+ __gnuplot_draw_to_file__ (h, term, file, mono, debug_file);
+
+ elseif (nargin == 1)
+ ## Plot to terminal and/or static (e.g., via the "plot" command)
+ plot_stream = get (h, "__plot_stream__");
+ if (isempty (plot_stream))
+ plot_stream = __gnuplot_open_stream__ (2, h);
+ new_stream = true;
+ else
+ new_stream = false;
+ endif
+ term = gnuplot_default_term (plot_stream);
+
+ ## There are a few options for how we can proceed.
+ ## In most cases, we will tell GNUPLOT to put the plot in its terminal.
+ ## If we have no display, we want to use the "dumb" terminal.
+ ## Octave Link may request that we send the plot as an event.
+ ## The latter two cases require plotting to a temp file.
+
+ should_plot_to_terminal = (
+ !strcmp (term, "dumb") && (
+ __octave_link_plot_destination__ () == 0 ||
+ __octave_link_plot_destination__ () == 2
+ )
+ );
+
+ if (should_plot_to_terminal)
+ enhanced = gnuplot_set_term (plot_stream(1), new_stream, h, term);
+ __go_draw_figure__ (h, plot_stream(1), enhanced, mono);
+ fflush (plot_stream(1));
+ endif
+
+ should_plot_to_temp_file = (
+ strcmp (term, "dumb") ||
+ __octave_link_plot_destination__ () == 1 ||
+ __octave_link_plot_destination__ () == 2
+ );
+
+ if (should_plot_to_temp_file)
+ tmp_file = tempname ();
+ __gnuplot_draw_to_file__ (h, term, tmp_file);
+ pause (1);
+
+ ## Read the temp file into memory and then delete it
+ fid = fopen (tmp_file, 'r');
+ [a, count] = fscanf (fid, '%c', Inf);
+ fclose (fid);
+ unlink (tmp_file);
+
+ ## What to do with the plot data?
+ if (count > 0)
+ if (a(1) == 12)
+ a = a(2:end); # avoid ^L at the beginning
+ endif
+ if strcmp (term, "dumb")
+ puts (a);
+ else
+ __octave_link_show_static_plot__ (term, a);
+ endif
+ endif
+ endif
+
endif
+endfunction
- if (nargin >= 3 && nargin <= 5)
+function __gnuplot_draw_to_file__ (h, term, file, mono = false, debug_file)
## Produce various output formats, or redirect gnuplot stream to a
## debug file.
plot_stream = [];
@@ -65,45 +131,6 @@
fclose (fid);
endif
end_unwind_protect
- else # nargin == 1
- ## Graphics terminal for display.
- plot_stream = get (h, "__plot_stream__");
- if (isempty (plot_stream))
- plot_stream = __gnuplot_open_stream__ (2, h);
- new_stream = true;
- else
- new_stream = false;
- endif
- term = gnuplot_default_term (plot_stream);
- if (strcmp (term, "dumb"))
- ## popen2 eats stdout of gnuplot, use temporary file instead
- dumb_tmp_file = tempname ();
- enhanced = gnuplot_set_term (plot_stream(1), new_stream, h,
- term, dumb_tmp_file);
- else
- enhanced = gnuplot_set_term (plot_stream(1), new_stream, h, term);
- endif
- __go_draw_figure__ (h, plot_stream(1), enhanced, mono);
- fflush (plot_stream(1));
- if (strcmp (term, "dumb"))
- fid = -1;
- while (fid < 0)
- pause (0.1);
- fid = fopen (dumb_tmp_file, 'r');
- endwhile
- ## reprint the plot on screen
- [a, count] = fscanf (fid, '%c', Inf);
- fclose (fid);
- if (count > 0)
- if (a(1) == 12)
- a = a(2:end); # avoid ^L at the beginning
- endif
- puts (a);
- endif
- unlink (dumb_tmp_file);
- endif
- endif
-
endfunction
function enhanced = gnuplot_set_term (plot_stream, new_stream, h, term, file)
================================================
FILE: back-octave/oo-changesets/003-4d28376c34a8.hg.txt
================================================
# HG changeset patch
# User Shane F. Carr
# Date 1453120386 21600
# Mon Jan 18 06:33:06 2016 -0600
# Branch oo
# Node ID 4d28376c34a877ba9eb5aefb84282c5bdf72a277
# Parent d3de6023e84666d9db08e00e3417d2601d05989e
Adding octave link endpoint clear_screen (for the "clc" command).
diff -r d3de6023e846 -r 4d28376c34a8 libgui/src/octave-qt-link.cc
--- a/libgui/src/octave-qt-link.cc Mon Jan 18 06:17:58 2016 -0600
+++ b/libgui/src/octave-qt-link.cc Mon Jan 18 06:33:06 2016 -0600
@@ -509,6 +509,11 @@
}
void
+octave_qt_link::do_clear_screen (void)
+{
+}
+
+void
octave_qt_link::do_pre_input_event (void)
{
}
diff -r d3de6023e846 -r 4d28376c34a8 libgui/src/octave-qt-link.h
--- a/libgui/src/octave-qt-link.h Mon Jan 18 06:17:58 2016 -0600
+++ b/libgui/src/octave-qt-link.h Mon Jan 18 06:33:06 2016 -0600
@@ -117,6 +117,8 @@
void do_append_history (const std::string& hist_entry);
void do_clear_history (void);
+ void do_clear_screen (void);
+
void do_pre_input_event (void);
void do_post_input_event (void);
diff -r d3de6023e846 -r 4d28376c34a8 libinterp/corefcn/octave-link.h
--- a/libinterp/corefcn/octave-link.h Mon Jan 18 06:17:58 2016 -0600
+++ b/libinterp/corefcn/octave-link.h Mon Jan 18 06:33:06 2016 -0600
@@ -264,6 +264,12 @@
instance->do_clear_history ();
}
+ static void clear_screen (void)
+ {
+ if (enabled ())
+ instance->do_clear_screen ();
+ }
+
static void pre_input_event (void)
{
if (enabled ())
@@ -492,6 +498,8 @@
virtual void do_append_history (const std::string& hist_entry) = 0;
virtual void do_clear_history (void) = 0;
+ virtual void do_clear_screen (void) = 0;
+
virtual void do_pre_input_event (void) = 0;
virtual void do_post_input_event (void) = 0;
diff -r d3de6023e846 -r 4d28376c34a8 libinterp/corefcn/sysdep.cc
--- a/libinterp/corefcn/sysdep.cc Mon Jan 18 06:17:58 2016 -0600
+++ b/libinterp/corefcn/sysdep.cc Mon Jan 18 06:33:06 2016 -0600
@@ -75,6 +75,7 @@
#include "error.h"
#include "input.h"
#include "oct-obj.h"
+#include "octave-link.h"
#include "ov.h"
#include "pager.h"
#include "parse.h"
@@ -596,6 +597,8 @@
{
bool skip_redisplay = true;
+ octave_link::clear_screen ();
+
command_editor::clear_screen (skip_redisplay);
return octave_value_list ();
================================================
FILE: back-octave/oo-changesets/004-6ff3e34eea77.hg.txt
================================================
# HG changeset patch
# User Shane F. Carr
# Date 1453120461 21600
# Mon Jan 18 06:34:21 2016 -0600
# Branch oo
# Node ID 6ff3e34eea77bae35e07007cbd7a1a17e7fedacc
# Parent 4d28376c34a877ba9eb5aefb84282c5bdf72a277
Adding support for condition variables to octave_mutex.
diff -r 4d28376c34a8 -r 6ff3e34eea77 liboctave/util/oct-mutex.cc
--- a/liboctave/util/oct-mutex.cc Mon Jan 18 06:33:06 2016 -0600
+++ b/liboctave/util/oct-mutex.cc Mon Jan 18 06:34:21 2016 -0600
@@ -53,6 +53,18 @@
return false;
}
+void
+octave_base_mutex::cond_wait (void)
+{
+ (*current_liboctave_error_handler) ("mutex not supported on this platform");
+}
+
+void
+octave_base_mutex::cond_signal (void)
+{
+ (*current_liboctave_error_handler) ("mutex not supported on this platform");
+}
+
#if defined (__WIN32__) && ! defined (__CYGWIN__)
class
@@ -63,11 +75,13 @@
: octave_base_mutex ()
{
InitializeCriticalSection (&cs);
+ InitializeConditionVariable (&cv);
}
~octave_w32_mutex (void)
{
DeleteCriticalSection (&cs);
+ // no need to delete cv: http://stackoverflow.com/a/28981408/1407170
}
void lock (void)
@@ -85,8 +99,21 @@
return (TryEnterCriticalSection (&cs) != 0);
}
+ void cond_wait (void)
+ {
+ SleepConditionVariableCS (&cv, &cs, INFINITE);
+ }
+
+ void cond_signal (void)
+ {
+ WakeConditionVariable (&cv);
+ }
+
+ void
+
private:
CRITICAL_SECTION cs;
+ CONDITION_VARIABLE cv;
};
static DWORD octave_thread_id = 0;
@@ -118,11 +145,18 @@
pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init (&pm, &attr);
pthread_mutexattr_destroy (&attr);
+
+ pthread_condattr_t condattr;
+
+ pthread_condattr_init (&condattr);
+ pthread_cond_init (&condv, &condattr);
+ pthread_condattr_destroy (&condattr);
}
~octave_pthread_mutex (void)
{
pthread_mutex_destroy (&pm);
+ pthread_cond_destroy (&condv);
}
void lock (void)
@@ -140,8 +174,20 @@
return (pthread_mutex_trylock (&pm) == 0);
}
+ void cond_wait (void)
+ {
+ pthread_cond_wait (&condv, &pm);
+ }
+
+ void cond_signal (void)
+ {
+ pthread_cond_signal (&condv);
+ }
+
private:
pthread_mutex_t pm;
+ pthread_cond_t condv;
+
};
static pthread_t octave_thread_id = 0;
diff -r 4d28376c34a8 -r 6ff3e34eea77 liboctave/util/oct-mutex.h
--- a/liboctave/util/oct-mutex.h Mon Jan 18 06:33:06 2016 -0600
+++ b/liboctave/util/oct-mutex.h Mon Jan 18 06:34:21 2016 -0600
@@ -43,6 +43,10 @@
virtual bool try_lock (void);
+ virtual void cond_wait (void);
+
+ virtual void cond_signal (void);
+
private:
octave_refcount count;
};
@@ -95,6 +99,16 @@
return rep->try_lock ();
}
+ void cond_wait (void)
+ {
+ rep->cond_wait ();
+ }
+
+ void cond_signal (void)
+ {
+ rep->cond_signal ();
+ }
+
protected:
octave_base_mutex *rep;
};
================================================
FILE: back-octave/oo-changesets/005-9e73fe0d92d5.hg.txt
================================================
# HG changeset patch
# User Shane F. Carr
# Date 1453121851 21600
# Mon Jan 18 06:57:31 2016 -0600
# Branch oo
# Node ID 9e73fe0d92d5817002f67034983af5b557f874be
# Parent 6ff3e34eea77bae35e07007cbd7a1a17e7fedacc
Changing definition of "isguirunning()" to "octave_link::enabled()". This enables triggering octave link endpoints by implementations of octave link other than the GUI.
diff -r 6ff3e34eea77 -r 9e73fe0d92d5 libinterp/octave.cc
--- a/libinterp/octave.cc Mon Jan 18 06:34:21 2016 -0600
+++ b/libinterp/octave.cc Mon Jan 18 06:57:31 2016 -0600
@@ -65,6 +65,7 @@
#include "oct-map.h"
#include "oct-mutex.h"
#include "oct-obj.h"
+#include "octave-link.h"
#include "ops.h"
#include "options-usage.h"
#include "ov.h"
@@ -989,7 +990,7 @@
octave_value retval;
if (args.length () == 0)
- retval = start_gui;
+ retval = octave_link::enabled ();
else
print_usage ();
================================================
FILE: back-octave/oo-changesets/006-15d21ceec728.hg.txt
================================================
# HG changeset patch
# User Shane F. Carr
# Date 1453127653 21600
# Mon Jan 18 08:34:13 2016 -0600
# Branch oo
# Node ID 15d21ceec7282b94db2d86503127d03730d5c316
# Parent 9e73fe0d92d5817002f67034983af5b557f874be
Adding a "--json-sock" command line option. With this option, Octave will publish all octave link messages as JSON objects to the specified UNIX domain socket.
diff -r 9e73fe0d92d5 -r 15d21ceec728 libinterp/corefcn/json-main.cc
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/libinterp/corefcn/json-main.cc Mon Jan 18 08:34:13 2016 -0600
@@ -0,0 +1,79 @@
+#ifdef HAVE_CONFIG_H
+#include
+#endif
+
+#include "json-main.h"
+
+#include
+#include
+#include
+#include
+
+
+// Analog of main-window.cc
+// TODO: Think more about concurrency and null pointer exceptions
+
+void* run_loop_pthread(void* arg) {
+ json_main* _json_main = static_cast(arg);
+ _json_main->run_loop();
+ return NULL;
+}
+
+void json_object_cb(std::string name, JSON_OBJECT_T jobj, void* arg) {
+ json_main* _json_main = static_cast(arg);
+ _json_main->process_json_object(name, jobj);
+}
+
+json_main::json_main(const std::string& json_sock_path)
+ : _json_sock_path (json_sock_path),
+ _loop_thread_active (false),
+ _octave_json_link (this)
+{
+ // Enable octave_json_link instance
+ octave_link::connect_link(&_octave_json_link);
+
+ // Open UNIX socket file descriptor
+ sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
+ struct sockaddr_un addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.sun_family = AF_UNIX;
+ memcpy(&addr.sun_path, _json_sock_path.c_str(), sizeof(addr.sun_path)-1);
+ connect(
+ sockfd,
+ reinterpret_cast(&addr),
+ sizeof(addr));
+}
+
+json_main::~json_main(void) {
+ close(sockfd);
+
+ // TODO: Stop the _loop_thread
+}
+
+void json_main::publish_message(const std::string& name, JSON_OBJECT_T jobj) {
+ std::string jstr = json_util::to_message(name, jobj);
+ send(sockfd, jstr.c_str(), jstr.length(), 0);
+}
+
+void json_main::run_loop_on_new_thread(void) {
+ if (_loop_thread_active)
+ perror("won't run JSON socket loop multiple times");
+ _loop_thread_active = true;
+
+ pthread_create(
+ &_loop_thread,
+ NULL,
+ run_loop_pthread,
+ static_cast(this));
+}
+
+void json_main::run_loop(void) {
+ json_util::read_stream(
+ sockfd,
+ json_object_cb,
+ static_cast(this));
+}
+
+void json_main::process_json_object(std::string name, JSON_OBJECT_T jobj) {
+ _octave_json_link.receive_message(name, jobj);
+}
diff -r 9e73fe0d92d5 -r 15d21ceec728 libinterp/corefcn/json-main.h
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/libinterp/corefcn/json-main.h Mon Jan 18 08:34:13 2016 -0600
@@ -0,0 +1,29 @@
+#ifndef json_main_h
+#define json_main_h
+
+#include
+#include
+#include
+
+#include "octave-json-link.h"
+#include "json-util.h"
+
+class json_main {
+public:
+ json_main(const std::string& json_sock_path);
+ ~json_main(void);
+
+ void publish_message(const std::string& name, JSON_OBJECT_T jobj);
+ void run_loop_on_new_thread(void);
+ void run_loop(void);
+ void process_json_object(std::string name, JSON_OBJECT_T jobj);
+
+private:
+ std::string _json_sock_path;
+ int sockfd;
+ bool _loop_thread_active;
+ pthread_t _loop_thread;
+ octave_json_link _octave_json_link;
+};
+
+#endif
diff -r 9e73fe0d92d5 -r 15d21ceec728 libinterp/corefcn/json-util.cc
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/libinterp/corefcn/json-util.cc Mon Jan 18 08:34:13 2016 -0600
@@ -0,0 +1,226 @@
+#ifdef HAVE_CONFIG_H
+#include
+#endif
+
+#include
+#include
+#include
+#include
+#include
+
+#include "str-vec.h"
+
+#include "json-util.h"
+
+JSON_OBJECT_T json_util::from_string(const std::string& str) {
+ return json_object_new_string(str.c_str());
+}
+
+JSON_OBJECT_T json_util::from_int(int i) {
+ return json_object_new_int(i);
+}
+
+JSON_OBJECT_T json_util::from_float(float flt) {
+ return json_object_new_double(flt);
+}
+
+JSON_OBJECT_T json_util::from_boolean(bool b) {
+ return json_object_new_boolean(b);
+}
+
+JSON_OBJECT_T json_util::empty() {
+ return json_object_new_object();
+}
+
+template
+JSON_OBJECT_T json_object_from_list(const std::list& list, JSON_OBJECT_T (*convert)(T)) {
+ JSON_OBJECT_T jobj = json_object_new_array();
+ for (
+ typename std::list::const_iterator it = list.begin();
+ it != list.end();
+ ++it
+ ){
+ json_object_array_add(jobj, convert(*it));
+ }
+ return jobj;
+}
+
+JSON_OBJECT_T json_util::from_string_list(const std::list& list) {
+ return json_object_from_list(list, json_util::from_value_string);
+}
+
+JSON_OBJECT_T json_util::from_string_vector(const string_vector& vect) {
+ // TODO: Make sure this function does what it's supposed to do
+ std::list list;
+ for (int i = 0; i < vect.numel(); ++i) {
+ list.push_back(vect[i]);
+ }
+
+ return json_object_from_list(list, json_util::from_value_string);
+}
+
+JSON_OBJECT_T json_util::from_int_list(const std::list& list) {
+ return json_object_from_list(list, json_util::from_int);
+}
+
+JSON_OBJECT_T json_util::from_float_list(const std::list& list) {
+ return json_object_from_list(list, json_util::from_float);
+}
+
+JSON_OBJECT_T json_util::from_workspace_list(const std::list& list) {
+ return json_object_from_list(list, json_util::from_workspace_element);
+}
+
+JSON_OBJECT_T json_util::from_filter_list(const octave_link::filter_list& list) {
+ return json_object_from_list(list, json_util::from_pair);
+}
+
+JSON_OBJECT_T json_util::from_value_string(const std::string str) {
+ return json_util::from_string(str);
+}
+
+JSON_OBJECT_T json_util::from_workspace_element(workspace_element element) {
+ JSON_MAP_T m;
+ m["scope"] = json_util::from_int(element.scope());
+ m["symbol"] = json_util::from_string(element.symbol());
+ m["class_name"] = json_util::from_string(element.class_name());
+ m["dimension"] = json_util::from_string(element.dimension());
+ m["value"] = json_util::from_string(element.value());
+ m["complex_flag"] = json_util::from_boolean(element.complex_flag());
+ return json_util::from_map(m);
+}
+
+JSON_OBJECT_T json_util::from_pair(std::pair pair) {
+ JSON_OBJECT_T jobj = json_object_new_array();
+ json_object_array_add(jobj, json_object_new_string(pair.first.c_str()));
+ json_object_array_add(jobj, json_object_new_string(pair.second.c_str()));
+ return jobj;
+}
+
+JSON_OBJECT_T json_util::from_map(JSON_MAP_T m) {
+ JSON_OBJECT_T jobj = json_object_new_object();
+ for(
+ std::map::iterator it = m.begin();
+ it != m.end();
+ ++it
+ ){
+ json_object_object_add(jobj, it->first.c_str(), it->second);
+ }
+ return jobj;
+}
+
+std::string json_util::to_message(const std::string& name, JSON_OBJECT_T jobj) {
+ JSON_OBJECT_T jmsg = json_object_new_array();
+ json_object_array_add(jmsg, json_util::from_string(name));
+ json_object_array_add(jmsg, jobj);
+ std::string str (json_object_to_json_string(jmsg));
+ return str;
+}
+
+std::string json_util::to_string(JSON_OBJECT_T jobj) {
+ return std::string(json_object_get_string(jobj));
+}
+
+template
+std::list json_object_to_list(JSON_OBJECT_T jobj, T (*convert)(JSON_OBJECT_T)) {
+ std::list ret;
+
+ struct array_list* arr = json_object_get_array(jobj);
+ if (arr == NULL)
+ return ret;
+
+ for (int i = 0; i < array_list_length(arr); ++i) {
+ JSON_OBJECT_T jsub = static_cast (array_list_get_idx(arr, i));
+ ret.push_back(convert(jsub));
+ }
+ return ret;
+}
+
+std::pair, int> json_util::to_int_list_int_pair(JSON_OBJECT_T jobj) {
+ std::pair, int> ret;
+
+ struct array_list* arr = json_object_get_array(jobj);
+ if (arr == NULL)
+ return ret;
+
+ JSON_OBJECT_T first = static_cast (array_list_get_idx(arr, 0));
+ JSON_OBJECT_T second = static_cast (array_list_get_idx(arr, 1));
+
+ ret.first = json_object_to_list(first, json_util::to_int);
+ ret.second = json_object_get_int(second);
+
+ return ret;
+}
+
+std::list json_util::to_string_list(JSON_OBJECT_T jobj) {
+ return json_object_to_list(jobj, json_util::to_string);
+}
+
+int json_util::to_int(JSON_OBJECT_T jobj) {
+ return json_object_get_int(jobj);
+}
+
+bool json_util::to_boolean(JSON_OBJECT_T jobj) {
+ return json_object_get_boolean(jobj);
+}
+
+void json_util::read_stream(int sockfd, void (*cb)(std::string, JSON_OBJECT_T, void*), void* arg) {
+
+ // Make some local variables
+ int BUF_LEN = 24;
+ char* buf = new char[BUF_LEN]; // buffer for socket read
+ int buf_len; // length of new bytes in the buffer
+ int buf_offset; // offset of the JSON parser in the buffer
+ JSON_OBJECT_T jobj; // pointer to parsed JSON object
+ json_tokener* tok = json_tokener_new(); // JSON tokenizer instance
+ enum json_tokener_error jerr; // status of JSON tokenizer
+
+ // Start the blocking I/O loop
+ while( (buf_len=recv(sockfd, buf, BUF_LEN, 0)) > 0) {
+ buf_offset = 0;
+ while(buf_offset < buf_len){
+ jobj = json_tokener_parse_ex(tok, buf + buf_offset, buf_len - buf_offset);
+ jerr = json_tokener_get_error(tok);
+ buf_offset += tok->char_offset;
+
+ // Do we need more material in order to make JSON?
+ if (jerr == json_tokener_continue) {
+ continue;
+ }
+
+ // Make a new tokenizer
+ json_tokener_free(tok);
+ tok = json_tokener_new();
+
+ // Did we encounter a malformed JSON object?
+ if (jerr != json_tokener_success) {
+ fprintf(stderr,
+ "JSON parse error: %s: '%.*s'\n",
+ json_tokener_error_desc(jerr),
+ 1,
+ buf + buf_offset);
+ fflush(stderr);
+ break;
+ }
+
+ // Our object is ready
+ process_message(jobj, cb, arg);
+ }
+ }
+
+ json_tokener_free(tok);
+ delete buf;
+}
+
+void json_util::process_message(JSON_OBJECT_T jobj, void (*cb)(std::string, JSON_OBJECT_T, void*), void* arg) {
+ if (!json_object_is_type(jobj, json_type_array))
+ return;
+ if (json_object_array_length(jobj) != 2)
+ return;
+
+ cb(
+ json_util::to_string(json_object_array_get_idx(jobj, 0)),
+ json_object_array_get_idx(jobj, 1),
+ arg
+ );
+}
diff -r 9e73fe0d92d5 -r 15d21ceec728 libinterp/corefcn/json-util.h
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/libinterp/corefcn/json-util.h Mon Jan 18 08:34:13 2016 -0600
@@ -0,0 +1,55 @@
+#ifndef json_util_h
+#define json_util_h
+
+#include
+#include