-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdeploy.html
941 lines (787 loc) · 29.4 KB
/
deploy.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" class='height100'>
<head>
<meta charset="UTF-8">
<title>Server installation</title>
<!-- Google font:, also related: -->
<!-- Encode+Sans|Encode+Sans+Condensed|Encode+Sans+Semi+Condensed|Montserrat|Open+Sans+Condensed:300|Cabin+Condensed| -->
<link href="https://fonts.googleapis.com/css?family=Encode+Sans+Condensed|Lato&display=swap" rel="stylesheet">
<!-- -->
<!-- BOOTSTRAP for safety, it must be loaded before all possible plugins -->
<!--<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">-->
<!-- font awesome (e.g. required by easybutton & sidebar)-->
<!-- <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
-->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- syntax highlights library (scroll to the bottom for specific syntax): -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/themes/prism.min.css">
<style type='text/css'>
.note{
color: #666;
}
body{
font-family: 'Lato', sans-serif;
max-width: 60vw;
margin-left: 25vw;
line-height:1.5em;
text-align: justify;
text-justify: inter-word;
}
#toc{
position:fixed;
left: 0;
top: 0;
background-color: #f5f2f0;
width: 20vw;
height: 100vh;
overflow: auto;
}
h1, h2, h3, h4, h5, h6, ul, ol, td:not(:last-child){
text-align: initial;
text-justify: initial;
}
h1, h2, h3, h4, h5, h6{
font-family: 'Encode Sans Condensed', sans-serif;
margin-top: 3rem;
border-bottom: 2px solid #b74122;
color: #b74122;
line-height: 2;
}
table{
display:block;
overflow: auto;
}
table td{
vertical-align:top;
}
input[type=text]{
padding:0.5em;
min-width:20em;
font-size: 100%;
}
a, a:hover{
text-decoration: none;
}
/* numbering */
body {
/* Set "h2counter" and "h3counter" to 0 */
counter-reset: h2counter h3counter;
}
h1 {
/* Set "h2counter" and "h3counter" to 0 */
counter-reset: h2counter h3counter;
}
h2 {
/* Set "h3counter" to 0 */
counter-reset: h3counter;
}
h2:before {
content: counter(h2counter) ".\0000a0\0000a0";
counter-increment: h2counter;
counter-reset: h3counter;
}
h3:before {
content: counter(h2counter) "." counter(h3counter) ".\0000a0\0000a0";
counter-increment: h3counter;
}
</style>
</head>
<body>
<div id='toc'>
<!-- this TOC will be populated later with all H1,2,3 found in this document.
See javascript code at the page bottom.
Everything you write here will be overridden -->
</div>
<p style='font-weight:bold;font-size:200%'>eGSIM deployment (Django and wsgi)</p>
<p>
The following cheatsheet covers two main aspect: Maintenance and Deployment.
It assumes that you already have access to a remote
machine. The following instructions have been tested on Ubuntu 18.04 MATE.
The procedure to obtain or update an SSL certificate (in order to have
a http<b>s</b> address) is not covered here
</p>
<p>
Set the following variables to see meaningful paths (the document will update
automatically):
</p>
<table>
<tr>
<td>
<input type='text' id='DOMAIN' /> <!-- see bottom of the page to set the startup var -->
</td>
<td>
The domain name of the computer, i.e. the internet address it is assigned to,
e.g.: rz-vm183d.gfz-potsdam.de, www.example.com
</td>
</tr>
<tr>
<td>
<input type='text' id='DJANGO_PROJECT' />
</td>
<td>
The eGSIM Django project name where all Python packages will be placed
(including the eGSIM git repository) <b>usually egsim followed by some numeric version,
but note that this also is the name of the Gunicorn
service file, so please provide only alphanumeric or underscore characters</b>
</td>
</tr>
<tr>
<td>
<input type='text' id='DJANGO_USER' />
</td>
<td>
The Django user (can be the same as <code>$DJANGO_PROJECT</code>)
</td>
</tr>
<tr>
<td>
<input type='text' id='PYTHON_VERSION' />
</td>
<td>
the Python version of the virtual environment (major.medium or major.medium.minor).
The relative Python virtual environment should be created by convention
under $VENV_PATH
(see below)
</td>
</tr>
</table>
<h1>Maintenance</h1>
This section covers information for an already installed program. To perform a
server installation, scroll down
<h2>Important files</h2>
<table>
<tr>
<td><i class="fa fa-folder-o"></i></td>
<td><span class="token important">$EGSIM_CWD</span><br>
where the cloned eGSIM project and (usually) the Python virtual environment resides.
This is the place to go to perform <code>git</code> operations and
activate the virtual environment</td>
</tr>
<tr>
<td><i class="fa fa-folder-o"></i></td>
<td><span class="token important">$VENV_PATH</span><br>
The Python path (virtual environment)</td>
</tr>
<tr>
<td><i class="fa fa-file-o"></i></td>
<td><span class="token important">$EGSIM_CONFIG_DIR/settings.py</span><br>
the settings, keep confidential, root access needed</td>
</tr>
<tr>
<td><i class="fa fa-file-o"></i></td>
<td><span class="token important">/etc/systemd/system/$DJANGO_PROJECT.service</span><br>
the Gunicorn script to start the django production server</td>
</tr>
<tr>
<td><i class="fa fa-file-o"></i></td>
<td><span class="token important">$EGSIM_LOG_DIR/gunicorn.log</span><br>
inspects the django server log<br>
Example: sudo tail -30 $EGSIM_LOG_DIR/gunicorn.log</td>
</tr>
<tr>
<td><i class="fa fa-file-o"></i></td>
<td><span class="token important">/etc/nginx/sites-available/$DJANGO_PROJECT</span><br>
the nginx config for the egsim site</td>
</tr>
<tr>
<td><i class="fa fa-file-o"></i></td>
<td><span class="token important">/var/log/nginx/access.log</span><br>
inspects the nginx log (access info).<br>
Example: sudo tail -30 /var/log/nginx/access.log</td>
</tr>
<tr>
<td><i class="fa fa-file-o"></i></td>
<td><span class="token important">/var/log/nginx/error.log</span><br>
inspects the nginx log (error info)<br>
Example: sudo tail -30 /var/log/nginx/error.log</td>
</tr>
<tr>
<td><i class="fa fa-file-o"></i></td>
<td><span class="token important">/etc/nginx/sites-available/default</span><br>
the default nginx config. It should be the "fallback" when all
other configs are not used. We saved the original not-modified config
in <code>default.backup</code> in the same directory
</td>
</tr>
<tr>
<td><i class="fa fa-file-o"></i></td>
<td><span class="token important">/etc/nginx/nginx.conf</span><br>
the main nginx configuration (should not be modified frequently
and only in rare cases)
</td>
</tr>
<tr>
<td><i class="fa fa-file-o"></i></td>
<td><span class="token important">/etc/hosts</span><br>
where the matching hosts are written: should not be modified
frequently, we did it only once to add the domain name
(line "127.0.0.1 $DOMAIN", without quotes)
</td>
</tr>
</table>
<h2>Common operations</h2>
<b>
Note: in any command below you need to restart the service(s)
$DJANGO_PROJECT and nginx. If you want to check their functioning
after restart, type:
</b>
<pre><code class="language-bash">
service $DJANGO_PROJECT restart && systemctl status $DJANGO_PROJECT
service nginx restart && nginx -t
</code></pre>
<h3>Get Django uploaded files directory</h3>
If you did not set it explicitly in settings.FILE_UPLOAD_TEMP_DIR (by default
is missing), then Django will put uploaded files the standard temporary
directory which you can get easily by typing:
<pre><code class="language-bash">
source $VENV_ACTIVATE
python -c "import tempfile;print(tempfile.gettempdir())"
</code></pre>
<h3>Update the package</h3>
<b>this assumes there are: NO changes to
(=migrations to be performed on) the eGSIM database, NO Python libraries
to be updated or newly installed, NO static files
(e.g., images, css, javascript) to be updated</b>
<p>Inside $EGSIM_CWD, as root user:</p>
<pre><code class="language-bash">
(cd $EGSIM_CWD && git pull)
service $DJANGO_PROJECT restart
service nginx restart
</code></pre>
<h3>Update the package and the static files</h3>
<b>this assumes there are: NO changes to
(=migrations to be performed on) the eGSIM database, NO Python libraries
to be updated or newly installed</b>
<p>Same as above but we need to run Django collectstatic in the activated virtualenv</p>
<pre><code class="language-bash">
source $VENV_ACTIVATE
(cd $EGSIM_CWD && git pull)
(cd $EGSIM_CWD; export PYTHONPATH=$EGSIM_CONFIG_DIR DJANGO_SETTINGS_MODULE=settings; python manage.py collectstatic)
service $DJANGO_PROJECT restart
service nginx restart
deactivate
</code></pre>
<h3>Update egsim DB data or media files</h3>
(For details on how to change the DB schema, see README file)
<p>IMPORTANT: Execute these command as <code>$DJANGO_USER</code>
<b>otherwise database and media files will not be accessible and you'll get a cryptic
"500 error" by the server</b>
</p>
<p>Thus FIRST type:</p>
<pre><code class="language-bash">
su $DJANGO_USER
</code></pre>
<b>You probably need to re-activate the Python virtual env</b>:
<pre><code class="language-bash">
source $VENV_ACTIVATE
</code></pre>
Now type:
<pre><code class="language-bash">
(cd $EGSIM_CWD && git pull)
rm $EGSIM_DATA_DIR/egsim.db
# create the db and populate it with Django stuff (this is necessary only when changing the DB schema, but for safety):
(cd $EGSIM_CWD; export PYTHONPATH=$EGSIM_CONFIG_DIR DJANGO_SETTINGS_MODULE=settings; python manage.py migrate)
# populate the DB with egsim stuff
(cd $EGSIM_CWD; export PYTHONPATH=$EGSIM_CONFIG_DIR DJANGO_SETTINGS_MODULE=settings; python manage.py egsim_init)
service $DJANGO_PROJECT restart
service nginx restart
</code></pre>
<h3>Install system fonts (to produce and download the same plots visible on the browser)</h3>
See snippet below (change the font name and the URL in case. The font directory "egsim" should be
already created, otherwise create it with the name you wish):
<pre><code class="language-bash">
cd /usr/share/fonts
mkdir egsim
cd egsim
wget "https://fonts.google.com/download?family=Encode%20Sans%20Semi%20Condensed" -O ./Encode_Sans_Semi_Condensed.zip
unzip -d . ./Encode_Sans_Semi_Condensed.zip
sudo chmod -R --reference=/usr/share/fonts/opentype /usr/share/fonts/egsim
fc-cache -fv
# check if font is installed:
fc-match EncodeSansSemiCondensed
</code></pre>
More details <a target="_blank" href="https://gist.github.com/lightonphiri/5811226a1fba0b3df3be73ff2d5b351c">here (opens in new tab)</a>
<p></p>
To check the font name, type <code>fc-list</code>
(optionally with <code>grep</code>) and check the font name which is
displayed after the first colon ":". E.g.:
<pre><code class="language-bash">
fc-list | grep Encode
</code></pre>
More details <a target="_blank" href="https://unix.stackexchange.com/a/305934">here (opens in new tab)</a>
<h1>Server installation</h1>
<h2>System requirements</h2>
Update and upgrade
<pre><code class="language-bash">
sudo apt-get update && sudo apt-get upgrade
</code></pre>
<p>Install required libraries</p>
<pre><code class="language-bash">
apt install git nginx-light curl libhdf5-dev gcc python3-rtree
</code></pre>
<p class='note'>
(libhdf5-dev gcc required by openquake,
see below. python3-rtree required by gmpe-smtk, see below)
</p>
<p>Optional installations</p>
<pre><code class="language-bash">
apt install vim
</code></pre>
<p>Install Python desired version</p>
Add repository (one time operation):
<pre><code class="language-bash">
sudo add-apt-repository ppa:deadsnakes/ppa
</code></pre>
Install your Python desired version
<b>Please check that
the value of the <input> component on top of this document is a correct Python version
(e.g. "3.11.2" or "3.10") before running the commands below</b>
<pre><code class="language-bash">
sudo apt-get update
sudo apt-get install $CURRENT_PYTHON $CURRENT_PYTHON-dev $CURRENT_PYTHON-distutils $CURRENT_PYTHON-venv
</code></pre>
<details>
<summary>Add Django user if not present yet (click for details)</summary>
[UPDATE 3/2023]: If you keep the same user as previous versions, skip this section
<pre><code class="language-bash">
adduser --system --home=$EGSIM_DATA_DIR --no-create-home --disabled-password --group --shell=/bin/bash $DJANGO_USER
</code></pre>
Optional: to configure $DJANGO_USER terminal sessions
(e.g. colors, completion, history, command aliases):
copy the root bashrc into $DJANGO_USER, i.e. typing as root:
<code>cp $HOME/.bashrc /var/opt/$DJANGO_USER/.bashrc</code>
(where <code>/var/opt/$DJANGO_USER</code> is supposed to be the $HOME variable of
$DJANGO_USER: in case of doubts: <code>su $DJANGO_USER</code> and <code>echo $HOME</code>)
</details>
<p>Final note: as always, proceed installing
Python packages being aware that in case of problems, the solution after googling is to
<code>apt-get install</code> missing packages. For instance, in case of Python 3.9
installation we had to:
<code>sudo apt-get install gfortran libopenblas-dev liblapack-dev libfreetype6-dev libgeos-dev</code>
<h2>Program requirements</h2>
<p>Create project folder</p>
<pre><code class="language-bash">
cd /opt
mkdir $DJANGO_PROJECT
cd $DJANGO_PROJECT
</code></pre>
<p>Clone package(s)</p>
eGSIM:
<pre><code class="language-bash">
git clone https://github.com/rizac/eGSIM.git
</code></pre>
Check that the path of eGSIM repository is: $EGSIM_CWD
<p>Create the virtual environment</p>
[UPDATE 10/2021] IMPORTANT: you need to have python-venv installed
(e.g. <code>apt-get install $CURRENT_PYTHON-venv</code>, see above).
<p>Installation</p>
<pre><code class="language-bash">
$CURRENT_PYTHON -m venv $VENV_PATH
</code></pre>
<p>Activation</p>
<pre><code class="language-bash">
source $VENV_ACTIVATE
</code></pre>
<p><b>IMPORTANT: from now on, every Python-related operation must be performed
within your activated virtual env</b></p>
<p>Check correct path: activate virtualenv and type</p>
<pre><code class="language-bash">
which python
python --version
</code></pre>
<p>the Python path should refer to the newly installed Python in the current
virtual environment (Python version should be 3.7+)</p>
<b>We assume hereafter that you are in $DJANGO_PROJECT</b>
<p>Install the repositories</p>
<p class='note'>For any error in any of the 'pip install' commands below,
the most likely cause is some system package missing: we suggest to google the
error first, then check if anybody suggests to <code>apt install</code>
missing packages and follow the instructions. <b>Ignore at first complicated
suggestions, they are rarely the solution to your problem</b>.
This doc was created precisely following the pattern above.
Eventually, we added in the apt-install command above all packages that we
discovered missing, so hopefully a fresh new installation might work fine
without any new error</p>
<p>Install eGSIM + required packages: activate virtualenv, then</p>
<pre><code class="language-bash">
cd ./eGSIM/
pip install --upgrade pip setuptools && pip install -r ./requirements.txt && pip install gunicorn
</code></pre>
<h2>Create project structure</h2>
<p>Data directory with correct ownership</p>
<pre><code class="language-bash">
mkdir $EGSIM_DATA_DIR
chown $DJANGO_USER $EGSIM_DATA_DIR
</code></pre>
<p>Log directory with correct ownership</p>
<pre><code class="language-bash">
mkdir $EGSIM_LOG_DIR
chown $DJANGO_USER $EGSIM_LOG_DIR
</code></pre>
<p>Config directory. Change group ownership (with the flag --group added to the command adduser
above we created a group with the same name as $DJANGO_USER).
Change also permissions (750 means the current user, i.e. root, can read, write,
and execute while the group and others cannot write)</p>
<pre><code class="language-bash">
mkdir $EGSIM_CONFIG_DIR
chgrp $DJANGO_USER $EGSIM_CONFIG_DIR
chmod 750 $EGSIM_CONFIG_DIR
</code></pre>
<h2>Set up the project</h2>
<p>Create the settings file:
Create (or copy from a previous deployment file):
<p><code>$EGSIM_CONFIG_DIR/settings.py</code></p>
For reference, see the template below, which is automatically
filled according to the variables set in this page:
<pre><code class="language-python">
"""
Django settings for eGSIM project.
Copied from https://djangodeployment.com/wp-content/uploads/2017/03/Django-deployment-cheatsheet.pdf
This file should be copied from previous deployments and modified accordingly
Listed below are the Django variables that are most likely to be edited. Note that this module
inherits from the debug settings under the egsim git repository
"""
from egsim.settings_debug import *
DEBUG = False # DO NOT CHANGE THIS!
ALLOWED_HOSTS = ['$DOMAIN']
# SECRET_KEY SHOULD BE UNIQUE FOR EACH SETTINGS FILE AND CAN BE GENERATED ON THE TERMINAL (WITHIN THE DJANGO VIRTUAL ENV) WITH THE COMMAND:
# python -c "from django.core.management.utils import get_random_secret_key;print(get_random_secret_key())"
# COPY THE OUTPUT STRING HERE BELOW
SECRET_KEY = ''
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '$EGSIM_DATA_DIR/egsim.db',
}
}
# static files root (path on the server)
STATIC_ROOT = '/var/cache/$DJANGO_PROJECT/static/'
# static files url (already set in settings debug, here for ref.):
# STATIC_URL = '/static/'
# media root (path on the server):
MEDIA_ROOT = '$EGSIM_DATA_DIR/media/'
# static files url (already set in settings debug, here for ref.):
# MEDIA_URL = '/media/'
CSRF_TRUSTED_ORIGINS = ["https://$DOMAIN"] # required in Django 4+. Https or http depends on your SSL certificate
</code></pre>
Then, inside $EGSIM_CWD:
<p>Run collectstatic: copy static files to the new location.
Activate virtualenv and:</p>
<pre><code class="language-bash">
(cd $EGSIM_CWD; export PYTHONPATH=$EGSIM_CONFIG_DIR DJANGO_SETTINGS_MODULE=settings; python manage.py collectstatic)
</code></pre>
<p class='note'>(the PYTHONPATH simply makes the option
<code>--settings=settings</code> to point to the newly created settings.py).
You should see a message like: '175 static files copied to
'/var/cache/$DJANGO_PROJECT/static'
(the number of files might be huge but there are also Django css and so on
</p>
<p>Migration and data initialization scripts</p>
<p>IMPORTANT: Execute these command as <code>$DJANGO_USER</code>, thus FIRST type:</p>
<pre><code class="language-bash">
su $DJANGO_USER
</code></pre>
<b>You probably need to re-activate the Python virtual env</b>:
<pre><code class="language-bash">
source $VENV_ACTIVATE
</code></pre>
With the Python virtualenv activated, execute:
<p>Django migration</p>
<pre><code class="language-bash">
(cd $EGSIM_CWD; export PYTHONPATH=$EGSIM_CONFIG_DIR DJANGO_SETTINGS_MODULE=settings; python manage.py migrate)
<!--export PYTHONPATH=$EGSIM_CONFIG_DIR/;export DJANGO_SETTINGS_MODULE=settings;python manage.py migrate-->
</code></pre>
<p>Initialize our database (OpenQuake GSIMs IMTs and TRTs)</p>
<pre><code class="language-bash">
(cd $EGSIM_CWD; export PYTHONPATH=$EGSIM_CONFIG_DIR DJANGO_SETTINGS_MODULE=settings; python manage.py egsim_init)
<!--export PYTHONPATH=$EGSIM_CONFIG_DIR; export DJANGO_SETTINGS_MODULE=settings;python manage.py egsim_init-->
</code></pre>
<h2>Server configuration</h2>
<p>NGINX is the main application server, however, it delegates Gunicorn for
serving the Python code (everything except static and media files).</p>
In the following, we will configure Gunicorn and Nginx.
<p>IMPORTANT: <b>remember that After any modification to the code or the config below,
before checking the results online, is better to restart the services</b></p>
<pre><code class="language-bash">
service $DJANGO_PROJECT restart
service nginx restart
</code></pre>
<h3>Gunicorn</h3>
<p>
(become root <code class="language-bash">su root</code> and <b>(re)activate virtualenv if necessary</b>)
</p>
Check that gunicorn is installed, i.e. the file <code>$VENV_PATH/bin/gunicorn</code> exists
(otherwise <code>pip install gunicorn</code>)
<details>
<summary>
Start Gunicorn and go to $DOMAIN (from the server or another external computer)
to test:
</summary>
<pre><code class="language-bash">
export PYTHONPATH=$EGSIM_CONFIG_DIR; export DJANGO_SETTINGS_MODULE=settings
gunicorn --workers=4 --log-file=$EGSIM_LOG_DIR/gunicorn.log --bind=127.0.0.1:$GUNICORN_PORT --bind=[::1]:$GUNICORN_PORT egsim.wsgi:application
</code></pre>
<!-- <p>Create the systemd task to start automatically egsim django server</p>
<pre><code class="language-bash">
su $DJANGO_USER
</code></pre> -->
</details>
<p>
Create the so-called service <i>unit file</i> (<code>touch</code> or
<code>cp</code> from a previous unit file, if available.
<i>Remember: not dots in the file name</i>):
</p>
<pre><code class="language-bash">/etc/systemd/system/$DJANGO_PROJECT.service</code></pre>
<p>
with the following content (please READ NOTES BELOW before deploying):
</p>
<pre><code class="language-bash">
[Unit]
Description=$DJANGO_PROJECT
[Service]
User=$DJANGO_USER
Group=$DJANGO_USER
Environment="PYTHONPATH=$EGSIM_CONFIG_DIR:$VENV_PATH"
Environment="DJANGO_SETTINGS_MODULE=settings"
WorkingDirectory=$EGSIM_CWD
ExecStart=$VENV_PATH/bin/gunicorn \
--workers=4 \
--log-file=$EGSIM_LOG_DIR/gunicorn.log \
--timeout=180 \
--bind=127.0.0.1:$GUNICORN_PORT --bind=[::1]:$GUNICORN_PORT \
egsim.wsgi:application
[Install]
WantedBy=multi-user.target
</code></pre>
<b>Important notes:</b>
<ul>
<li>--bind argument: it is typed twice to
bind our Django application on localhost both on ipv6 and ipv4 interfaces.
We will then tell Nginx (see below) to proxy each request to localhost
(see <code>proxy_pass</code> argument) delegating Gunicorn for everything that is not a
static file (everything not in media or static directories)
</li>
<li>--timeout argument: this is the timeout after which a request is interrupted. It should
be equal to the timeout configured for Nginx (see config file in this page).
Timeout errors will result in a 502 error (Gunicorn) and - theoretically -
a 504 (Nginx)
</li>
<li>The URL port of the <code>--bind</code> arguments is set as
<input type='number' step="1" id='GUNICORN_PORT' style="width:6rem"/>, you can change
the value in the field to automatically update the templates below. Changing the port
is useful if you want to run several Gunicorn instances from Nginx (e.g., previous
versions alongside the current)
</li>
</ul>
<p>Stop all running egsim services</p>
List all running services via:
<pre><code class="language-bash">
systemctl list-units --type=service --state=running
</code></pre>
And then, after identifying the old egsim service:
<pre><code class="language-bash">
service [old_egsim_unit_file] stop
</code></pre>
</p>
<p><b>Important note</b> without this procedure, if the old service is using the same url
and port specified in the unit file above, then our service will not work, as the port is
already in use
</p>
<p>Restart the service</p>
<pre><code class="language-bash">
service $DJANGO_PROJECT stop
systemctl daemon-reload
service $DJANGO_PROJECT start
</code></pre>
<p>Check the status of the service</p>
<pre><code class="language-bash">
sudo systemctl status $DJANGO_PROJECT
</code></pre>
<details>
<summary>command details</summary>
The usual way to restart the service:
<pre><code class="language-bash">
service $DJANGO_PROJECT restart
</code></pre>
works if the service file has not been changed. so for safety we
instruct systemd to reload its configuration files, including unit files and security
profiles, without restarting the system or services (the command is essential after making
changes to any unit file to ensure systemd applies the updates correctly)
</details>
<p>
<details>
<summary>To start the service automatically on boot:</summary>
<pre><code class="language-bash">
systemctl enable $DJANGO_PROJECT
</code></pre>
</details>
</p>
<h3>NGINX</h3>
<p>
(become root <code class="language-bash">su root</code> and <b>(re)activate virtualenv if necessary</b>)
</p>
<p>
Create the config file (<code>touch</code> or
<code>cp</code> from a previous config file, if available):
</p>
<pre><code class="language-bash">
/etc/nginx/sites-available/$DJANGO_PROJECT
</code></pre>
<p>
with the following content (Please READ NOTES BELOW before deploying):
</p>
<pre><code class="language-nginx">
server {
listen 80;
listen [::]:80;
server_name $DOMAIN www.$DOMAIN;
location / {
proxy_pass http://localhost:$GUNICORN_PORT;
proxy_read_timeout 180s;
}
location /static/ {
alias /var/cache/$DJANGO_PROJECT/static/;
}
location /media/ {
alias $EGSIM_DATA_DIR/media/;
}
}
</code></pre>
<b>Important notes:</b>
<ul>
<li>The line <code>proxy_pass http://localhost:$GUNICORN_PORT;</code>
is the line that forwards to Gunicorn all locations starting with '/' and not
matching '/static/' or '/media/'. As such, <code>proxy_pass</code> must point to the Gunicorn
URL just configured in the service unit file (see above)
</li>
<li>The line <code>proxy_read_timeout</code> defines a timeout for reading a response from the proxied server.
It is optional but if given, it should match the proxy server timeout (gunicorn in our case).
<b>Note that timed out requests from the proxy server return a 502 error, and from nginx a 504</b>:
if you encounter these errors after waiting for a long time, it is likely that you need to
increase the timeout settings
</li>
</ul>
<p>Remove the previous egsim link (if present)</p>
<pre><code class="language-bash">
ls -l /etc/nginx/sites-enabled
# then rm ... the link pointing to the previous config
</code></pre>
<p>Create link in sites-enabled</p>
<pre><code class="language-bash">
cd /etc/nginx/sites-enabled
ln -s ../sites-available/$DJANGO_PROJECT .
</code></pre>
<p>
<details>
<summary>Add $DOMAIN to known hosts (one time operation)</summary>
<b>NOTE: This operation should be investigated: it is not mentioned
in any documentation, but we needed to do it once, in order to make the site work
</b>:
open <code>/etc/hosts</code> and add the line:
<pre><code class="language-bash">
127.0.0.1 $DOMAIN
</code></pre>
</p>
</details>
</body>
<script type='text/javascript'>
// customizable global variables:
var $DOMAIN = 'egsim.gfz-potsdam.de';
var $DJANGO_PROJECT = '[DJANGO_PROJECT]';
var $DJANGO_USER = '[DJANGO_USER]';
var $PYTHON_VERSION = '3.11.3';
var $GUNICORN_PORT = '8001';
// all global variables (the vars listed above plus other inferred from them):
var allVars = [
'$DJANGO_USER',
'$DOMAIN',
'$DJANGO_PROJECT',
'$PYTHON_VERSION',
'$VENV_PATH',
'$VENV_ACTIVATE',
'$CURRENT_PYTHON',
'$EGSIM_DATA_DIR',
'$EGSIM_LOG_DIR',
'$EGSIM_CONFIG_DIR',
'$EGSIM_CWD',
'$GUNICORN_PORT'
];
// script for custom code on page load:
window.onload=function(){
// replace variables $... with <span> updated automatically everytime
// we change the content of the $... variable
var body = document.querySelector('body');
var docText = body.innerHTML;
for (var v of allVars){
var reg = new RegExp('\\' + v, "g"); // escape first $
docText = docText.replace(reg, '<span data-key="' + v + '"></span>');
}
body.innerHTML = docText;
// set defaults on input components:
for (let id of ['DJANGO_USER', 'DOMAIN', 'DJANGO_PROJECT', 'PYTHON_VERSION', 'GUNICORN_PORT' ]){
let elm = document.getElementById(id);
// set input value from var:
elm.value = window['$'+id];
// attach listener on input change:
elm.oninput = function(){
window['$'+id] = elm.value;
updatePageVars();
}
}
function updatePageVars(){
// update global variables that depend on other
$EGSIM_CWD = "/opt/" + $DJANGO_PROJECT + "/eGSIM";
$VENV_PATH = '/opt/' + $DJANGO_PROJECT + '/pyenv' + $PYTHON_VERSION;
$VENV_ACTIVATE = $VENV_PATH + "/bin/activate";
var vars = $PYTHON_VERSION.split('.');
var currentPython = 'python' + (vars.length >= 2 ? `${vars[0]}.${vars[1]}` : $PYTHON_VERSION);
$CURRENT_PYTHON = currentPython;
$EGSIM_DATA_DIR = "/var/opt/" + $DJANGO_PROJECT;
$EGSIM_LOG_DIR = "/var/log/" + $DJANGO_PROJECT;
$EGSIM_CONFIG_DIR = "/etc/opt/" + $DJANGO_PROJECT;
//update everything:
for (let v of allVars){
var spans = document.querySelectorAll('span[data-key="' + v + '"]');
for(var span of spans){
span.innerHTML = window[v];
}
}
}
updatePageVars();
// trim code, removing leading and trailing spaces:
var codes = document.querySelectorAll('pre > code');
for(var code of codes){
code.innerHTML = code.innerHTML.trim();
}
// make TOC (table of contents):
var ul = document.createElement('ul');
var toc = document.getElementById('toc');
for (var h of document.querySelectorAll('h1,h2,h3')){
// add to each H* element an id inferred from their inner HTML:
var id = h.innerHTML.replace('/\s/', '_');
h.setAttribute('id', id);
// create an anchor pointing to that H* document section:
var a = document.createElement('a');
a.setAttribute('href', '#'+id);
a.innerHTML = h.innerHTML;
// create a <li> wrapping the anchor above:
var li = document.createElement('li');
// indent the li according to its level (h1, h2 etcetera):
margin = parseInt(h.tagName.substring(1));
li.style.marginLeft = margin + 'rem';
// append all:
li.appendChild(a);
ul.appendChild(li);
}
document.getElementById('toc').innerHTML = ''; // clear
document.getElementById('toc').appendChild(ul);
}
</script>
<!-- scripts for specific syntax highlight in prism (is there a reason we have to put them at the bottom?): -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/components/prism-bash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/components/prism-nginx.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.16.0/components/prism-python.min.js"></script>
</html>