From 93e130021aa34c5d224b692845f01c2d77b6723c Mon Sep 17 00:00:00 2001 From: Miguel Barão Date: Sat, 13 Jul 2019 18:41:48 +0100 Subject: [PATCH] updates README.md. adds the --version option. shows instructions in the terminal for some failures in configuration. fix error with exception not detected when database not usable. --- BUGS.md | 3 ++- README.md | 180 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------------------------------------------------------------- aprendizations/learnapp.py | 13 +++++++++---- aprendizations/serve.py | 55 ++++++++++++++++++++++++++++++++++++++++++++----------- 4 files changed, 154 insertions(+), 97 deletions(-) diff --git a/BUGS.md b/BUGS.md index 05cfa53..4ce9b04 100644 --- a/BUGS.md +++ b/BUGS.md @@ -3,7 +3,7 @@ - quando termina topico devia apagar as perguntas todas (se falhar a gerar novo topico, aparecem perguntas do antigo) - apos clicar no botao responder, inactivar o input (importante quando o tempo de correcção é grande) -- devia mostrar timout para o aluno saber a razao. +- devia mostrar timeout para o aluno saber a razao. - permitir configuracao para escolher entre static files locais ou remotos - sqlalchemy.pool.impl.NullPool: Exception during reset or similar sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. @@ -40,6 +40,7 @@ sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in # FIXED +- add aprendizatons --version - se aluno abre dois tabs no browser, conseque navegar em simultaneo para perguntas diferentes. quando submete uma delas dá asneira. Tem de haver um campo hidden que tenha um céodigo único que indique qual a pergunta. do lado do servidor apnas há o codigo da pergunta corrente, se forem diferentes faz redirect para /. - nos topicos learn.yaml, qd falha acrescenta no fim. nao faz sentido. - não esta a fazer render correcto de tabelas nas opcoes checkbox. e.g. information-theory/source-coding-theory/block-codes diff --git a/README.md b/README.md index f723737..734e25d 100644 --- a/README.md +++ b/README.md @@ -1,56 +1,69 @@ # Getting Started +To complete the installation we will need to perform the following steps: -## Requirements +1. install python3.7, pip and npm +1. download aprendizations from the repository +1. install javascript libraries (with npm) +1. install aprendizations (with pip) +1. initialize database +1. generate SSL certificates +1. configure the firewall (optional) +1. try running `aprendizations demo.yaml` -This application requires python3.7+ and a few additional python packages. -It also uses npm (Node package management) to install javascript libraries. +These steps are explained next in detail. ### Install python3.7 with sqlite3 support and npm -This can be done using the system package management, downloaded from [http://www.python.org](), or compiled from sources. +Python can be installed either from the system package management or compiled from sources. -- Installing from the system package manager: +#### Installing from the system package manager ```sh -sudo port install python37 npm5 # MacOS +sudo apt install python3.7 npm # Linux (Ubuntu) sudo pkg install python37 py37-sqlite3 npm # FreeBSD -sudo apt install python3.7 npm # Linux +sudo port install python37 npm6 # MacOS ``` -- Installing from source: +#### Installing from source -Download from [http://www.python.org]() and +Make sure that the build tools and libraries are installed: ```sh -unxz Python-3.7.tar.xz -tar xvf Python-3.7.tar +# Ubuntu: +sudo apt install build-essential libssl-dev zlib1g-dev libncurses5-dev libncursesw5-dev libreadline-dev libsqlite3-dev libgdbm-dev libdb5.3-dev libbz2-dev libexpat1-dev liblzma-dev tk-dev libffi-dev +``` + +Download python from [http://www.python.org]() and + +```sh +tar xvfJ Python-3.7.tar.xz cd Python-3.7 -./configure --prefix=$HOME/.local/bin +./configure --prefix=$HOME/.local --enable-optimizations make && make install ``` -This will install python locally under `~/.local/bin`. Make sure to add it to your `PATH` (edit `~/.profile` in MacOS or FreeBSD). - +This will install python locally under `~/.local/bin`. Make sure to add it to your `PATH` in `~/.profile`. If `~/bin` is already in the path, you may just make a symbolic link `ln -s ~/.local/bin ~/bin`. ### Install pip +Python usually includes pip which is accessible through `python -m pip install something`, but it's also convenient to have the `pip` command installed. If the `pip` command is not yet installed, run one of these: ```sh -sudo apt install python3.7-pip # Ubuntu +sudo apt install python3.7-pip # Ubuntu 19.04+ +python3.7 -m pip install pip # Ubuntu 18.04 sudo pkg py37-pip # FreeBSD sudo port install py37-pip # MacOS -python3.7 -m ensurepip --user # otherwise ``` The latter will install `pip` in your user account under `~/.local/bin`. -In the end you should be able to run `pip3 --version` and -`python3 -c "import sqlite3"` without errors (sometimes `pip3` is `pip`, -`pip3.7` or `pip-3.7`). +In the end you should be able to run `pip --version` and +`python3 -c "import sqlite3"` without errors. +Sometimes the `pip` command is named `pip3`, +`pip3.7` or `pip-3.7`. -If you want to always install python modules on the user account (recommended), -edit the pip configuration file `~/.config/pip/pip.conf` (FreeBSD, Linux) or +Edit the configuration file `~/.config/pip/pip.conf` (FreeBSD, Linux) or `Library/Application Support/pip/pip.conf` (MacOS) and add the lines ```ini @@ -58,69 +71,72 @@ edit the pip configuration file `~/.config/pip/pip.conf` (FreeBSD, Linux) or user = yes ``` -### Install python packages and javascript libraries: +This will set pip to install modules in the user area (recommended). -Replace USER by your bitbucket username: +### Install aprendizations and dependencies: ```sh -cd somewhere git clone https://git.xdi.uevora.pt/mjsb/aprendizations.git cd aprendizations npm install # install javascript libraries pip install . # install aprendizations and dependencies ``` +Javascript libraries are initially installed in `aprendizations/node_modules` directory. +These libraries already have symbolic links from `aprendizations/aprendizations/static`. + Python packages are usually installed in: - `~/.local/lib/python3.7/site-packages/` in Linux/FreeBSD. - `~/Library/python/3.7/lib/python/site-packages/` in MacOS. -Javascript libraries are installed in `aprendizations/node_modules` directory. -This libraries have symbolic links from `aprendizations/aprendizations/static`. +When aprendizations is installed with pip, all the dependencies are also installed. The javascript libraries previously installed with npm are copied to the above directory and the cloned repository is no longer needed. -At this point aprendizations is installed in +At this point, aprendizations is installed in ```sh +~/.local/bin # Linux/FreeBSD ~/Library/Python/3.7/bin # MacOS -~/.local/bin # FreeBSD/Linux ``` -Make sure this directory is in your `$PATH`. +and can be run from the terminal: -The server can be run with the command `aprendizations` from the terminal. +```sh +aprendizations --version +aprendizations --help +``` ## Configuration ### Database -The user data is maintained in a sqlite3 database file. We first need to create -the database. -At the moment, the database should be located in the same directory as the main -configuration file (see below). As an example, do +User data is maintained in a sqlite3 database which has to be created manually using the command `initdb-aprendizations`. +The database file should be located in the same directory as the main +YAML configuration file. + +For example, to run the included demo do: ```sh cd demo # contains a small example initdb-aprendizations # show or initialize database initdb-aprendizations --admin # add admin user initdb-aprendizations inscricoes.csv # add students from CSV -initdb-aprendizations --add 1184 "Aladino da Silva" # add user +initdb-aprendizations --add 1184 "Aladino da Silva" # add new user initdb-aprendizations --update 1184 --pw alibaba # update password -initdb-aprendizations --help # for the available options +initdb-aprendizations --help # for available options ``` -The default password is equal to the user name used to login. +The default password is equal to the user name, if left undefined. ### SSL Certificates -We need certificates for https. Certificates can be self-signed or validated by -a trusted authority. +We need certificates for https. Certificates can be self-signed or validated by a trusted authority. Self-signed can be used locally for development and testing, but browsers will -complain. LetsEncrypt issues trusted and free certificates, but the server must -have a registered publicly accessible domain name. +complain. LetsEncrypt issues trusted and free certificates, but the server must have a registered publicly accessible domain name. -#### Selfsigned +#### Generating selfsigned certificates Generate a selfsigned certificate and place it in `~/.local/share/certs`. @@ -128,18 +144,20 @@ Generate a selfsigned certificate and place it in `~/.local/share/certs`. openssl req -x509 -newkey rsa:4096 -keyout privkey.pem -out cert.pem -days 365 -nodes ``` -#### LetsEncrypt +#### LetsEncrypt certificates + +Install the certbot from LetsEncrypt: ```sh -sudo pkg install py27-certbot # FreeBSD +sudo pkg install py36-certbot # FreeBSD +sudo apt install certbot # Linux Ubuntu ``` -Shutdown the firewall and any web server that might be running. Then run the script to generate the certificate: +To generate or renew the certificates, ports 80 and 443 have to be accessible. The firewall and webserver have to be stopped. ```sh -sudo service pf stop # disable pf firewall (FreeBSD) -sudo certbot certonly --standalone -d www.example.com -sudo service pf start # enable pf firewall +sudo certbot certonly --standalone -d www.example.com # first time +sudo certbot renew # renew ``` Certificates are saved under `/usr/local/etc/letsencrypt/live/www.example.com/`. Copy them to `~/.local/share/certs` and change permissions to be readable: @@ -150,47 +168,32 @@ sudo cp /usr/local/etc/letsencrypt/live/www.example.com/privkey.pem . chmod 400 cert.pem privkey.pem ``` -Renews can be done as follows: - -```sh -sudo service pf stop # shutdown firewall -sudo certbot renew -sudo service pf start # start firewall -``` - -and then copy the `cert.pem` and `privkey.pem` files to `~/.local/share/certs` directory. Change permissions and ownership as appropriate. +### Running the demo - -### Testing - -The application includes a small example in `demo/demo.yaml`. Run it with +The application includes a small example in `demo/demo.yaml` that can be used for initial testing. Run it with ```sh cd demo aprendizations demo.yaml ``` -and open a browser at [https://127.0.0.1:8443](https://127.0.0.1:8443). -If it everything looks good, -check at the correct address `https://www.example.com` (requires port forward -in the firewall). The option `--debug` provides more verbose logging and might -be useful during testing. The option `--check` generates all the questions once -before running the server to check for any obvious syntax error. - +Open the browser at [https://127.0.0.1:8443](https://127.0.0.1:8443). +If it everything looks good, check at the correct address +`https://www.example.com:8443`. +The option `--debug` provides more verbose logging and might +be useful during testing. ### Firewall configuration -Ports 80 and 443 are only usable by root. For security reasons it is better to -run the server as an unprivileged user on higher ports like 8080 for http and -8443 for https. For this, we can configure port forwarding in the firewall to -redirect incoming tcp traffic from 80 to 8080 and 443 to 8443. +Ports 80 and 443 are only usable by root. For security reasons the server runs as an unprivileged user on port 8443 for https. +To access the server in the default https port (443), port forwarding can be configured in the firewall. #### FreeBSD and pf Edit `/etc/pf.conf`: ```sh -ext_if="em0" # this should be the correct network interface +ext_if="em0" # change em0 to the correct network interface rdr on $ext_if proto tcp from any to any port 80 -> 127.0.0.1 port 8080 rdr on $ext_if proto tcp from any to any port 443 -> 127.0.0.1 port 8443 ``` @@ -212,6 +215,18 @@ pflog_logfile="/var/log/pflog" Reboot or `sudo service pf start`. +### Testing the system + +Make sure the following steps have been done: + +- installed python3.7, pip and npm +- git-cloned the aprendizations from the main repository +- installed javascript libraries with npm +- installed aprendizations with pip +- initialized database with at least 1 user +- generate and copy certificates to the appropriate place +- (optional) configure the firewall to do port forwarding +- run `aprendizations demo.yaml --check` ## Troubleshooting @@ -243,20 +258,23 @@ me:\ ## FAQ -- Which students did at least one topic? +Common database manipulations: ```sh -sqlite3 students.db "select distinct student_id from studenttopic" +initdb-aprendizations -u 12345 --pw alibaba # reset student password +initdb-aprendizations -a 12345 --pw alibaba # add new student ``` -- How many topics has each student done? +Common database queries: ```sh -sqlite3 students.db "select student_id, count(topic_id) from studenttopic group by student_id order by count(topic_id) desc" -``` +# Which students did at least one topic? +sqlite3 students.db "select distinct student_id from studenttopic" -- Which questions have more wrong answers? +# How many topics has each student done? +sqlite3 students.db "select student_id, count(topic_id) from studenttopic group by student_id order by count(topic_id) desc" -```sh +# Which questions have more wrong answers? sqlite3 students.db "select count(ref), ref from answers where grade<1.0 group by ref order by count(ref) desc" -``` \ No newline at end of file +``` + diff --git a/aprendizations/learnapp.py b/aprendizations/learnapp.py index d3abc98..5f012ce 100644 --- a/aprendizations/learnapp.py +++ b/aprendizations/learnapp.py @@ -29,6 +29,10 @@ class LearnException(Exception): pass +class DatabaseUnusableException(LearnException): + pass + + # ============================================================================ # LearnApp - application logic # ============================================================================ @@ -46,6 +50,7 @@ class LearnApp(object): except Exception: logger.error('DB rollback!!!') session.rollback() + raise finally: session.close() @@ -105,7 +110,7 @@ class LearnApp(object): logger.error(f'{errors:>6} errors found.') raise LearnException('Sanity checks') else: - logger.info('No errors found.') + logger.info(' 0 errors found.') # ------------------------------------------------------------------------ # login @@ -274,9 +279,9 @@ class LearnApp(object): n = s.query(Student).count() m = s.query(Topic).count() q = s.query(Answer).count() - except Exception as e: - logger.critical(f'Database "{db}" not usable!') - raise e + except Exception: + logger.error(f'Database "{db}" not usable!') + raise DatabaseUnusableException() else: logger.info(f'{n:6} students') logger.info(f'{m:6} topics') diff --git a/aprendizations/serve.py b/aprendizations/serve.py index 7e0601d..0dc1739 100644 --- a/aprendizations/serve.py +++ b/aprendizations/serve.py @@ -21,9 +21,9 @@ import tornado.web from tornado.escape import to_unicode # this project -from .learnapp import LearnApp +from .learnapp import LearnApp, DatabaseUnusableException from .tools import load_yaml, md_to_html -from . import APP_NAME +from . import APP_NAME, APP_VERSION # ---------------------------------------------------------------------------- @@ -380,39 +380,44 @@ def signal_handler(signal, frame): # ---------------------------------------------------------------------------- def parse_cmdline_arguments(): argparser = argparse.ArgumentParser( - description='Server for online learning. Enrolled students and topics ' + description='Server for online learning. Students and topics ' 'have to be previously configured. Please read the documentation ' 'included with this software before running the server.' ) argparser.add_argument( - 'conffile', type=str, nargs='+', + 'conffile', type=str, nargs='*', help='Topics configuration file in YAML format.' ) argparser.add_argument( '--prefix', type=str, default='.', - help='Path where the topic directories can be found, e.g. ~/topics' + help='Path where the topic directories can be found (default: .)' ) argparser.add_argument( '--port', type=int, default=8443, - help='Port to be used by the HTTPS server, e.g. 8443' + help='Port to be used by the HTTPS server (default: 8443)' ) argparser.add_argument( '--db', type=str, default='students.db', - help='SQLite3 database file, e.g. students.db' + help='SQLite3 database file (default: students.db)' ) argparser.add_argument( '--check', action='store_true', - help='Sanity check all questions' + help='Sanity check questions (can take awhile)' ) argparser.add_argument( '--debug', action='store_true', - help='Enable debug messages' + help='Enable debug mode' + ) + + argparser.add_argument( + '--version', action='store_true', + help='Print version information' ) return argparser.parse_args() @@ -434,8 +439,7 @@ def get_logger_config(debug=False): 'version': 1, 'formatters': { 'standard': { - 'format': '%(asctime)s %(name)-24s %(levelname)-10s - ' - '%(message)s', + 'format': '%(asctime)s | %(levelname)-10s | %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, @@ -472,6 +476,11 @@ def main(): # --- Commandline argument parsing arg = parse_cmdline_arguments() + if arg.version: + print(APP_NAME + ' ' + APP_VERSION) + print('Python ' + sys.version) + sys.exit(0) + # --- Setup logging logger_config = get_logger_config(arg.debug) logging.config.dictConfig(logger_config) @@ -489,6 +498,17 @@ def main(): try: learnapp = LearnApp(arg.conffile, prefix=arg.prefix, db=arg.db, check=arg.check) + except DatabaseUnusableException: + logging.critical('Failed to start application.') + print('--------------------------------------------------------------') + print('Could not find a usable database. Use one of the follwing ') + print('commands to initialize: ') + print(' ') + print(' initdb-aprendizations --admin # add admin ') + print(' initdb-aprendizations -a 86 "Max Smart" # add student ') + print(' initdb-aprendizations students.csv # add many students') + print('--------------------------------------------------------------') + sys.exit(1) except Exception: logging.critical('Failed to start application.') sys.exit(1) @@ -513,6 +533,19 @@ def main(): path.join(certs_dir, 'privkey.pem')) except FileNotFoundError: logging.critical(f'SSL certificates missing in {certs_dir}') + print('--------------------------------------------------------------') + print('Certificates should be issued by a certificate authority (CA),') + print('such as https://letsencrypt.org, and then copied to: ') + print(' ') + print(f' {certs_dir:<62}') + print(' ') + print('For testing purposes a selfsigned certificate can be generated') + print('locally by running: ') + print(' ') + print(' openssl req -x509 -newkey rsa:4096 -keyout privkey.pem \\ ') + print(' -out cert.pem -days 365 -nodes ') + print(' ') + print('--------------------------------------------------------------') sys.exit(1) # --- create webserver -- libgit2 0.21.2