Compare commits

..

710 Commits

Author SHA1 Message Date
Girish Ramakrishnan f74f17af02 fix language 2017-06-13 14:42:30 -07:00
Johannes Zellner 87ca05281d Revert "Always check for updates prior to performing an update"
Lets keep the rest apis more single purpose and offload this case to the
client

This reverts commit 0bddd5a2c6.
2017-06-13 22:58:07 +02:00
Johannes Zellner 9780f77fa8 Ensure we fetch the latest update info
This is to bring the webadmin in sync
2017-06-13 22:51:53 +02:00
Johannes Zellner 0bddd5a2c6 Always check for updates prior to performing an update
This covers the case where the box has not yet received a tarballUrl but
the user already setup a subscription.
2017-06-13 21:42:32 +02:00
Johannes Zellner 20f2a6e4c6 Block updates if sourceTarballUrl is missing 2017-06-13 21:33:03 +02:00
Johannes Zellner 6d47737de7 Remove unused require 2017-06-13 21:14:27 +02:00
Johannes Zellner e8f9552ff9 Remove email modal, it is included in the free plan 2017-06-13 17:26:28 +02:00
Johannes Zellner 9c76c5fc27 Also handle the undecided case 2017-06-13 17:25:59 +02:00
Johannes Zellner f9d5f92397 Align the text with the dialog 2017-06-13 17:23:44 +02:00
Johannes Zellner 3a2a05dfce Change the plan configure label 2017-06-13 17:21:38 +02:00
Johannes Zellner 5a291fa2a4 Change subscription dialog to reflect 1.0 2017-06-13 17:08:36 +02:00
Johannes Zellner 84d34ec004 Mention our app request tracker in the missing app dialog 2017-06-13 16:07:21 +02:00
Girish Ramakrishnan 63fca38f0b Add gce to cloudron-setup 2017-06-12 14:05:03 -07:00
Johannes Zellner e3b2799230 Make it clear that the domain, not the server must be hosted on the DNS provider 2017-06-12 10:16:53 +02:00
Girish Ramakrishnan 2efe72519e Can only update using paid plan 2017-06-09 11:05:23 -07:00
Johannes Zellner eb3ae2c34f Give better feedback when a plan was selected 2017-06-09 14:26:28 +02:00
Johannes Zellner eba79cd859 Open all outlinks in a new tab 2017-06-09 14:10:42 +02:00
Girish Ramakrishnan d7d8cf97ed update dialog text 2017-06-08 14:19:32 -07:00
Girish Ramakrishnan 089f7301b8 set webServerOrigin in cloudron.conf
also remove the hardly used --api-server
2017-06-08 10:51:28 -07:00
Johannes Zellner fb4f13eb13 Fixes to the update dialog logic 2017-06-08 17:44:35 +02:00
Johannes Zellner 89878ff9ad Also preset the login email for account details 2017-06-08 14:09:01 +02:00
Johannes Zellner ba62f577fa Show the correct navbar badge for managed cloudron users 2017-06-08 11:17:32 +02:00
Johannes Zellner 4c5bd2d318 Specifically redirect the managed cloudron user to the cc setup 2017-06-08 11:07:05 +02:00
Johannes Zellner 3c318a72f7 Add email query param name 2017-06-08 10:14:09 +02:00
Girish Ramakrishnan 23532eafea Fix path to version 2017-06-07 20:31:18 -07:00
Girish Ramakrishnan 5b7a080d98 Add email when redirecting to cloudron.io 2017-06-07 17:47:03 -07:00
Girish Ramakrishnan 0a44b8c23b Change badge text based on 1.0.0 or not 2017-06-07 15:15:14 -07:00
Girish Ramakrishnan c0c07c2839 ensure .ssh dir exists
Fixes #349
2017-06-07 09:50:31 -07:00
Girish Ramakrishnan 96d2b32a9f doc: scaleway does not require boot script anymore 2017-06-07 09:18:02 -07:00
Girish Ramakrishnan 795c2ad91c typo 2017-06-07 09:04:11 -07:00
Johannes Zellner fc9a9c3f87 Add new changes to changelog 2017-06-07 16:22:56 +02:00
Johannes Zellner d141d6ba21 Do not poll for subscription so often 2017-06-07 13:41:18 +02:00
Johannes Zellner 479da5393a Reword the version 1.0 update dialog 2017-06-07 13:40:56 +02:00
Johannes Zellner 307334ef81 Also test for parent object in case it does not exist 2017-06-07 12:46:01 +02:00
Johannes Zellner c1ec7a06bf If we don't have a dockerImage, we can't proceed with the update 2017-06-07 12:46:01 +02:00
Johannes Zellner 1126a0fc1e Use the app manifest from the box updater 2017-06-07 12:46:01 +02:00
Johannes Zellner b5f678613b Add version 1.0 welcome dialog 2017-06-07 12:46:01 +02:00
Johannes Zellner b7e3447a46 Show subscription dialog on app update 2017-06-07 12:46:01 +02:00
Johannes Zellner 32fa3b8a51 Show subscription indicator in navbar 2017-06-07 12:46:01 +02:00
Johannes Zellner fe0e4000a6 Fix link to subscription page 2017-06-07 12:46:01 +02:00
Johannes Zellner 9ceeb70fc2 No need to pull in unused AppStore dependency 2017-06-07 12:46:01 +02:00
Johannes Zellner aa8b4f1fba show cloudron account in the settings view 2017-06-07 12:46:01 +02:00
Johannes Zellner 95ba51dfb2 Add wrapper to get current subscription 2017-06-07 12:46:01 +02:00
Girish Ramakrishnan c74fb07ff7 Replace all / with _ when querying graphite
Part of #348
2017-06-06 21:25:20 -07:00
Johannes Zellner 03f1326073 Tweak the architecture doc page 2017-06-05 18:10:50 +02:00
Johannes Zellner daa4c66e7f Do not perform automatic updates for major platform version 2017-06-05 18:06:00 +02:00
Johannes Zellner 571abc56fe Fix email view flickering while not eveything has loaded yet 2017-06-05 14:22:34 +02:00
Johannes Zellner 4aaeccecbd Hide DNS record listing for caas dnsprovider 2017-06-02 10:48:00 +02:00
Johannes Zellner 4287d69397 Correctly show dns recrods on view load 2017-06-02 10:47:56 +02:00
Johannes Zellner de328e34d8 Ensure menu is sorted 2017-06-02 10:47:53 +02:00
Johannes Zellner 8d45ce6971 Move email related things into separate view 2017-06-02 10:47:46 +02:00
Johannes Zellner fa3f173e8a Reduce app grid item size a bit to avoid too early overflow 2017-06-02 09:28:22 +02:00
Girish Ramakrishnan 414e9bdf05 Do not use lastBackupId in cleanup logic
lastBackupId is only used as a "message" passing field for apptask restore.

Theoretically, this code somehow protects a race between the cleanup logic
and the restore apptask. this is unlikely to happen and adds unnecessary
complexity.
2017-06-01 14:47:57 -07:00
Girish Ramakrishnan c342e52e7d Record copyLastBackup in the backupdb 2017-06-01 14:08:55 -07:00
Girish Ramakrishnan 78aa9c66f7 Add a note why we do not cleanup more aggressively yet 2017-06-01 10:33:49 -07:00
Girish Ramakrishnan 986ec02ac6 Add debug on what backup is preserved 2017-06-01 09:38:39 -07:00
Girish Ramakrishnan 4e0bb9187a lower case domain in migrate code path 2017-06-01 09:26:03 -07:00
Johannes Zellner 9c8a8571b4 Ensure we lowercase the domain name before consuming it in dns setup
Finally fixes #335
2017-06-01 17:29:46 +02:00
Johannes Zellner 7f30b8de9d Ensure we test domains with lowercase
Fixes #335
2017-06-01 16:42:16 +02:00
Johannes Zellner d1bfa4875a Give the domain name a bit more space
Fixes #340
2017-06-01 15:31:58 +02:00
Johannes Zellner 0250e1ea59 Improve the domain name fitting 2017-06-01 15:31:58 +02:00
Johannes Zellner 924fb337e8 Ensure long domain names are visible in the app grid
Part of #340
2017-06-01 15:31:58 +02:00
Girish Ramakrishnan 0c9dce0c9f redis: set memoryLimit to 600 because only half is RAM 2017-05-31 23:09:47 -07:00
Girish Ramakrishnan 9e9470c6af Fix link to managed hosting 2017-05-31 21:49:28 -07:00
Girish Ramakrishnan 471539d64b CNAME output from dig has trailing dot 2017-05-30 21:14:28 -07:00
Girish Ramakrishnan 95127a868d 0.150.0 changes 2017-05-30 16:23:06 -07:00
Girish Ramakrishnan f34d429052 kill the backup process if it runs for too long 2017-05-30 16:11:12 -07:00
Girish Ramakrishnan 82e53bce36 ensure backups and clean them every 6 hours
also, make sure they don't run at the same time.
2017-05-30 16:04:32 -07:00
Girish Ramakrishnan b04a417cfc Cleanup errored and creating backups
Fixes #330
2017-05-30 15:16:08 -07:00
Girish Ramakrishnan 77641f4b51 Add backupdb.getByState and backupdb.getByTypeAndState
part of #330
2017-05-30 14:30:06 -07:00
Girish Ramakrishnan 765d20c8be Add backup states to track unfinished backups
part of #330
2017-05-30 13:43:30 -07:00
Girish Ramakrishnan d2420de594 refactor backup cleanup logic 2017-05-30 13:43:30 -07:00
Girish Ramakrishnan 8e9da38451 update schema file 2017-05-26 22:23:24 -07:00
Girish Ramakrishnan ddb69eb25c remove native-dns and use dig directly
native-dns module is unmaintained and we keep getting sporadic
errors from that module

Fixes #220
2017-05-26 16:51:05 -07:00
Girish Ramakrishnan 11697f11cf use constants for admin location 2017-05-24 15:41:37 -07:00
Girish Ramakrishnan 35a2a656d3 doc: fix path to node 2017-05-22 12:25:18 -07:00
Girish Ramakrishnan 6fc69c05ca Add noop storage backend
This is sometimes useful when an update gets stuck because of some
bug in backup logic.

Note that you cannot restore from this backend because nothing is
saved.
2017-05-22 10:45:01 -07:00
Girish Ramakrishnan 65cff35be6 Do not dump certs in the log files 2017-05-19 14:39:08 -07:00
Girish Ramakrishnan 7467907c09 Do not dump data in update script since it might have the cert 2017-05-19 14:34:20 -07:00
Girish Ramakrishnan d6c32a2632 tweak redis memory limit based on app's memory 2017-05-18 15:39:38 -07:00
Johannes Zellner 7dc277a80c Give the backup task more memory 150 is often too close to the limit 2017-05-17 14:17:54 +02:00
Girish Ramakrishnan 4881d090f0 disable dnsmasq on ovh 2017-05-16 16:33:43 -07:00
Girish Ramakrishnan 48330423c6 Add 0.140.0 changes 2017-05-15 14:27:24 -07:00
Girish Ramakrishnan 88e844b545 Bump infra version to reconfigure apps for http2 support 2017-05-12 16:25:14 -07:00
Girish Ramakrishnan f45da2efc4 Merge branch 'http2' into 'master'
Add HTTP/2 support to NGINX configs

See merge request !9
2017-05-12 23:23:41 +00:00
Girish Ramakrishnan f422614e7b doc: new app store submission guidelines
Fixes #292
2017-05-11 15:58:02 -07:00
Johannes Zellner d164f881ca Bring back code for alt domain match
There are no actual tests for this yet. Should be added.
2017-05-11 21:55:29 +02:00
Johannes Zellner 4994a5da49 Use -checkhost openssl subcommand 2017-05-11 21:31:01 +02:00
Johannes Zellner 393317d114 Automatically expand the failing dns records 2017-05-11 16:44:18 +02:00
Johannes Zellner 8de940ae36 Condense the dns checks in the settings view 2017-05-11 16:34:15 +02:00
Johannes Zellner 374130d12a Only set local dns server if run on a cloudron 2017-05-11 15:37:44 +02:00
Johannes Zellner 05fcdb0a67 Extract CN from cert with JS
unlike the sed script, this does not rely on the order openssl reports the subject entities
2017-05-11 15:19:02 +02:00
Johannes Zellner 23827974d8 Fix certificate validation to work with new openssl version as well 2017-05-11 14:58:29 +02:00
Girish Ramakrishnan ae2c0f3503 Use new mail container (fix for exec) 2017-05-10 21:58:39 -07:00
Girish Ramakrishnan cbb93ef7ad For low end cloudrons, give a delay between addon starts
Starting them all at once, sometimes hogs cpu/memory too much
and makes the startup scripts of the addons error.

The new addons setup a .setup file to confirm initialization.
In a future commit, we can use those .setup files to check if
the addon has started up instead of a timeout
2017-05-10 15:43:02 -07:00
Girish Ramakrishnan 4d3c6f7caa better error message 2017-05-09 11:24:47 -07:00
Girish Ramakrishnan 4f3c846e2b Add 0.130.3 changes 2017-05-09 09:22:07 -07:00
Girish Ramakrishnan 6ef2f974ae fs: Use key to determine backup extension 2017-05-08 16:03:29 -07:00
Girish Ramakrishnan 180cafad0c Fix restore of unencrypted backups 2017-05-08 15:48:32 -07:00
Girish Ramakrishnan f707f59765 Only ext4 supports as data dir
Fixes #325
2017-05-08 15:25:16 -07:00
Girish Ramakrishnan 969ef3fb11 doc: ensure the data directory exists 2017-05-08 15:16:58 -07:00
Girish Ramakrishnan 7af3f85d7c cloudron-setup: pass --data-dir for all non 0.10x.x versions 2017-05-08 12:04:00 -07:00
Johannes Zellner ffc0a75545 user.get() returns UserErrors 2017-05-08 13:51:19 +02:00
Johannes Zellner d5b5bdb104 Replace old cloud logo with cloudron logo in error and no app pages 2017-05-08 13:51:19 +02:00
Girish Ramakrishnan 8ae65661dd redact the password so it is never displayed in logs 2017-05-05 15:36:47 -07:00
Johannes Zellner 423c4446de Show description if setup fails due to reserved username 2017-05-05 11:54:47 +02:00
Girish Ramakrishnan 53cffd5133 doc: Add note on A record for external domain 2017-05-04 20:49:53 -07:00
Johannes Zellner 15ff1fb093 Add changes for 0.130.2 2017-05-04 21:52:17 +02:00
Johannes Zellner 195d388990 Bring back tldExists() for the dns setup screen 2017-05-04 21:49:27 +02:00
Johannes Zellner d008e871da Add changes for 0.130.1 2017-05-04 14:34:48 +02:00
Johannes Zellner 3e6295de92 Fix form validation for external domains 2017-05-03 15:25:24 +02:00
Ian Fijolek 788004245a Add HTTP/2 support to NGINX configs
This easy fix should improve performance with newer browsers especially
for applications that require many files to be sent over the wire
*cough*Nextcloud11*cough*

NGINX blog post about HTTP/2 support: https://www.nginx.com/blog/nginx-1-9-5/
2017-05-02 22:00:55 +00:00
Girish Ramakrishnan be5221d5b8 bash gymnastics for password with spaces 2017-05-01 11:40:08 -07:00
Girish Ramakrishnan dacc66bb35 Ignore fifo files during backup
Fixes #318
2017-05-01 10:11:41 -07:00
Girish Ramakrishnan 5f26c3a2c1 bump test image version 2017-05-01 09:46:20 -07:00
Girish Ramakrishnan 228af62c39 Add more changes to 0.130.0 2017-05-01 08:03:40 -07:00
Girish Ramakrishnan b531922175 do not quote the argument 2017-04-30 22:17:23 -07:00
Girish Ramakrishnan dad58efc94 Version 0.130.0 changes 2017-04-30 19:30:03 -07:00
Girish Ramakrishnan 7a3d3a3c74 Fix usage of tar.gz API 2017-04-30 17:42:55 -07:00
Girish Ramakrishnan e5c42f2b90 Do a multipart download for slow internet connections
Fixes #317
2017-04-28 17:28:40 -07:00
Girish Ramakrishnan 6cbf64b88e use openssl password only when restore key is non-empty or backup ends with .enc 2017-04-28 15:00:17 -07:00
Girish Ramakrishnan 9635f9aa24 Use key to determine if we should encrypt or not
When encrypting we use the .enc extension. When not encrypting, we
use the plain .tar.gz extension.

Fixes #315
2017-04-28 14:50:20 -07:00
Girish Ramakrishnan 893f9d87bc make s3 upload use queueSize of 1 2017-04-28 14:50:08 -07:00
Girish Ramakrishnan bfda0d4891 drop support for old format backups 2017-04-28 14:45:44 -07:00
Girish Ramakrishnan 65a62f9fbf allow backup prefix to be an empty string 2017-04-26 22:28:52 -07:00
Girish Ramakrishnan 6d74f7e26f doc: fix link for blacklist testing 2017-04-26 21:20:30 -07:00
Girish Ramakrishnan 14ca0c1623 Support naked domains as external location
Let the user add an A record for naked domains

Fixes #272
2017-04-26 15:56:39 -07:00
Girish Ramakrishnan 3f6e8273a7 remove hack to update docker 2017-04-26 15:50:01 -07:00
Girish Ramakrishnan 287b96925a Check if dns flag is in some intermediate state 2017-04-26 12:36:33 -07:00
Girish Ramakrishnan 608cc1e036 remove notification that can never trigger
this code comes from 0601ea2f39
2017-04-25 17:31:14 -07:00
Girish Ramakrishnan 5fa27c4954 show warning if domain config is not working
fixes #302
2017-04-25 17:31:09 -07:00
Girish Ramakrishnan 8deadece05 handle null tlsCert and tlsKey 2017-04-25 17:29:26 -07:00
Girish Ramakrishnan 797dc26f47 ip_based_setup.conf is long gone 2017-04-25 17:29:26 -07:00
Girish Ramakrishnan ddf7823b19 Make box come up regardless of dns config
Part of #302
2017-04-25 16:53:14 -07:00
Girish Ramakrishnan 923e1d0524 Kill more event based logic 2017-04-25 16:36:38 -07:00
Girish Ramakrishnan 339bc71435 Rename onConfigured to onDomainConfigured 2017-04-25 14:09:13 -07:00
Girish Ramakrishnan 863612356d refactor addDnsRecords to take IP as argument 2017-04-25 14:06:13 -07:00
Girish Ramakrishnan 56cdaefecc configureAdmin on dns key change
This allows the user to re-get an admin certificate by updating
the DNS config.

Part of #302
2017-04-25 14:04:27 -07:00
Girish Ramakrishnan 9e611b6ae3 Run scheduler containers in cloudron network as well
This results in:
  box:scheduler Unhandled error:  { Error: (HTTP code 409) unexpected - Conflicting options: dns and the network mode

Part of #307
2017-04-25 12:25:21 -07:00
Girish Ramakrishnan 7e26b4091b use ":" in security-opt is deprecated 2017-04-25 11:41:05 -07:00
Girish Ramakrishnan d7702b96e5 Also set dns args for redis addon
part of #307
2017-04-25 10:13:52 -07:00
Girish Ramakrishnan 41edd3778d Merge branch 'dns-fixes' into 'master'
Set DNS per container rather than the daemon

Closes #307

See merge request !6
2017-04-25 17:06:31 +00:00
Ian Fijolek 0ac69cc6c9 Add DNS args to platform containers 2017-04-25 15:21:23 +00:00
Johannes Zellner fbb01b1ce7 Add 0.120.1 changes 2017-04-25 13:59:41 +02:00
Johannes Zellner a723203b28 Fix typo of missing data argument 2017-04-25 13:48:12 +02:00
Girish Ramakrishnan a995037f0a set retentionSecs of caas to 10 days 2017-04-24 19:06:19 -07:00
Girish Ramakrishnan 5ad4600fd4 More 0.120.0 changes 2017-04-24 16:29:52 -07:00
Girish Ramakrishnan 8ddb670445 simplify: start/stop taskmanager from platform logic 2017-04-24 15:48:23 -07:00
Girish Ramakrishnan ca5723bbc7 more work on tests
disable the migrate tests for now
2017-04-24 15:45:23 -07:00
Girish Ramakrishnan 1b0a81cb3f make sysadmin test work 2017-04-24 15:21:42 -07:00
Johannes Zellner d92a2b070c retry apt endlessly 2017-04-24 23:40:21 +02:00
Johannes Zellner 4703f1afda woops Revert "WIP"
This reverts commit ca7f80414e.
2017-04-24 16:18:01 +02:00
Johannes Zellner 3fad5e856c Do not cleanup any app backups which are referenced by an app through lastBackupId 2017-04-24 13:50:46 +02:00
Johannes Zellner cc66830a2d Also cleanup app backups which are not referenced by a box backup 2017-04-24 13:41:23 +02:00
Johannes Zellner 880f7b4cd3 Allow to get backups by type in backupdb 2017-04-24 12:41:19 +02:00
Johannes Zellner 5b9d4daafe Add first backup cleanup tests 2017-04-24 12:34:57 +02:00
Johannes Zellner 410420e9d5 Ensure we keep at least one backup on cleanup
If for some reason backups fail for longer than the retention time
we should at least keep the latest around
2017-04-24 12:01:52 +02:00
Johannes Zellner ca7f80414e WIP 2017-04-24 11:41:45 +02:00
Girish Ramakrishnan 81b705b25b give inner callback variable a different name 2017-04-23 22:51:07 -07:00
Girish Ramakrishnan 11c7ba1957 Say why filesystem is not recommended 2017-04-23 22:36:45 -07:00
Girish Ramakrishnan f79e1993cb use debug() more 2017-04-23 22:10:44 -07:00
Girish Ramakrishnan fe71dc22fc add note on lastBackupId 2017-04-23 22:00:17 -07:00
Girish Ramakrishnan e3c72fa6ce remove src/ prefix in debug tags 2017-04-23 21:53:59 -07:00
Girish Ramakrishnan 27a542daec Do not show support tab for non-admins
Fixes #313
2017-04-23 21:25:14 -07:00
Girish Ramakrishnan aeba8e8fd2 Use retentionSecs to cleanup backups
Part of #310
2017-04-23 19:34:00 -07:00
Girish Ramakrishnan a0e122e578 Try to make tests work again 2017-04-23 18:03:40 -07:00
Girish Ramakrishnan 29ae2cf8ca Allow setting retentionSecs in backendConfig
Part of #310
2017-04-22 23:25:57 -07:00
Girish Ramakrishnan abe72442ae Set default retentionSecs
Set to 2 days for filesystem provider and -1 (never) for s3/minio.

Part of #310
2017-04-22 21:46:26 -07:00
Girish Ramakrishnan 8e134f3ae8 make docker install script more robust 2017-04-22 19:22:01 -07:00
Girish Ramakrishnan 70042021aa caas: make migrate not send the restoreKey like upgrade 2017-04-22 18:28:58 -07:00
Girish Ramakrishnan 6cc708136e caas expects filename for migrations 2017-04-22 18:17:44 -07:00
Girish Ramakrishnan 00ac78c839 backup ui: clear form if selector changes 2017-04-22 14:14:21 -07:00
Girish Ramakrishnan 6f0c271e6e Make URL the first field for minio 2017-04-22 13:47:44 -07:00
Girish Ramakrishnan ef3a125ce4 Move the info button 2017-04-22 13:36:28 -07:00
Girish Ramakrishnan d91e8bb87b add minio as a separate backend
Fixes #308
2017-04-22 13:34:43 -07:00
Johannes Zellner a7d7935451 Remove backup download code 2017-04-22 22:17:29 +02:00
Girish Ramakrishnan 8c011ea9b0 setup: do not dump sensitive fields in args 2017-04-22 11:57:00 -07:00
Girish Ramakrishnan c41b2c32f5 Fix debug 2017-04-22 11:50:12 -07:00
Girish Ramakrishnan 1e90ec95d3 Add -y flag to apt install 2017-04-22 10:23:48 -07:00
Girish Ramakrishnan 1cca0aee6e refactor targz logic into separate file 2017-04-21 15:45:45 -07:00
Girish Ramakrishnan be73ec4b66 Add oldFormat support to caas and s3 backends 2017-04-21 15:06:54 -07:00
Girish Ramakrishnan 6c8b9b8799 Propagate error messages from backuptask into box code 2017-04-21 14:26:34 -07:00
Girish Ramakrishnan 0aea7cc347 Add progress-stream for upload/download progress 2017-04-21 12:07:01 -07:00
Girish Ramakrishnan e15c3f05c2 Pass DEBUG args to node.sh 2017-04-21 12:04:54 -07:00
Johannes Zellner f516dddf30 Detect old backup format and pipe to openssl 2017-04-21 19:39:02 +02:00
Johannes Zellner 8fb1bc29d1 Fix storage tests for filesystem and s3 2017-04-21 17:21:10 +02:00
Johannes Zellner cc8f8b2339 Only send backend specific fields on configuration 2017-04-21 16:52:10 +02:00
Johannes Zellner f7338c8210 Show default filesystem storage location 2017-04-21 16:51:46 +02:00
Johannes Zellner c04e8f33c5 Allow to change the backup storage provider in the ui 2017-04-21 16:37:17 +02:00
Johannes Zellner 8e1f190079 Implement check configuration for filesystem backend 2017-04-21 15:37:57 +02:00
Johannes Zellner 019cff8851 Wait for dpkg tasks to finish before installing new docker 2017-04-21 13:34:36 +02:00
Johannes Zellner 8a76788e7a From this version on encrypted backups don't use the openssl implicit salt 2017-04-21 10:58:52 +02:00
Johannes Zellner 33492333c7 Fix backupDone() for caas 2017-04-21 10:31:43 +02:00
Johannes Zellner 710cdc7bb8 Bring storage interface up to date 2017-04-21 10:01:58 +02:00
Johannes Zellner 0471a14894 We always encrypt even with empty key so make that clear with the file extension 2017-04-21 09:59:27 +02:00
Girish Ramakrishnan e4b1b73408 Add more 0.120.0 changes 2017-04-20 20:16:12 -07:00
Girish Ramakrishnan a6c2c608e4 storage/caas: bring it upto speed for new backup design 2017-04-20 20:12:45 -07:00
Girish Ramakrishnan 1cd36319ff s3: support setting the signatureVersion 2017-04-20 19:56:06 -07:00
Girish Ramakrishnan a65611a37b Fix error handling in s3 backend 2017-04-20 19:27:12 -07:00
Girish Ramakrishnan 4769d14414 Mark all fs failures as external errors
This gets the right error message on failures:

$ cloudron machine backup create
Waiting for backup to finish...backup failed: ENOENT: no such file or directory, open '/var/backups/2017-04-21-013900-584/app_7549c6a1-682e-4150-8b40-2c31a3fa92f7_2017-04-21-013900-591_v0.7.1.tar.gz'
2017-04-20 19:01:12 -07:00
Girish Ramakrishnan 64c2f3d8c3 copyBackup() already returns a BackupError 2017-04-20 18:56:34 -07:00
Girish Ramakrishnan 2083efdef8 Fix PERM issue when restoring an app with redis
This is the root cause of 926224bd5d.

0488aada9f caused a regression where
we setup addons in the restore code path. This meant that redis was
instantiated and running, changing the perms of the dir. Then when
the backup extract happens it fails as it has wrong permissions.
2017-04-20 18:12:29 -07:00
Girish Ramakrishnan a5efdb067d Revert "Add apprestoretask.js"
This reverts commit 926224bd5d.

This shouldn't be required. We already fix the perms

See 7035b3c18a
2017-04-20 18:12:29 -07:00
Girish Ramakrishnan 0584ace954 Remove StorageError from backends 2017-04-20 18:12:29 -07:00
Girish Ramakrishnan 77d23d6c15 return BackupsError on error 2017-04-20 18:12:29 -07:00
Girish Ramakrishnan a0c3a531b3 Remove unused file 2017-04-20 18:12:29 -07:00
Girish Ramakrishnan 31ea1e677c Simply change ownership instead instead of umask fiddling 2017-04-20 18:12:25 -07:00
Girish Ramakrishnan 2479af23ab app backups must have app version (and not box version) 2017-04-20 17:29:21 -07:00
Girish Ramakrishnan 83f36981f7 Make box backups work again 2017-04-20 16:26:42 -07:00
Ian Fijolek 851e70be6e Bump version to force creation of new containers 2017-04-20 21:34:31 +00:00
Ian Fijolek f0ba126156 Move dns-search from daemon to client as well
Verified no regression of #130
2017-04-20 21:33:16 +00:00
Ian Fijolek 9dd51575ab Set DNS per container rather than the daemon
All Cloudron containers need to have the nameserver 172.18.0.1. This was
being done at the daemon level, however since there are also iptables
rules restricting access to the nameserver from containers that aren't
on the Cloudron Docker network, this broke DNS for non-Cloudron
containers.

Since the DNS is only required for Cloudron containers in the first
place, this patch specifies 172.18.0.1 as the nameserver when Cloudron
creates a container and reverts the change at the daemon level
2017-04-20 19:02:10 +00:00
Girish Ramakrishnan cf701b8eb0 Use apt install instead so that deps are installed 2017-04-20 10:37:46 -07:00
Girish Ramakrishnan 9b4e81b476 Fix curl usage 2017-04-20 10:19:00 -07:00
Johannes Zellner 788873e858 Add error callbacks for backup in filesystem and s3 2017-04-20 16:18:27 +02:00
Johannes Zellner 926224bd5d Add apprestoretask.js 2017-04-20 16:10:13 +02:00
Johannes Zellner d9a0bf457d Don't make backup files executable 2017-04-20 16:02:13 +02:00
Johannes Zellner 6a5b0c194f No more restore mapping 2017-04-20 15:37:49 +02:00
Johannes Zellner 9f117fcfdc Also simplify the s3 backend 2017-04-20 15:35:52 +02:00
Johannes Zellner fe01d1bf28 Keep storage api as simple as possible
Do not support the directory mapping, which is only used for box backups
This greatly simplifies things, but needs a special fix for the box.
2017-04-20 15:20:11 +02:00
Johannes Zellner a94d44da75 Add generic node.sh to run node apps as root and with memory limitations 2017-04-20 15:20:11 +02:00
Girish Ramakrishnan 8ded006dea Fix apps.getLogs usage 2017-04-19 21:43:29 -07:00
Girish Ramakrishnan 5424a658f3 Do not read PTR records from /etc/hosts
Fixes #306
2017-04-19 19:34:22 -07:00
Girish Ramakrishnan b268a18695 Just destroy the client socket 2017-04-19 09:14:00 -07:00
Johannes Zellner 06f1b9dd1b Ensure we only call callback once for port 25 check
On a caas cloudron we saw timeout and end events raised, causing the box
to crash as async throws on double callbacks
2017-04-19 14:35:22 +02:00
Johannes Zellner e82bdfc996 Use a specific tag of our patched node-archiver 2017-04-19 13:38:46 +02:00
Johannes Zellner 40f5d0412b Bring the caas storage backend up to speed
This is mostly the same as the s3 backend at the moment
2017-04-19 13:30:05 +02:00
Johannes Zellner 65af062c33 Cleanup linter issues 2017-04-19 13:20:24 +02:00
Girish Ramakrishnan 68a1efe3d3 Download short format logs from web ui
Fixes #304
2017-04-18 21:04:45 -07:00
Girish Ramakrishnan 3cb4d4b1ab Add UI to download logs
Part of #304
2017-04-18 18:43:09 -07:00
Girish Ramakrishnan 0c706cffc0 Add API to get cloudron logs
part of #304
2017-04-18 15:19:26 -07:00
Girish Ramakrishnan 5f888341ea move eventlog api into /api/v1/cloudron 2017-04-18 15:18:00 -07:00
Girish Ramakrishnan cf69a8c4ce move feedback route into /api/v1/feedback 2017-04-18 14:49:28 -07:00
Girish Ramakrishnan a3ece64273 getDnsConfig only if admin 2017-04-18 14:41:02 -07:00
Girish Ramakrishnan 4bda11edcf Require admin for reboot, disk, graphs api 2017-04-18 14:31:55 -07:00
Girish Ramakrishnan 3913a8367b doc: provider is varied 2017-04-18 12:22:49 -07:00
Girish Ramakrishnan bac0ea17c2 update packages
this also updates dockerode
2017-04-18 12:22:49 -07:00
Girish Ramakrishnan d7f77de6c6 Add 0.120.0 changes 2017-04-18 12:22:49 -07:00
Girish Ramakrishnan d2d2818b0b wrap curl command with retry and timeouts 2017-04-18 12:22:49 -07:00
Girish Ramakrishnan b58fe9edd6 Update docker to CE 17.03
https://docs.docker.com/engine/installation/linux/ubuntu/#install-from-a-package
has helpful instructions.

This should also help use userns at some point (https://github.com/moby/moby/pull/25540)

Fixes #303
2017-04-18 12:22:32 -07:00
Girish Ramakrishnan dee8bec2dc doc: add note about what we collect 2017-04-18 10:20:29 -07:00
Johannes Zellner d5db9657ca Add s3 mock for the s3 storage tests 2017-04-18 19:15:56 +02:00
Johannes Zellner 9378b949fb Add s3 storage tests
Those are not mocked yet and require real aws things.
Change will follow for mocking. We should probably keep them optionally
working agains AWS directly to ensure things really work
2017-04-18 17:34:45 +02:00
Johannes Zellner ad9cb00f13 Add s3 storage removeBackup() and getDownloadStream() implementations 2017-04-18 17:33:59 +02:00
Johannes Zellner 5ccca76b17 Fix typo 2017-04-18 17:33:17 +02:00
Johannes Zellner cec52e14f6 Remove s3 backup test shell script 2017-04-18 16:58:27 +02:00
Johannes Zellner 977936018f Update aws-sdk node module 2017-04-18 16:49:30 +02:00
Johannes Zellner 261d15f0f7 Handle S3 not found errors 2017-04-18 16:47:49 +02:00
Johannes Zellner 14fe1dde58 s3 storage backend with backup and restore implemented 2017-04-18 16:28:39 +02:00
Johannes Zellner 737bbd26ee sort requires alphabetically 2017-04-18 15:32:59 +02:00
Johannes Zellner f5db7c974f Sync the storage interface api 2017-04-18 14:55:22 +02:00
Johannes Zellner 7303a09f2f Support older backupIds which already include the type prefix 2017-04-18 14:39:48 +02:00
Johannes Zellner e3cfaabb74 Ensure we keep the backup creationTimestamp on migration 2017-04-18 13:35:31 +02:00
Johannes Zellner 3cae400b63 We still want to store the restoreConfig config.json as part of the backup itself 2017-04-18 12:16:32 +02:00
Johannes Zellner 5dd10e7cd2 app restoreConfig file api is no more in the filesystem backend 2017-04-18 12:11:05 +02:00
Johannes Zellner f12358a10c Do not save the restoreConfig json file in the backuptask 2017-04-18 12:10:39 +02:00
Johannes Zellner 23e3b0bd91 Get the restoreConfig from the database instead of the json file 2017-04-18 12:08:26 +02:00
Johannes Zellner 7a39cdda97 Store restoreConfig on backups 2017-04-18 12:02:15 +02:00
Johannes Zellner 5460027a49 Add restoreConfig to backupsdb.js 2017-04-18 11:57:59 +02:00
Johannes Zellner 4cfee06297 Follow the json field pattern 2017-04-18 11:47:18 +02:00
Johannes Zellner d0147a5e67 Fallback to empty restoreConfig if migration fails 2017-04-18 11:36:57 +02:00
Johannes Zellner a1dfc2b47b Add backups.restoreConfig field with migration 2017-04-18 11:33:43 +02:00
Girish Ramakrishnan 5eaade1079 doc: Add note on LE 2017-04-17 22:08:47 -07:00
Girish Ramakrishnan 19d8b90a12 pass IP in query parameter 2017-04-17 21:14:13 -07:00
Girish Ramakrishnan 6bc764090c Get geolocation info from geolocation.cloudron.io 2017-04-17 21:09:04 -07:00
Girish Ramakrishnan d64c4927aa doc: add a privacy section 2017-04-17 20:44:42 -07:00
Johannes Zellner 9c45dec8b0 Fix permissions for the filesystem backend
node will always apply the umask, so we have to set and then restore it
properly
2017-04-17 20:26:06 +02:00
Johannes Zellner a21750a4c9 Fix the mysql dump commandline 2017-04-17 20:26:06 +02:00
Johannes Zellner dda16331f6 Remove unused rmbackup.sh 2017-04-17 20:26:06 +02:00
Johannes Zellner 7b93150047 Also add intermediate removeAppRestoreConfig() api 2017-04-17 20:26:06 +02:00
Johannes Zellner a98177fe71 Ensure non-root permissions to the backups 2017-04-17 20:26:06 +02:00
Johannes Zellner d95e68926b Remove unused backupapp.sh and backupbox.sh 2017-04-17 20:26:06 +02:00
Johannes Zellner ff3a748398 Call backuptask.js directly as root to avoid trampoline shell scripts 2017-04-17 20:26:05 +02:00
Johannes Zellner 9354784f01 Remove unused cpbackup.sh 2017-04-17 20:26:05 +02:00
Johannes Zellner e021a4b377 Remove unused restoreapp.sh 2017-04-17 20:26:05 +02:00
Johannes Zellner 4fac5a785f Add unit tests for the filesystem storage backend 2017-04-17 20:26:05 +02:00
Johannes Zellner 4d42c116ce Implement all the apis for the filesystem storage backend 2017-04-17 20:26:05 +02:00
Johannes Zellner 3879b55642 Also copy the app restore config file 2017-04-17 20:26:05 +02:00
Johannes Zellner 9d61ccaa45 Add custom archiver until upstream fixes 2017-04-17 20:26:05 +02:00
Johannes Zellner 6d8cf8456e Add filesystem backend encryption support
We will probably remove this but lets keep this for now
just to keep changes low in the next release.
2017-04-17 20:26:05 +02:00
Johannes Zellner 5e1ad4ad93 We need root access to copy backup files with the filesystem backend 2017-04-17 20:26:05 +02:00
Johannes Zellner b29a6014d5 Remove unused shell variable 2017-04-17 20:26:05 +02:00
Johannes Zellner bd7625031e The writeable stream end event is 'finished' 2017-04-17 20:26:05 +02:00
Johannes Zellner 9e881d1934 Gunzip the app backups 2017-04-17 20:25:59 +02:00
Johannes Zellner 31f93f0255 Use the directory property not the object 2017-04-17 20:09:10 +02:00
Johannes Zellner 67a7624da0 add an explicit saveAppRestoreConfig() api 2017-04-17 20:09:10 +02:00
Johannes Zellner 7fdf491815 Add backuptask.js to work with new storage interface 2017-04-17 20:09:02 +02:00
Johannes Zellner 798c2ff921 Return correct error if route53 security token is invalid 2017-04-16 12:52:14 +02:00
Girish Ramakrishnan 42c138e134 doc: appstore_config API 2017-04-15 07:30:58 -07:00
Girish Ramakrishnan b1b389dd7d Use the POST routes to login to appstore 2017-04-15 07:13:42 -07:00
Girish Ramakrishnan 8911081f85 When dns config changes, only fixup the cloudron records 2017-04-14 19:52:44 -07:00
Girish Ramakrishnan 9605fe3842 Only change dns records of already installed apps 2017-04-14 19:48:58 -07:00
Girish Ramakrishnan bb91faf23c mysql: Use utf8mb4 character set 2017-04-14 13:29:01 -07:00
Johannes Zellner ba56f7d15d Special case versions lower than '0.11*' to not pass new --data-dir 2017-04-14 17:24:28 +02:00
Johannes Zellner 6e73761983 We still require the versionsUrl in the setup script to be able to restore to older versions 2017-04-14 15:05:09 +02:00
Girish Ramakrishnan 588812a13a Disable secure cookies for tests (since they use http) 2017-04-14 01:45:00 -07:00
Girish Ramakrishnan b6d8721aed reset config in backups test 2017-04-14 01:35:04 -07:00
Girish Ramakrishnan da835afde1 More test fixing 2017-04-14 01:28:29 -07:00
Girish Ramakrishnan 5e22caa6e7 Fix updatechecker tests 2017-04-14 00:36:22 -07:00
Girish Ramakrishnan 937931e885 Pass the token when querying for updates
Part of #293
2017-04-13 19:40:59 -07:00
Girish Ramakrishnan c2b140208e doc: add note on subdomains vs paths 2017-04-13 16:11:12 -07:00
Girish Ramakrishnan f9a4d00b3c Query tarball url via appstore
Part of #293
2017-04-13 15:41:08 -07:00
Girish Ramakrishnan eb2ef47df1 remove boxVersionsUrl
update checker now uses the appstore routes
2017-04-13 11:38:42 -07:00
Girish Ramakrishnan cdb5dc2c53 Remove isDev flag
We can pretty much test everything here on self-hosted cloudrons now
2017-04-13 11:34:03 -07:00
Girish Ramakrishnan f6a2406091 Use hat for secret instead of uuid 2017-04-13 11:05:46 -07:00
Johannes Zellner c7134d2da3 Use a dynamic cookie secret
Fixes #300
2017-04-13 15:13:07 +02:00
Johannes Zellner 1692842bf0 Enable secure cookies
Fixes #299
2017-04-13 14:04:30 +02:00
Johannes Zellner 8d78f06a34 Add more 0.110.0 changes 2017-04-13 13:23:40 +02:00
Johannes Zellner 1694a1536c Use our own tar for app backups
This is only temporarily as moving away from btrfs snapshots,
we introduced a regression for app backups.
gnu tar fails to create tarballs if the files change during packing.
2017-04-13 13:06:12 +02:00
Girish Ramakrishnan e0b9dc3623 doc: fix links 2017-04-13 01:34:10 -07:00
Girish Ramakrishnan 644bc54a0d Get box updates via appstore API
Part of #293
2017-04-13 01:31:25 -07:00
Girish Ramakrishnan b2d062bdf8 Get app updates via appstore API
Part of #293
2017-04-13 01:23:18 -07:00
Girish Ramakrishnan 894d7a6e72 Handle AppstoreError correctly 2017-04-13 01:11:20 -07:00
Girish Ramakrishnan fee513594f Move sendAliveStatus to appstore.js 2017-04-13 01:07:07 -07:00
Girish Ramakrishnan 456c183622 Move sendAliveStatus into appstore.js 2017-04-13 00:52:02 -07:00
Girish Ramakrishnan 0488aada9f refactor appstore logic to separate file 2017-04-13 00:42:44 -07:00
Girish Ramakrishnan 54f7cf5f64 Fix copy/paste errors 2017-04-13 00:19:11 -07:00
Girish Ramakrishnan e1740a0d4b Use new alive route for sending status 2017-04-12 21:29:42 -07:00
Girish Ramakrishnan bac7d3ad84 Check for app and box updates once an hour
Part of #293
2017-04-12 18:48:14 -07:00
Girish Ramakrishnan 6402b0c221 doc: update check api 2017-04-12 18:38:33 -07:00
Girish Ramakrishnan 1f55bb52fc Add a button to check updates instantly
Part of #293
2017-04-12 18:34:20 -07:00
Girish Ramakrishnan 1029402d1e Make mailer.js work in test mode 2017-04-12 15:35:52 -07:00
Girish Ramakrishnan abb371d81e Add 0.110.0 changes 2017-04-12 13:49:27 -07:00
Girish Ramakrishnan 779c9d79b3 Add UI to choose from backups to restore from
Fixes #296
2017-04-12 13:41:26 -07:00
Girish Ramakrishnan 832c11d785 Always show the restore button
Part of #296
2017-04-12 13:17:53 -07:00
Girish Ramakrishnan 85fb63298e Overwrite existing DNS record on restore 2017-04-12 13:17:50 -07:00
Girish Ramakrishnan 25b9d5a746 Fix comment 2017-04-12 00:17:20 -07:00
Girish Ramakrishnan 6dc900bbd8 Bump mysql to fix the encoding issue in dumps 2017-04-12 00:16:33 -07:00
Girish Ramakrishnan e32b313cf2 refactor restore/clone/install into single function 2017-04-11 15:16:42 -07:00
Girish Ramakrishnan a01dea3932 Allow installing from a backup 2017-04-11 13:06:39 -07:00
Johannes Zellner aa0e820605 Bump infra version to rebuild nginx configs 2017-04-10 22:49:35 +02:00
Johannes Zellner 13db61a0e2 Merge branch 'master' into 'master'
Adding proxy_max_temp_file_size 0 to nginx config

Closes #294

See merge request !5
2017-04-10 20:48:50 +00:00
mehdi fce2cdce7f Adding proxy_max_temp_file_size 0 to nginx config.
Explanation:
When proxying an HTTP request, nginx first fills up the memory buffers (set by proxy_buffer_size and proxy_buffers).
When these are full, it then writes them to a temporary file in batches of proxy_temp_file_write_size until it reaches proxy_max_temp_file_size.
When proxy_max_temp_file_size is not set, and a very large file is being served, it reaches the maximum of 1GB, and nginx begins to behave weirdly.
2017-04-10 22:47:19 +02:00
Johannes Zellner 89bb690152 Only log failing REST requests 2017-04-10 14:17:26 +02:00
Girish Ramakrishnan 5c203dc759 Handle case where restore config is not found 2017-04-07 15:29:42 -07:00
Girish Ramakrishnan 4d737d535a doc: disks api 2017-04-07 12:52:57 -07:00
Girish Ramakrishnan 558acf27a3 Add 0.109.1 changes 2017-04-07 12:38:48 -07:00
Girish Ramakrishnan 3da503ab8e doc: improve the data-dir script 2017-04-07 12:34:59 -07:00
Girish Ramakrishnan 299e8aceeb Check if --data-dir exists 2017-04-07 12:34:59 -07:00
Johannes Zellner b422a27be8 Use the new disks api to explicitly get the apps data disk stats
We can add the other graphs if the disks deviate later

Also this is still pending the check if symlinked folders are reported
correctly.

Fixes #290
2017-04-07 18:46:11 +02:00
Johannes Zellner f2312a6768 Add rest api to list disks where cloudron data is stored 2017-04-07 18:45:36 +02:00
Johannes Zellner 178ffe20a8 use df instead of node-df 2017-04-07 18:45:14 +02:00
Johannes Zellner 3b8edd4896 Do not make the DNS notfication persistent 2017-04-07 17:08:52 +02:00
Girish Ramakrishnan f16aab7f80 Add --data-dir to cloudron-setup
This allows the data-dir to be re-located

Part of #148
2017-04-06 23:56:57 -07:00
Girish Ramakrishnan 09118d6b06 doc: how to configure data location 2017-04-06 15:31:43 -07:00
Girish Ramakrishnan bd57ee9461 doc: more security notes 2017-04-06 13:53:35 -07:00
Girish Ramakrishnan 1fbbe036ce doc: appstore command 2017-04-06 13:46:40 -07:00
Johannes Zellner 94d7bc5328 Ensure the app install dialog closes and releases the backdrop when moving to other views
Fixes #201
2017-04-06 17:39:45 +02:00
Johannes Zellner d709a5cfe4 Attempt to give better digitalocean DNS error messages 2017-04-05 16:50:31 +02:00
Johannes Zellner 188f000507 Dump whole errors for app installation progress
Sometimes on error we get random strings for the installationProgresss,
as those contain the upstream errors :-/
We now at least attempt to show that so the user may give us the real
error not some wrongly parsed bits from that.
In the long run we have to make that a real structure to give sane error
messages
2017-04-05 16:42:13 +02:00
Johannes Zellner 51d5b96fa1 use "mountpoint" to check if we have the user data mounted 2017-04-05 14:34:18 +02:00
Girish Ramakrishnan 11d12c591e Add 0.109.0 changes 2017-04-05 00:36:24 -07:00
Girish Ramakrishnan 245d17ad25 Fix test image version 2017-04-04 19:13:03 -07:00
Girish Ramakrishnan e05e9c3ead Use latest test-app 2017-04-04 14:47:54 -07:00
Girish Ramakrishnan 8102d431e8 use debug instead 2017-04-04 14:07:28 -07:00
Girish Ramakrishnan 0f76cbbb95 remove temporary authorized_keys file 2017-04-04 14:00:41 -07:00
Girish Ramakrishnan 2a45a9bbd4 test: rate limit is now in nginx 2017-04-04 13:12:50 -07:00
Girish Ramakrishnan e68d627f72 tests: data -> platformdata 2017-04-04 13:11:44 -07:00
Girish Ramakrishnan 1a3e3638ff iptables-restore is not used anymore 2017-04-04 13:00:48 -07:00
Girish Ramakrishnan 8f912d8a1b add note on how to view graphite browser 2017-04-04 12:35:29 -07:00
Girish Ramakrishnan d891058f8c Restore apps if the existingInfra version is not semver (as in, old infra) 2017-04-04 12:15:29 -07:00
Girish Ramakrishnan 71fe094be1 Make platform version a semver 2017-04-04 12:07:53 -07:00
Johannes Zellner da857f520b Only stop apps and addons on data migration 2017-04-04 14:30:45 +02:00
Johannes Zellner 39ff21bdf4 Bump infra version now with a explicit minor version 2017-04-04 12:34:55 +02:00
Johannes Zellner 72dd7c74d5 Introduce major/minor infra versions
The strategy now is that major infra version changes make apps restore,
whereas minor infra version changes only reconfigure and thus restart
them
2017-04-04 12:34:55 +02:00
Johannes Zellner 7c7ef15e1c Do not collect data for btrfs file systems 2017-04-04 12:34:55 +02:00
Johannes Zellner b320e15ea7 No need to install btrfs-tools in the base image 2017-04-04 12:34:55 +02:00
Johannes Zellner aa22ab8847 Cleanup the btrfs mounts and the user data file 2017-04-04 12:34:55 +02:00
Johannes Zellner 3e23c3efce Do not move the whole mail folder but only its content 2017-04-04 12:34:55 +02:00
Johannes Zellner c4f96bbd6b Some directory creation fixes 2017-04-04 12:34:55 +02:00
Johannes Zellner 649092ecb0 Fix typo PLATFORM_CONFIG_DIR -> PLATFORM_DATA_DIR 2017-04-04 12:34:55 +02:00
Johannes Zellner 128a3b03c9 Do not use btrfs snapshots for mail on box backup 2017-04-04 12:34:55 +02:00
Johannes Zellner 847ef6626f Also use appsdir in rmappdir.sh 2017-04-04 12:34:55 +02:00
Johannes Zellner 4643daeeec Use appsdata in createappdir.sh 2017-04-04 12:34:55 +02:00
Johannes Zellner 38178afd31 Do not use btrfs snapshots for app backups 2017-04-04 12:34:55 +02:00
Johannes Zellner 9c6324631d Use APPS_DATA_DIR in app backup and restore scripts 2017-04-04 12:34:55 +02:00
Johannes Zellner 3a17bf9a0f Ensure apps and platform data dirs exist 2017-04-04 12:34:55 +02:00
Johannes Zellner 602f8bcd04 Split platform and app data folders and get rid of btrfs volumes 2017-04-04 12:34:55 +02:00
Girish Ramakrishnan 785ae765a4 better error text 2017-04-03 16:54:06 -07:00
Girish Ramakrishnan c85120834c refactor ngTld so it can be used with plain strings 2017-04-03 16:20:32 -07:00
Johannes Zellner 89d36b8ad4 Reset the dns error states on resubmission 2017-04-03 22:36:02 +02:00
Johannes Zellner b9711d7b47 Move AMI instanceId verification to DNS setup 2017-04-03 22:19:01 +02:00
Johannes Zellner 4f9273819a Ensure autofocus on setup.html 2017-04-03 16:45:04 +02:00
Johannes Zellner e0d7850135 Add a tooltip to email field during setup 2017-04-03 16:33:07 +02:00
Girish Ramakrishnan 2c871705c7 Add a referrer policy 2017-03-31 16:11:54 -07:00
Girish Ramakrishnan 2bb99db2c7 Add another blacklist tester 2017-03-30 19:42:14 -07:00
Girish Ramakrishnan 3fc5757e97 doc: Add note on OS updates 2017-03-30 08:35:18 -07:00
Girish Ramakrishnan 92ff19ffce Add 0.108.0 changes 2017-03-29 22:20:13 -07:00
Girish Ramakrishnan e9456f70f9 use connlimit module to rate limit
hitcount cannot be more than 255 in recent module
2017-03-29 21:51:24 -07:00
Girish Ramakrishnan ffbda22145 Fine tune rate limits a bit more 2017-03-29 16:03:08 -07:00
Girish Ramakrishnan b92ae44578 Generate 128 byte passwords 2017-03-29 15:38:15 -07:00
Girish Ramakrishnan b6ffc966cd Bump mysql (for increasing multidb password len) 2017-03-29 15:21:49 -07:00
Girish Ramakrishnan b42bc52093 doc: improve rate limit wording 2017-03-29 10:40:02 -07:00
Girish Ramakrishnan 806b458ff1 Move it to the selfhosting guide instead 2017-03-29 10:33:51 -07:00
Girish Ramakrishnan d5d4e237bd doc: add security section 2017-03-29 10:23:08 -07:00
Girish Ramakrishnan 956fe86250 Add firewall service
Docker really insists on adding itself to the top of the FORWARD
chain. Making our firewall side-steps this docker design.
2017-03-29 02:31:53 -07:00
Girish Ramakrishnan 4d000e377f Enable iptables based ratelimit for cloudron auth services
The goal here is to simply add a rate limit to prevent brute
force password attacks.

Covered services includes:
    (public) http, https, ssh, smtp, msa, imap, sieve
    (private) postgres, redis, mysql, ldap, mongodb. msa

The private limits are higher because some apps will create
a db connection for each page request.  Some apps like mailtrain
will send out lots of emails etc.

Note that apps that use SSO are ratelimited by the ldap limit.

Part of #187
2017-03-29 00:02:05 -07:00
Johannes Zellner 39e827be04 Add rosehosting to the help output if no provider is specified 2017-03-28 10:38:00 +02:00
Girish Ramakrishnan e50b4cb7ec doc: fixup the best practices docs
Fixes #232
2017-03-27 15:29:07 -07:00
Johannes Zellner 1938ec635b Remove bestpractices.md as this was already incorporated into the main packaging guide 2017-03-27 16:05:03 +02:00
Johannes Zellner 03a3d367a4 Incorporate best practices into app package guide
Part of #232
2017-03-27 16:03:19 +02:00
Johannes Zellner 38c2f75b5e Also patch the cloudron-setup to match the resize script
Part of #278
2017-03-27 13:51:37 +02:00
Johannes Zellner 9d98b55881 Merge branch 'tobru/fix_278' into 'master'
get disk_size_bytes by directly querying df /. fixes #278

Closes #278

See merge request !4
2017-03-27 11:46:49 +00:00
Girish Ramakrishnan 18e59c4754 Rate limit nginx routes that verify the password
Also remove rate-limit middleware

Test using something like:

    ab -v 1 -n 1000 -c 10 -s 5 -m POST https://my.<doamain>/api/v1/developer/login

Part of #187
2017-03-27 00:06:42 -07:00
Girish Ramakrishnan 64cb951206 Fix failing dns test 2017-03-26 22:07:28 -07:00
Girish Ramakrishnan 77df520b07 addons is optional in manifest 2017-03-26 21:55:31 -07:00
Girish Ramakrishnan 32f94a03ce Fix failing test 2017-03-26 21:53:45 -07:00
Girish Ramakrishnan fc6ce4945f add sendmail/recvmail ldap tests 2017-03-26 20:42:46 -07:00
Girish Ramakrishnan 17b7d89db9 Generate password for mailboxes
Fixes #109
2017-03-26 20:07:59 -07:00
Girish Ramakrishnan 6ea741e92f Verify password for sendmail/recvmail addon
Part of #109
2017-03-26 20:07:55 -07:00
Girish Ramakrishnan 790ad4e74d Add getAddonConfigByName 2017-03-26 19:06:36 -07:00
Girish Ramakrishnan f92297cc99 Store env vars as name, value pairs
Part of #109
2017-03-26 12:22:19 -07:00
Tobias Brunner 0c6c835a39 get disk_size_bytes by directly querying df /. fixes #278
This simplifies the logic to get the available space the root
mountpoint has available and makes it more robust.
2017-03-26 18:03:10 +02:00
Girish Ramakrishnan 514341172c Add name to appAddonConfigs
Part of #109
2017-03-25 18:06:56 -07:00
Girish Ramakrishnan e535ffa778 Disable bind9 as it conflicts with unbound
part of #194
2017-03-25 17:36:10 -07:00
Girish Ramakrishnan b86cfabd17 Do not allocate more than 4GB swap
Also resize existing swap file, if necessary. Note that if the user
allocates more than what we expect, we don't do anything.

Fixes #277
2017-03-24 16:03:30 -07:00
Girish Ramakrishnan b44f0b78a1 remove spurious console.log 2017-03-24 14:55:22 -07:00
Johannes Zellner 76d234d0bf Also allow data: uri to be loaded for images 2017-03-24 17:23:20 +01:00
Johannes Zellner a694acba44 Redirect to /setupdns.html if cloudron is activated but no domain is set
This happens in the restore case where no domain is provided to
cloudron-setup

Fixes #273
2017-03-23 15:40:18 +01:00
Johannes Zellner 046120befc Move email toggle button above checks to make it more likely people read the text 2017-03-23 11:41:26 +01:00
Girish Ramakrishnan b65fee4b73 Pass ENABLE_MDA flag to mail addon 2017-03-22 20:42:28 -07:00
Girish Ramakrishnan 153dcc1826 Fix bug in example text 2017-03-22 18:23:24 -07:00
Girish Ramakrishnan fa4725176c Group help text together 2017-03-22 16:44:18 -07:00
Girish Ramakrishnan e42607fec6 Always show the password input 2017-03-22 16:13:18 -07:00
Girish Ramakrishnan 297c1ff266 Show error message only if the domain changed 2017-03-22 16:06:47 -07:00
Girish Ramakrishnan 5afe75f137 Bump mail container (for mx bypass fix) 2017-03-22 14:39:30 -07:00
Girish Ramakrishnan 4cfc85f6d3 Do not validate password length 2017-03-22 13:50:20 -07:00
Girish Ramakrishnan b03f901bbf More 0.107.0 changes 2017-03-22 12:01:04 -07:00
Johannes Zellner b9dfac94ed Revert "Add ldapjs-rate-limit module"
This reverts commit 3d60a04b36.
2017-03-22 19:35:06 +01:00
Johannes Zellner c905adde1e Revert "Limit ldap queries per client to 60 per minute"
This reverts commit 466dfdf81f.
2017-03-22 19:35:06 +01:00
Girish Ramakrishnan 0e7efa77a5 Bump the mail container 2017-03-22 09:55:04 -07:00
Johannes Zellner 875ca0307f Fix the node tutorial to export the node PATH and use latest node release 2017-03-22 16:20:48 +01:00
Johannes Zellner 543c9843ba Use df instead of fdisk
some disk types do not contain proper partition tables like on time4vps
the type is simfs. On those fdisk fails to access the partition table,
thus being unable to determine the size of the volume.
df does only return the real usable disk space by the user, thus we
lower the 20GB threshold to 18

Fixes #275
2017-03-22 14:23:59 +01:00
Johannes Zellner 83254a16f9 Do not restrict CSP img-src as 3rd party apps might use other origins for medialinks 2017-03-21 20:20:16 +01:00
Johannes Zellner 466dfdf81f Limit ldap queries per client to 60 per minute
Part of #187
2017-03-21 16:43:22 +01:00
Johannes Zellner 3d60a04b36 Add ldapjs-rate-limit module 2017-03-21 16:43:02 +01:00
Johannes Zellner 103cb10cad Ignore upstream headers for security headers we set in nginx
Apps like nextcloud set their own security headers ending up with having
them set twice. I am not 100% sure if our headers should win or if we
should not inject headers with nginx if the upstream app sets them already.
This looks like the more permissive case where we simply enforce our
values, regardless what the apps sets.

This also fixes the nextcloud/owncloud security checks which were
failing because the header values were duplicated, which results in
string concatenation of values from same headers.
2017-03-21 14:18:39 +01:00
Johannes Zellner 29ef079a83 Do not let the invite link overflow the dialog 2017-03-21 13:36:36 +01:00
Johannes Zellner a55645770e Add missing csp img-src policy for app icons 2017-03-21 13:25:29 +01:00
Johannes Zellner 132ddd2671 Add 0.107.0 changes 2017-03-21 11:15:51 +01:00
Johannes Zellner fa5891b149 Also put csp meta tag in oauth views 2017-03-21 11:12:04 +01:00
Johannes Zellner d01929debc Be more permissive with csp header values 2017-03-21 11:12:04 +01:00
Johannes Zellner 7c01ee58b5 Template the cloudron origin for csp to support local development 2017-03-21 11:12:04 +01:00
Johannes Zellner ec89f8719c Add CSP meta tag for webadmin 2017-03-21 11:12:04 +01:00
Girish Ramakrishnan 9145022a2c Put scope in the end since it is pre-filled 2017-03-20 20:06:24 -07:00
Girish Ramakrishnan 9ae8ce3296 Change default oauth client scope to profile 2017-03-20 20:05:22 -07:00
Girish Ramakrishnan eabf27f0c9 More OAuth wording changes 2017-03-20 19:55:27 -07:00
Girish Ramakrishnan 3102a15dff doc: add oauth note in user manual 2017-03-20 19:52:34 -07:00
Girish Ramakrishnan 7747c482d4 Fix oauth wording in the tokens UI 2017-03-20 19:12:32 -07:00
Girish Ramakrishnan 444ca1888b remove dead comment 2017-03-20 15:14:06 -07:00
Girish Ramakrishnan 86ccf5ea84 doc: add kimsufi note
Fixes #261
2017-03-20 14:32:35 -07:00
Girish Ramakrishnan ef088293b6 Do not show repair and configure together 2017-03-20 08:48:50 -07:00
Johannes Zellner e0df19c888 Remove unused api wrapper for getAppLogStream() 2017-03-20 10:46:27 +01:00
Girish Ramakrishnan 6a523606ca Revert "Bump version to Nginx IPv6 support."
This reverts commit 5555321cf5.
This reverts commit f087ebbee0.
This reverts commit d04f64d3d4.

Part of #264
2017-03-19 14:25:30 -07:00
Girish Ramakrishnan b6cd40e63c Use latest manifestformat 2017-03-19 14:20:00 -07:00
Girish Ramakrishnan b421866bf5 Remove simpleauth
Simple Auth used to provide auth over HTTP. The original motivation
behind this was this was a simple way to add Cloudron Auth integration.
Back in the day, Cloudron Auth was a requirement for apps but this is
not the case anymore.

This is currently not used by any app and having this might encourage
people to make Cloudron specific un-upstreamable changes.
2017-03-19 01:31:38 -07:00
Girish Ramakrishnan fe06075816 more CHANGES 2017-03-17 13:49:47 -07:00
Girish Ramakrishnan 2b73eb90ec Merge branch 'ipv6' into 'master'
Add IPv6 Support

See merge request !3
2017-03-17 19:55:30 +00:00
Jonah Aragon 5555321cf5 Bump version to Nginx IPv6 support. 2017-03-17 19:43:54 +00:00
Jonah Aragon f087ebbee0 Add listen [::]:80; for IPv6 redirects. 2017-03-17 19:13:18 +00:00
Jonah Aragon d04f64d3d4 Add IPv6 listen directives 2017-03-17 19:12:25 +00:00
Girish Ramakrishnan 777a5a0929 Add 0.106.0 changes 2017-03-17 10:23:17 -07:00
Girish Ramakrishnan 6c297f890e Bump mail container 2017-03-17 10:23:17 -07:00
Johannes Zellner 3c8d0b1b37 Never hide the busy state on setup when it suceeded
In that case the whole page gets redirected and to avoid page flickering
we keep it at busy until the browser tears the whole page apart.
2017-03-16 09:58:21 +01:00
Johannes Zellner 74f2cd156f Only send setupToken on admin creation if it was actually specified 2017-03-16 09:37:28 +01:00
Girish Ramakrishnan a9fdffa9af 0.105.1 changes 2017-03-15 21:15:15 -07:00
Girish Ramakrishnan e6f8e8eb94 ami field is only required if shown 2017-03-15 21:10:22 -07:00
Girish Ramakrishnan 1bd89ca055 Wait for platform ready after box restarts
This is required for the case where the box restarts apptasks.
For example, the server can reboot mid-way when apptask is running
(as in cloudron-setup + appBundle case) and then when it comes back
up it doesn't wait for the platform to be ready. And the apps fail
to install (mysql takes a bit to startup)
2017-03-15 20:35:44 -07:00
Girish Ramakrishnan 0e226d0314 Download icon (for repair case) 2017-03-15 20:35:44 -07:00
Girish Ramakrishnan e8d4e2c792 send more logs 2017-03-15 19:35:42 -07:00
Girish Ramakrishnan 4cfbed8273 Use inline docker pgp key
The one from keyserver keeps failing sporadically

https://github.com/docker/docker/issues/13555
https://github.com/docker/docker/issues/20022
http://askubuntu.com/questions/720517/key-server-times-out-while-installing-docker-on-ubuntu-14-04
2017-03-15 18:04:44 -07:00
Girish Ramakrishnan 0410ac9780 doc: activate api 2017-03-15 16:14:25 -07:00
Girish Ramakrishnan 82fcf6a770 setupToken is not required in activate 2017-03-15 15:55:31 -07:00
Girish Ramakrishnan a1332865c0 Fix wording (should be prove otherwise) 2017-03-15 15:42:06 -07:00
Girish Ramakrishnan ae0e4de93e No semicolons in bash code 2017-03-15 15:40:43 -07:00
Johannes Zellner 02a6525558 Add changes for 0.105.0 2017-03-15 14:56:35 +01:00
Girish Ramakrishnan 5afef14760 Actually send emails for responsive apps 2017-03-14 13:42:28 -07:00
Johannes Zellner 890d589a36 Do not show Route53 in dns setup for AMIs 2017-03-14 16:54:46 +01:00
Johannes Zellner 89a50c4b83 Use ami provider in ami creation script 2017-03-14 13:48:11 +01:00
Johannes Zellner da5cd2b62c Show instance id input on cloudron setup for amis 2017-03-14 13:45:18 +01:00
Johannes Zellner 57321624aa Add ami setupToken verification in auth route 2017-03-14 13:45:04 +01:00
Johannes Zellner 876ae822b2 Skip splash setup if cloudron domain was not yet setup
This is based on the existence of admin.conf nginx file.
The splash would create/overwrite that file, but it will depend on the
host.cert to be already created, which is only the case after domain
setup.
2017-03-14 10:58:24 +01:00
Johannes Zellner 1ceb75868b Remove last remainder of apidocs 2017-03-14 10:12:17 +01:00
Johannes Zellner 98ad16f943 Remove unused requires 2017-03-14 10:10:59 +01:00
Johannes Zellner 9363746c1a Use ec2 sysinfo for ami provider 2017-03-14 09:34:39 +01:00
Johannes Zellner 7a1b9ab94c Support ami provider for ssh authorized_keys api 2017-03-14 09:34:11 +01:00
Johannes Zellner 46d6b5b81f Add hidden 'ami' provider for pre-built amis 2017-03-14 09:32:51 +01:00
Girish Ramakrishnan 7e8757a78c grep quietly 2017-03-13 13:52:16 -07:00
Girish Ramakrishnan e508b25ecd Lower memory expectations 2017-03-13 13:05:59 -07:00
Girish Ramakrishnan 3fdc10c523 Parse free and fdisk output with C locale
some vps providers seem to set a different locale by default.
Settings LC_ALL overrides all the other LC_*
2017-03-13 10:36:05 -07:00
Johannes Zellner 717953c162 Half the backup progress polling 2017-03-13 13:28:14 +01:00
Johannes Zellner daa34c3b4d add some asserts in the ldap code 2017-03-13 11:10:08 +01:00
Johannes Zellner bf5c78d819 Refactor ldap user listing code to avoid pyramids 2017-03-13 11:09:12 +01:00
Johannes Zellner 1763144278 Only list users in ldap groups who have access to the app
Fixes #215
2017-03-13 11:06:29 +01:00
Johannes Zellner 2f598529fc Only list users who have access to the app in an ldap search
Part of #215
2017-03-13 11:02:45 +01:00
Girish Ramakrishnan 8264e69e2f remove unused require 2017-03-10 14:52:31 -08:00
Johannes Zellner b0638df94e Only show the remote support for admins 2017-03-10 17:21:01 +01:00
Johannes Zellner bb61eee557 Add missing quote in support view 2017-03-10 17:17:51 +01:00
Johannes Zellner 39c39b861d Require admins for authorized_keys route 2017-03-10 17:16:45 +01:00
Girish Ramakrishnan e3deda4ef3 Always show port 25 status 2017-03-09 16:21:47 -08:00
Girish Ramakrishnan 7e44e7de82 Check outbound port 25
Fixes #243
2017-03-09 16:20:53 -08:00
Girish Ramakrishnan 9dd0518c00 Show email settings for non-caas
This is because people can use route53/DO now and we can show them
the RDNS settings as well.
2017-03-09 15:21:43 -08:00
Girish Ramakrishnan 81313d1c40 reduce nxdomain caching timeout
the other option is to use "/usr/sbin/unbound-control flush_negative"
on demand
2017-03-09 15:03:14 -08:00
Girish Ramakrishnan 2ceccc4557 Add note for caas users about enabling email 2017-03-09 14:25:03 -08:00
Girish Ramakrishnan 1c36918e92 Done -> Almost done 2017-03-09 10:21:52 -08:00
Girish Ramakrishnan 8d93df23c1 doc: cnameTarget 2017-03-09 10:00:42 -08:00
Johannes Zellner 0c06b34a2c Add more changes for 0.104.0 2017-03-09 15:38:09 +01:00
Johannes Zellner fe980eab7f Show either cnameTarget or fqdn for CNAME setup hint
Fixes #101
2017-03-09 15:23:17 +01:00
Johannes Zellner 979b903bf2 Add cnameTarget for apps using an external domain
We have 4 properties related to the domain:
1) location, is the subdomain location without information how to craft
a fqdn on the client
2) fqdn, the intended domain to reach the app
3) altDomain, just the value for the external domain, merely a db record
value
4) cnameTarget, mostly for display purpose on the client, which
otherwise has no way to build the original cloudron local fqdn
2017-03-09 15:11:27 +01:00
Johannes Zellner 4b8ee0934a Add Cloudron cancel link to the settings view
Fixes #251
2017-03-09 13:36:29 +01:00
Girish Ramakrishnan 0439725790 Bump infra version 2017-03-08 22:27:41 -08:00
Girish Ramakrishnan 4b3ef33989 Add some basic secure headers
Part of #249
2017-03-08 22:14:44 -08:00
Girish Ramakrishnan 9e99d51853 do not remote support for caas 2017-03-08 16:15:13 -08:00
Girish Ramakrishnan 00a9fa8f34 fix wording a bit 2017-03-08 16:11:45 -08:00
Girish Ramakrishnan 84a35343d1 Display <sso> and <nosso> contents based on SSO 2017-03-08 15:16:15 -08:00
Girish Ramakrishnan 397bd17c55 update showdown to 1.6.4 2017-03-08 15:01:07 -08:00
Girish Ramakrishnan c8e377a9bd doc: scaleway may need reboot for security group to take effect 2017-03-08 10:34:12 -08:00
Johannes Zellner 90e3138bae Show the correct postInstall message after app installation
Fixes #255
2017-03-08 15:42:29 +01:00
Girish Ramakrishnan 24b32a763b Add comments for CLI tool 2017-03-07 12:44:17 -08:00
Johannes Zellner 69a12d36ef Also give lightsail the special user treatment 2017-03-07 16:51:58 +01:00
Johannes Zellner 1485718fa6 Special treatment for ec2 and authorized_key user 2017-03-07 16:44:04 +01:00
Johannes Zellner 750f03d9de Add the public key of our support ssh key 2017-03-07 16:13:48 +01:00
Johannes Zellner b5ddf1d24d Add ssh support toggle button in the support view 2017-03-07 16:12:00 +01:00
Johannes Zellner 043a35111d Remove unused requires in ssh test 2017-03-07 16:11:21 +01:00
Johannes Zellner 676457b589 Add authorized_key wrappers to client.js 2017-03-07 16:07:25 +01:00
Johannes Zellner e61f11be81 Since we need root to save the authorized_key file we do it via sudo script 2017-03-07 15:16:41 +01:00
Johannes Zellner 101a44affd Add authorized_keys.sh 2017-03-07 15:16:18 +01:00
Johannes Zellner 7995c664ed Add shell.sudoSync() 2017-03-07 15:14:37 +01:00
Johannes Zellner 6023c0e5dc Ensure the authorized_file permissions are correct 2017-03-07 14:39:14 +01:00
Johannes Zellner d49d76c1ee add ssh route tests and fixup the code accordingly 2017-03-07 14:12:25 +01:00
Johannes Zellner 77ef212daa Add SSH authorized_keys routes 2017-03-07 13:16:28 +01:00
Johannes Zellner 7aa80193c0 Add more changes 2017-03-06 10:47:36 +01:00
Johannes Zellner 5632c74556 Add isadmin ldap attribute
Fixes #241
2017-03-06 10:45:50 +01:00
Girish Ramakrishnan 7a08745af1 doc: add the 20gb requirement 2017-03-05 18:31:31 -08:00
Girish Ramakrishnan d9ba0858c7 Add 0.103.1 changes 2017-03-03 09:42:31 -08:00
Johannes Zellner 617e51d294 Adjust the oom notification email 2017-03-03 11:04:48 +01:00
Johannes Zellner c07d322fff Do not send ldap records for users without a username set
If an app relies on the attribute to be set, apps like owncloud would
fail internally.
2017-03-03 10:18:38 +01:00
Girish Ramakrishnan 9b8fa8a772 doc: sso 2017-03-02 15:15:15 -08:00
Girish Ramakrishnan c351242af7 lie about the time if it is ahead of us
Fixes #247
2017-03-02 14:34:18 -08:00
Johannes Zellner 55245557f5 Use the new app login event in the webadmin
Part of #247
2017-03-02 17:15:01 +01:00
Johannes Zellner ee1cef3ee8 Add new event type for app mailbox ldap login 2017-03-02 17:13:19 +01:00
Girish Ramakrishnan 5d51a7178f domain migrate: Add text that subdomains are not supported 2017-03-01 15:45:37 -08:00
Girish Ramakrishnan 9d52397bcc Move dhparam creation
Now that all cloudrons have the dhparams file, we can generate this
*after* restoring from backup and if required.
2017-03-01 15:25:20 -08:00
Girish Ramakrishnan 5098fbe061 Version 0.103.0 changes 2017-03-01 13:08:49 -08:00
Girish Ramakrishnan 7062aa4ac7 use test image 19.0.1 2017-02-28 20:21:02 -08:00
Girish Ramakrishnan d6fec4f2b9 alertsTo must be an array 2017-02-28 18:17:17 -08:00
Girish Ramakrishnan 86ef462c76 doc: add email/recvmail to allowed addon keys 2017-02-27 06:51:54 -08:00
Girish Ramakrishnan c76e7a3f63 randomize the cn in ip based cert
Fixes #224
2017-02-25 15:38:15 -08:00
Girish Ramakrishnan 2516a08659 remove reference to npm-demo from manifest 2017-02-25 13:36:27 -08:00
Girish Ramakrishnan 562fe30333 Update cloudron-manifestformat
adds the upcoming tls addon
2017-02-24 22:13:28 -08:00
Girish Ramakrishnan 4e0eed4bb2 make tests pass 2017-02-24 21:48:38 -08:00
Girish Ramakrishnan b604caec72 Get rid of x509 module
This is the last of the "native" modules. These modules take forever
to rebuild in low memory machines
2017-02-24 21:01:48 -08:00
Girish Ramakrishnan 6b409e9089 Do not send crash logs to support in self-hosted case
Fixes #242
2017-02-24 10:40:51 -08:00
Girish Ramakrishnan 015d434358 remove unused require 2017-02-24 10:39:03 -08:00
Girish Ramakrishnan c8e448cb84 Remove support@cloudron.io in app died mails
part of #242
2017-02-24 10:36:48 -08:00
Girish Ramakrishnan 03924be491 self-hosted: do not cc support for bounce mails from apps
part of #242
2017-02-24 10:34:07 -08:00
Girish Ramakrishnan 2729cecf4a self-hosting: remove support@cloudron.io frmo oom mails, cert renewal and backup failure mails
Part of #242
2017-02-24 10:25:20 -08:00
Girish Ramakrishnan 32e2377828 sysinfo: getIp -> getPublicIp 2017-02-23 22:03:48 -08:00
Girish Ramakrishnan fdb8139b03 createAMI: better help text 2017-02-23 15:44:56 -08:00
Girish Ramakrishnan 4b25c8a5ad Add 0.102.1 changes 2017-02-23 11:08:15 -08:00
Girish Ramakrishnan ae930a7fe8 dns setup: fix wording a bit 2017-02-23 10:57:05 -08:00
Johannes Zellner 3b9144ba4d Alter the backups.dependsOn field to store as TEXT
Fixes #239
2017-02-23 17:56:34 +01:00
Johannes Zellner be6ea3d4c1 Add rosehosting to selfhosting docs 2017-02-22 16:02:03 +01:00
Girish Ramakrishnan a2983e58b5 doc: typo 2017-02-21 11:24:25 -08:00
Girish Ramakrishnan a99e86a5df doc: fix wording on base image a bit 2017-02-21 11:16:10 -08:00
Girish Ramakrishnan 906ad80069 Add terms link 2017-02-20 15:59:40 -08:00
Girish Ramakrishnan ac65f765e5 doc: emphasize the traffic mgmt bit 2017-02-20 14:58:27 -08:00
Girish Ramakrishnan c5bfe82315 more 0.102.0 changes 2017-02-20 14:13:53 -08:00
Girish Ramakrishnan 7035b3c18a Fix issue where redis is unable to write on re-configure
The configure code path now ensures the volume which ends up
changing the ownership of the data directory. This means that the
redis container which is still running cannot write anymore
when it is re-created as part of setupAddons().

Just change ownership of top level directory. The subdirectores
like data/ redis/ are owned by containers which will chown
accordingly.
2017-02-20 13:32:05 -08:00
Girish Ramakrishnan 2108c61d97 Send machine info as part of alive status 2017-02-20 13:13:25 -08:00
Johannes Zellner 2bdbb47286 Fix crash when a user does not yet have an username 2017-02-20 21:59:16 +01:00
Johannes Zellner 333b8970b8 Add rosehosting afiliate link 2017-02-20 14:42:22 +01:00
Girish Ramakrishnan 5673cfe2be bump version 2017-02-19 21:48:33 -08:00
Girish Ramakrishnan 4429239dbc Fix debug 2017-02-19 20:30:35 -08:00
Girish Ramakrishnan b6ab9aa9f5 Add 0.102.0 changes 2017-02-19 17:22:52 -08:00
Girish Ramakrishnan 84bde6327f graphs: Better disk name matching
For some reason, docker devices are collected in collectd stats (despite
us collecting only ext4 and btrfs devices). They have the patter *docker*.

Fixes #222
2017-02-19 15:53:18 -08:00
Girish Ramakrishnan d6f49eb54f Remove _docker addon
this was a highly experimental code path from the past
2017-02-19 13:44:55 -08:00
Johannes Zellner 3c8c5e158b Send cloudron time zone with the backendSettings 2017-02-19 22:47:36 +01:00
Girish Ramakrishnan b3045b796f Configure dialog becomes 'repair' in errored state
Fixes #228
2017-02-18 13:17:46 -08:00
Girish Ramakrishnan c0febacc30 Remove configureLink
postInstallMessage already has this information
2017-02-18 12:52:47 -08:00
Johannes Zellner f8ada91dc5 Add rosehosting provider 2017-02-18 12:01:49 +01:00
Johannes Zellner d0e2ce9a9e Support Linode 1GB instance with cloudron-setup 2017-02-18 12:00:26 +01:00
Girish Ramakrishnan e157608992 doc: add note on memory limit 2017-02-17 13:47:19 -08:00
Girish Ramakrishnan 8dbe0ddaf3 doc: add note about incoming email 2017-02-17 13:01:23 -08:00
Girish Ramakrishnan b0cb18539c doc: add note to keep all ports open 2017-02-17 12:58:08 -08:00
Girish Ramakrishnan 97b6d76694 Explain certificate renewal error a bit more
Fixes #225
2017-02-17 10:41:33 -08:00
Girish Ramakrishnan 9de6c8ee2b doc: expand provider argument 2017-02-17 10:29:40 -08:00
Johannes Zellner cd28b1106b Only create app subvolume if it does not exist
Fixes #227
2017-02-17 15:15:50 +01:00
Johannes Zellner b3a5dafee0 Ensure we download docker images and have an app data volume on configure
Part of #227
2017-02-17 15:00:58 +01:00
Johannes Zellner eb4ab8defd Change cert CN from 'localhost' to 'cloudron'
Apparently localhost is special and triggerd a strange behavior in
firefox. Fixes #224
2017-02-17 14:05:21 +01:00
Girish Ramakrishnan 639744e9cb async.every usage has changed 2017-02-16 20:20:46 -08:00
Girish Ramakrishnan 6a942ab27a Use latest async for Inifinity retry to work 2017-02-16 19:22:07 -08:00
Girish Ramakrishnan 278f1d6d24 use curl with reconnect 2017-02-16 17:32:44 -08:00
Girish Ramakrishnan 563eeca1a9 Use the capture match length 2017-02-16 15:32:46 -08:00
Girish Ramakrishnan 7a9c954646 use ec2 sysinfo backend for lightsail 2017-02-16 14:47:16 -08:00
Johannes Zellner d768c36afb use generic sysinfo backend as fallback 2017-02-16 23:20:15 +01:00
Johannes Zellner 36ae3b267d Use better vultr referral link 2017-02-16 22:52:08 +01:00
Girish Ramakrishnan cd60f394d3 Use 1gb droplet (else docker ooms) 2017-02-16 11:52:25 -08:00
Johannes Zellner 9aba90a6f7 Show error message if subdomain was entered in setupdns view 2017-02-16 20:08:13 +01:00
Girish Ramakrishnan 68a8155f49 skip redis addon incremental update
Part of #223
2017-02-16 10:31:02 -08:00
Girish Ramakrishnan 16695fd4ec remove 0.9.0 2017-02-16 09:25:17 -08:00
Girish Ramakrishnan 9b6c6dc709 doc: base image 0.10.0 2017-02-16 09:20:27 -08:00
Girish Ramakrishnan 7923ed4f0d 0.101.0 changes 2017-02-15 23:31:28 -08:00
Girish Ramakrishnan 0b3d1c855c get the user before updating it
updating a non-existent user ends up creating a new mailbox
2017-02-15 23:19:56 -08:00
Girish Ramakrishnan d8273719d2 more robust detection and injection of SPF record
Fixes #210
2017-02-15 23:03:56 -08:00
Girish Ramakrishnan c6d2c39ff7 add azure 2017-02-15 20:10:33 -08:00
Girish Ramakrishnan 6960afdf0b Add more providers for stats 2017-02-15 15:49:00 -08:00
Girish Ramakrishnan 3a5000ab1d Detect loop support on linode correctly
We don't need any of the loop logic since it seems scaleway
also supports automatically this now
2017-02-15 15:40:19 -08:00
Girish Ramakrishnan 98951bab9e Store data args in file just in case installer fails 2017-02-15 14:27:51 -08:00
Girish Ramakrishnan 96fc3b8612 doc: pass --domain for old upgades to work 2017-02-15 11:59:55 -08:00
Girish Ramakrishnan 2b345b6c2d doc: Add note on <= 0.94.0 upgrades 2017-02-15 11:43:56 -08:00
Girish Ramakrishnan 504662b466 acme: link url is absolute in le-staging
Part of #217
2017-02-15 10:40:05 -08:00
Girish Ramakrishnan f56e6edbe4 use subdomains.waitForDns in mailer 2017-02-15 10:16:26 -08:00
Girish Ramakrishnan 191b84d389 Make value a regexp 2017-02-15 10:16:23 -08:00
Girish Ramakrishnan 8a4350d22e upsert already returns a SubdomainError 2017-02-14 22:29:33 -08:00
Girish Ramakrishnan cc6dae0f9e check if ns is set to DO nameservers 2017-02-14 22:27:27 -08:00
Girish Ramakrishnan 58528450e2 dns: Handle 422 errors in DO backend
Fixes #214
2017-02-14 20:51:44 -08:00
Girish Ramakrishnan ebf3559e60 Assume mailbox already exists 2017-02-14 15:42:38 -08:00
Girish Ramakrishnan 57d20b2b32 Assume mailbox already exists 2017-02-14 15:32:56 -08:00
Girish Ramakrishnan fd27240b26 delete user's old mailbox
we don't really support username change. this is only done for
completness.
2017-02-14 15:16:08 -08:00
Girish Ramakrishnan cad69d335c Fix result offset 2017-02-14 14:37:58 -08:00
Girish Ramakrishnan 1f08cca355 Add some newlines 2017-02-14 14:30:54 -08:00
Girish Ramakrishnan 7f4f525551 dhparams.pem must be part of backup 2017-02-14 14:12:03 -08:00
Girish Ramakrishnan b0037b6141 Update infra images to use latest base image 2017-02-14 12:23:17 -08:00
Girish Ramakrishnan 7956c8f58d use latest mysql 2017-02-14 11:27:48 -08:00
Girish Ramakrishnan 330c9054b4 add/del/update user mailbox as part of transaction 2017-02-14 10:42:32 -08:00
Girish Ramakrishnan d444d8552e add/del group mailbox as part of transaction 2017-02-14 09:54:52 -08:00
Girish Ramakrishnan 595bf583c7 delete mailbox as part of transaction 2017-02-13 15:19:17 -08:00
Girish Ramakrishnan 3386b99a29 fromEmail -> mailboxName 2017-02-13 15:15:07 -08:00
Girish Ramakrishnan 5fd667cdaf manual is not recommended 2017-02-13 11:20:07 -08:00
Johannes Zellner 4217db9e18 Ensure we don't crash if domain is not a string
Fixes #219
2017-02-13 13:21:25 +01:00
Johannes Zellner b4717e2edb Generating the dhparams.pem does not only apply to updates 2017-02-13 10:53:08 +01:00
Johannes Zellner 1d5465f21e Update the ssl ciphers and add dhparams.pem
Fixes #218
2017-02-13 00:28:22 +01:00
Johannes Zellner 2f1998fa67 Fix typo in cloudron-setup 2017-02-12 20:48:36 +01:00
Girish Ramakrishnan a7e998c030 Add new base image 2017-02-10 09:15:47 -08:00
Johannes Zellner 8cc15726ec Prevent the domain input from accepting trailing dots 2017-02-10 11:18:44 +01:00
Johannes Zellner 62e59868b4 Use the whole fontawesome package including fonts
The css file sources fonts relative to itself, so we need to include the
font files in our distribution as well.

Fixes #209
2017-02-10 10:53:32 +01:00
Girish Ramakrishnan a64027f4af Add PTR verification link 2017-02-09 19:17:24 -08:00
Girish Ramakrishnan f5a02930ec Use local bootstrap 3.3.7
We have 2 copies of bootstrap now. Just keeping both to be safe.
2017-02-09 14:37:44 -08:00
Girish Ramakrishnan 530ca20ee2 Use local font-awesome.min.css
Fixes #209
2017-02-09 14:37:44 -08:00
Girish Ramakrishnan f3b84ece3d doc: say what Encryption key is 2017-02-09 13:21:52 -08:00
Girish Ramakrishnan ca2d5957e4 Add canada and london to backup regions
Fixes #208
2017-02-09 12:59:13 -08:00
Girish Ramakrishnan 7837214276 Second Level -> Subdomain of public suffix list 2017-02-09 09:04:24 -08:00
Johannes Zellner 994202ca94 Use angular-tldjs for domain validation in certs view 2017-02-09 17:28:48 +01:00
Johannes Zellner ff7ceb1442 remove domain-validator directive
we will replace with angular-tldjs
2017-02-09 17:27:20 +01:00
Johannes Zellner 56545b7f41 Use check-tld directive for domain validation 2017-02-09 17:25:57 +01:00
Johannes Zellner 586e78dfea Apply manual fixes to angular-tld.js to support our use-case 2017-02-09 17:25:37 +01:00
Johannes Zellner 92ede4c242 Make the tld angular directive available in the main view and setupdns 2017-02-09 16:56:32 +01:00
Johannes Zellner 5ca2c2d564 Add angular-tld and its dependencies 2017-02-09 16:56:15 +01:00
Girish Ramakrishnan 9692aa3c08 Better error handling of unpurchase errors 2017-02-08 18:55:41 -08:00
Girish Ramakrishnan 10ad1028ae 0.100.1 changes 2017-02-08 15:14:14 -08:00
Johannes Zellner 7155856b08 Allocate the mailbox db record for apps in a transaction with appdb.add() 2017-02-08 23:52:14 +01:00
Girish Ramakrishnan 69aa771d44 Fix dkim dns crash
Fixes #207
2017-02-08 14:02:30 -08:00
Girish Ramakrishnan d164b5ae3a docs: add ptr links 2017-02-08 11:04:00 -08:00
Girish Ramakrishnan b34d09f547 ldap: Fix crash if displayName is empty and username is null 2017-02-08 10:13:50 -08:00
Girish Ramakrishnan 9e2850ffad setup: do not restart mysql unnecessarily 2017-02-08 07:53:55 -08:00
Johannes Zellner 480cface63 Do not crash if we did not receive a dmarc txt record 2017-02-08 16:55:08 +01:00
Girish Ramakrishnan 85aba589b8 Add hack to send heartbeat only after a minute of server running 2017-02-07 20:25:30 -08:00
Girish Ramakrishnan e890140aa9 Hold off sending heartbeat until the server is ready 2017-02-07 16:14:51 -08:00
Girish Ramakrishnan 53d56ef3a0 console.error -> debug 2017-02-07 10:48:51 -08:00
Girish Ramakrishnan b91674799b Create/destroy event listeners
mocha loads all the tests in same process. This means that when
we start a new test, the old state still persists. For event
listeners, this means that they get multiple duplicate event handlers.
2017-02-07 10:30:52 -08:00
Girish Ramakrishnan 4bb864e2ac use debug() instead
the tests are spewing out logs like crazy
2017-02-07 09:18:45 -08:00
Johannes Zellner 7db091525e Do not reboot the server on AMI creation
This will anyways happen once a new EC2 instance is created from the ami
and this ensures we do not encounter an SSH disconnect error when
running the cloudron-setup script during image creation
2017-02-07 12:49:28 +01:00
Johannes Zellner 695923ed75 cloudron-setup: support --skip-reboot for image creation 2017-02-07 12:49:28 +01:00
Johannes Zellner 1b43ccca6f Use new db-migrate which allows to specify the db backend
We use only mysql, so updating this means a lot of unused db backends
like sqlite do not need to be built with gyp anymore.
Note that this version is not yet released as stable, but works fine for
us. The outstanding issues are not related to our use-case from what I
can tell.

Fixes #82
2017-02-07 12:49:28 +01:00
Girish Ramakrishnan 96a0bad149 generate dkim keys in tests
move out dkim creation code that the tests require
2017-02-07 01:32:50 -08:00
Girish Ramakrishnan 243ade15e1 tests: restore aws.route53 mock 2017-02-07 01:32:34 -08:00
Girish Ramakrishnan 9d3cf990d1 Fix app test 2017-02-07 00:45:24 -08:00
Girish Ramakrishnan 02bcff2223 set isCustomDomain to true by default
CaaS is an exception and not the norm
2017-02-06 23:58:06 -08:00
Girish Ramakrishnan 8f388c86a6 do not unlink config file in test mode
this was incredibly hard to debug
2017-02-06 22:39:22 -08:00
Girish Ramakrishnan 8dc929f0ff Fix update checker test 2017-02-06 16:33:55 -08:00
Girish Ramakrishnan 509bd7e79b Make settings-test pass 2017-02-06 16:02:30 -08:00
Girish Ramakrishnan 19c665d747 docker daemon is deprecated 2017-02-06 11:33:10 -08:00
Girish Ramakrishnan cb09086ae8 Add dmsetup required by docker 2017-02-06 11:32:08 -08:00
Johannes Zellner fa915d0b23 Check for activated instead of fqdn to redirect to setup screens 2017-02-03 16:28:11 -08:00
Girish Ramakrishnan a383f01406 ami: wait for ssh as cloudron-setup reboots server 2017-02-03 11:26:56 -08:00
Girish Ramakrishnan 1a46e80403 remove .sh extension 2017-02-03 10:50:32 -08:00
Girish Ramakrishnan e8cd230c12 ami: remove ssh keys and fix subnet 2017-02-03 10:32:22 -08:00
Girish Ramakrishnan 0711dc2c5a createAMIImage: Add --region 2017-02-02 23:37:24 -08:00
Girish Ramakrishnan 486e72457d remove minlength for username 2017-02-02 16:09:07 -08:00
Girish Ramakrishnan 450e017bdb 0.100.0 changes 2017-02-02 15:43:16 -08:00
Girish Ramakrishnan c6d9cfc0d7 Passing IP never worked 2017-02-02 15:33:19 -08:00
Girish Ramakrishnan a0b073d881 Show DNS warning for manual/noop only 2017-02-02 14:43:34 -08:00
Girish Ramakrishnan 4dde16f987 Fix wording 2017-02-02 14:28:23 -08:00
Girish Ramakrishnan f7d2e262f4 Always fill spf record 2017-02-02 14:20:25 -08:00
Girish Ramakrishnan 34fedb5835 check spf and dkim all the time 2017-02-02 14:00:13 -08:00
Girish Ramakrishnan ff491be976 Display SPF/DKIM/PTR records for manual and noop backends 2017-02-02 13:58:49 -08:00
Girish Ramakrishnan 7635482191 Query via unbound
The timeout applies to each server. This resulted in us frequently
getting timeout out when we have more than one name server.
2017-02-02 13:58:49 -08:00
Girish Ramakrishnan b23001e43f better error log 2017-02-02 13:58:49 -08:00
Girish Ramakrishnan 06c8e8f0cb Query dns in parallel 2017-02-02 13:58:49 -08:00
Girish Ramakrishnan ce2cd00fbf Fix crash when no MX record is found 2017-02-02 13:58:49 -08:00
Johannes Zellner 651af185c8 Restart the droplet after installation for good measure
This is then in sync with selfhosting and ensures the init startup
sequence is in order, since the setup on its own creates unit files
which should run prior to services already running.

This hopefully fixes the mysql disconnect issues.
2017-02-02 11:24:49 -08:00
Girish Ramakrishnan 6951383ae0 Remove text-danger class in setupdns 2017-02-02 11:07:26 -08:00
Girish Ramakrishnan 37596e89b4 Fix display of info text in dns dialog 2017-02-02 11:05:56 -08:00
Girish Ramakrishnan 711fe37dad Add note on dnsRecordId 2017-02-02 10:43:04 -08:00
Girish Ramakrishnan 7fee3d0da0 Do not rely on dnsRecordId 2017-02-02 10:40:10 -08:00
Girish Ramakrishnan 45a61e9541 refreshDNS must always overwrite dns entries
dnsRecordId is mostly obsolete
2017-02-02 10:32:25 -08:00
Girish Ramakrishnan bd0be2affc No username implies no aliases 2017-02-02 01:22:44 -08:00
Girish Ramakrishnan 7812c0e5c2 Fix username and groupname min length 2017-02-02 01:16:32 -08:00
Girish Ramakrishnan 7efb6d60bc Allow usernames and groupnames of length 1
Fixes #204
2017-02-02 01:02:51 -08:00
Girish Ramakrishnan cd31e12bec Do not includeSubdomains in HSTS
This prevents one from redirecting to some http-only subdomain.
For example, surfer in naked domain redirects to www subdomain
(which is on github pages...)
2017-02-02 00:05:56 -08:00
Girish Ramakrishnan 87755c6097 ignore errors and continue 2017-02-01 23:38:06 -08:00
Girish Ramakrishnan 73f56efe2c Fix typo 2017-02-01 23:25:13 -08:00
Girish Ramakrishnan 20eaa60a97 clear timeout 2017-02-01 23:20:11 -08:00
Girish Ramakrishnan b80f0082e9 subdomain -> domain 2017-02-01 23:06:41 -08:00
Girish Ramakrishnan 1ff800a842 Display mx, dmarc, ptr status
Fixes #169
2017-02-01 22:59:06 -08:00
Girish Ramakrishnan 5b0abb1b17 re-setup DNS when the dns config changes 2017-02-01 14:34:57 -08:00
Girish Ramakrishnan 178aa4794a cloudron-setup: Add source-url 2017-02-01 14:11:50 -08:00
Girish Ramakrishnan 76583cb2fa createReleaseTarball: remove no-upload argument
We will put the upload in the release script
2017-02-01 13:41:27 -08:00
Girish Ramakrishnan aa484dc5b4 Add 0.99.1 changelog 2017-01-31 18:09:07 -08:00
249 changed files with 15787 additions and 7601 deletions
+149 -1
View File
@@ -736,4 +736,152 @@
* Cleanup graphs UI
* Polish webadmin UI
* Fix bug where hard disk size was detected incorrectly
* Use overlay2 as docker storage backend for scaleway
[0.99.1]
* Fix bug with duplicate nginx configs
[0.100.0]
* Improve DNS notifications for email
* Do not enable HSTS for subdomains
[0.100.1]
* Fix crash when fetching mail records
* Fix crash in LDAP server when username and displayName are empty
[0.101.0]
* New base image 0.10.0
* Better error handling of unpurchase errors
* Validate that cloudron domain name is a subdomain of public suffic list
* Add canada and london to S3 backup regions
* Bundle Font Awesome as part of webadmin
* Fix crash in custom certiicate validation
* Get A+ rating in SSL Check
* More robust detection and injection of SPF record
* Add azure, lightsail, linode, ovh, vultr to provider list
[0.102.0]
* Fix issue where SPF record check was only done 5 times (updated 'async')
* Make auto-generated self-signed cert load quickly on Firefox
* Ensure we download docker images and have an app data volume on app re-configure
* Improve certificate renewal erorr message
* Fix disk usage graph
* Show Repair UI for errored apps
[0.102.1]
* Add terms link when signing up for Cloudron.io account
* Fix issue where Cloudrons with many apps (> 35) were unable to backup
* Improve wording of DNS Setup
[0.103.0]
* Do not send crash logs and other notifications to support@cloudron.io for self-hosted instances
* Make auto-generated self-signed cert load quickly on Firefox (take 2)
[0.104.0]
* (mail) Fix crash when sending mails to groups with just 1 user
* (ldap) Add isadmin attribute to better map users in apps
* (ldap) Hide users which have not yet set a username in ldap searches
* (core) Add SSH authorized_keys management
* (core) Add additional security related headers to the nginx reverse proxy
* (ui) Add remote SSH support option
* (ui) Fix eventlog display
* (ui) Fix CNAME setup information
[0.105.0]
* Always show email related checks
* Show outbound SMTP port 25 status
* Hide remote feature for normal users
* Only list users via ldap searches who have access to the app
* Fix installation issue on servers with a differente locale set
[0.105.1]
* Fix crash when setupToken is not provided in activate API
* Add inline Docker GPG key
* Re-download icon when repairing app
* Fix issue where pre-installed apps were not installed correctly
* Fix issue where new cloudrons could not be activated
[0.106.0]
* (mail) Fix email forwarding to external domains
* (mail) Set maximum email size to 25MB
* Remove SimpleAuth addon
[0.107.0]
* Support CSP for webinterface and OAuth views
* (mail) Fix issue where Cloudron is only used to send emails
[0.108.0]
* Redirect to /setupdns.html when restoring
* Fix setting custom avatar
* Do not allocate more than 4GB swap
* Generate real passwords for sendmail/recvmail addons
* Rate limit all authentication routes to prevent password brute force
* Generate 128 byte password for MySQL multi-db addon
[0.109.0]
* Add Referrer-policy
* Add tooltip for admin email field explaining it is local & private
* Verify AMI instance id during DNS setup instead of admin account setup
* Split platform and app data folders and get rid of btrfs volumes
[0.110.0]
* Fix disk usage graphs
* Add --data-dir to cloudron-setup that allows customizing data location
* Add UI to restore from any app backup
* (mysql) Use utf8mb4 encoding for databases and backups
* Allow installing a new app from a backup
* Fix download of large files (> 1GB)
* Fix app backup regression
[0.120.0]
* Update Docker to 17.03.1-ce
* Rework backup backend logic
* Add UI to download logs
* Fix crash when checking mail dns settings
* Allow backup retention duration to be configured
* Add minio backend for backups
* Fix issue where Cloudron's with errored apps won't backup when using fs backend
* Fix DNS check issue where PTR records was read from hosts file
[0.120.1]
* Fix managed Cloudron backup cleanup
[0.130.0]
* Use Cloudron DNS server only for containers created by Cloudron
* Make Cloudron always start even if DNS credentials are invalid
* Show warning if DNS configuration is not valid
* Drop the '.enc' extension for non-encrypted backups
* Do not encrypt backups when the backup key is empty
* Do a multipart S3 download for slow internet connections
* Support naked domains as external location
[0.130.1]
* Fix app configure dialog regression
[0.130.2]
* Fix app configure dialog regression and dns setup screen
[0.130.3]
* Show error message if setup fails due to reserved username
* (security) Do not print password in the logs in the configure route
* Fix restore of unencrypted backups
* Fix bug where FS backups have incorrect extension for unencrypted backups
[0.140.0]
* HTTP2 support
* Condense the dns checks in the settings view
* Document new app store submission guidelines
[0.150.0]
* Disable dnsmasq on OVH
* Scale redis memory based on the app's memory limit
* (security) Do not print the ssl cert in debug logs
* Add noop storage backend to temporarily disable backups
* Replace native-dns module with dig to prevent spurious crashes
* Cleanup unfinished and errored backups
* Set a timelimit of 4 hours for backup to finish
[0.160.0]
* Fix disk graphs when using device mapper
* Prevent email view from flickering
* Prepare for 1.0
+7 -3
View File
@@ -46,10 +46,14 @@ Try our demo at https://my-demo.cloudron.me (username: cloudron password: cloudr
## Installing
You can install the Cloudron platform on your own server or get a managed server
from cloudron.io.
from cloudron.io. In either case, the Cloudron platform will keep your server and
apps up-to-date and secure.
* [Selfhosting](https://cloudron.io/references/selfhosting.html)
* [Managed Hosting](https://cloudron.io/pricing.html)
* [Selfhosting](https://cloudron.io/references/selfhosting.html) - [Pricing](https://cloudron.io/pricing.html)
* [Managed Hosting](https://cloudron.io/managed.html)
The wiki has instructions on how you can install and update the Cloudron and the
apps from source.
## Documentation
+51 -23
View File
@@ -10,9 +10,7 @@ readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")"/.. && pwd)"
export JSON="${SOURCE_DIR}/node_modules/.bin/json"
IMAGE_ID="ami-5aee2235" # ubuntu 16.04 eu-central-1
INSTANCE_TYPE="t2.micro"
SECURITY_GROUP="sg-19f5a770" # everything open on eu-central-1
BLOCK_DEVICE="DeviceName=/dev/sda1,Ebs={VolumeSize=20,DeleteOnTermination=true,VolumeType=gp2}"
SSH_KEY_NAME="id_rsa_yellowtent"
@@ -22,8 +20,9 @@ server_id=""
server_ip=""
destroy_server="yes"
deploy_env="prod"
image_id=""
args=$(getopt -o "" -l "revision:,name:,no-destroy,env:" -n "$0" -- "$@")
args=$(getopt -o "" -l "revision:,name:,no-destroy,env:,region:" -n "$0" -- "$@")
eval set -- "${args}"
while true; do
@@ -32,19 +31,35 @@ while true; do
--revision) revision="$2"; shift 2;;
--name) ami_name="$2"; shift 2;;
--no-destroy) destroy_server="no"; shift 2;;
--region)
case "$2" in
"us-east-1")
image_id="ami-6edd3078"
security_group="sg-a5e17fd9"
subnet_id="subnet-b8fbc0f1"
;;
"eu-central-1")
image_id="ami-5aee2235"
security_group="sg-19f5a770" # everything open on eu-central-1
subnet_id=""
;;
*)
echo "Unknown aws region $2"
exit 1
;;
esac
export AWS_DEFAULT_REGION="$2" # used by the aws cli tool
shift 2
;;
--) break;;
*) echo "Unknown option $1"; exit 1;;
esac
done
export AWS_DEFAULT_REGION="eu-central-1" # we have to use us-east-1 to publish
# TODO fix this
export AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY}"
export AWS_SECRET_ACCESS_KEY="${AWS_ACCESS_SECRET}"
echo "=> Creating AMI"
readonly ssh_keys="${HOME}/.ssh/id_rsa_yellowtent"
readonly SSH="ssh -o IdentitiesOnly=yes -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i ${ssh_keys}"
@@ -53,6 +68,11 @@ if [[ ! -f "${ssh_keys}" ]]; then
exit 1
fi
if [[ -z "${image_id}" ]]; then
echo "--region is required (us-east-1 or eu-central-1)"
exit 1
fi
function get_pretty_revision() {
local git_rev="$1"
local sha1=$(git rev-parse --short "${git_rev}" 2>/dev/null)
@@ -60,21 +80,34 @@ function get_pretty_revision() {
echo "${sha1}"
}
function wait_for_ssh() {
echo "=> Waiting for ssh connection"
while true; do
echo -n "."
if $SSH ubuntu@${server_ip} echo "hello"; then
echo ""
break
fi
sleep 5
done
}
now=$(date "+%Y-%m-%d-%H%M%S")
pretty_revision=$(get_pretty_revision "${revision}")
if [[ -z "${ami_name}" ]]; then
# if you change this, change the regexp is appstore/janitor.js
ami_name="box-${deploy_env}-${pretty_revision}-${now}" # remove slashes
ami_name="box-${deploy_env}-${pretty_revision}-${now}"
fi
echo "=> Create EC2 instance"
id=$(aws ec2 run-instances --image-id "${IMAGE_ID}" --instance-type "${INSTANCE_TYPE}" --security-group-ids "${SECURITY_GROUP}" --block-device-mappings "${BLOCK_DEVICE}" --key-name "${SSH_KEY_NAME}"\
id=$(aws ec2 run-instances --image-id "${image_id}" --instance-type "${INSTANCE_TYPE}" --security-group-ids "${security_group}" --block-device-mappings "${BLOCK_DEVICE}" --key-name "${SSH_KEY_NAME}" --subnet-id "${subnet_id}" --associate-public-ip-address \
| $JSON Instances \
| $JSON 0.InstanceId)
[[ -z "$id" ]] && exit 1
echo "Instance created with ID $id"
echo "Instance created ID $id"
echo "=> Waiting for instance to get a public IP"
while true; do
@@ -93,17 +126,7 @@ done
echo "Got public IP ${server_ip}"
echo "=> Waiting for ssh connection"
while true; do
echo -n "."
if $SSH ubuntu@${server_ip} echo "hello"; then
echo ""
break
fi
sleep 5
done
wait_for_ssh
echo "=> Fetching cloudron-setup"
while true; do
@@ -118,7 +141,12 @@ while true; do
done
echo "=> Running cloudron-setup"
$SSH ubuntu@${server_ip} sudo /bin/bash "cloudron-setup" --env "${deploy_env}" --provider "ec2"
$SSH ubuntu@${server_ip} sudo /bin/bash "cloudron-setup" --env "${deploy_env}" --provider "ami" --skip-reboot
wait_for_ssh
echo "=> Removing ssh key"
$SSH ubuntu@${server_ip} sudo rm /home/ubuntu/.ssh/authorized_keys /root/.ssh/authorized_keys
echo "=> Creating AMI"
image_id=$(aws ec2 create-image --instance-id "${id}" --name "${ami_name}" | $JSON ImageId)
+1 -1
View File
@@ -31,7 +31,7 @@ function create_droplet() {
local image_region="sfo1"
local ubuntu_image_slug="ubuntu-16-04-x64"
local box_size="512mb"
local box_size="1gb"
local data="{\"name\":\"${box_name}\",\"size\":\"${box_size}\",\"region\":\"${image_region}\",\"image\":\"${ubuntu_image_slug}\",\"ssh_keys\":[ \"${ssh_key_id}\" ],\"backups\":false}"
+15 -7
View File
@@ -26,10 +26,10 @@ debconf-set-selections <<< 'mysql-server mysql-server/root_password_again passwo
apt-get -y install \
acl \
awscli \
btrfs-tools \
build-essential \
cron \
curl \
dmsetup \
iptables \
logrotate \
mysql-server-5.7 \
@@ -51,16 +51,16 @@ apt-get install -y python # Install python which is required for npm rebuild
# https://docs.docker.com/engine/installation/linux/ubuntulinux/
echo "==> Installing Docker"
apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main" > /etc/apt/sources.list.d/docker.list
apt-get -y update
# create systemd drop-in file
mkdir -p /etc/systemd/system/docker.service.d
echo -e "[Service]\nExecStart=\nExecStart=/usr/bin/docker daemon -H fd:// --log-driver=journald --exec-opt native.cgroupdriver=cgroupfs --storage-driver=devicemapper" > /etc/systemd/system/docker.service.d/cloudron.conf
echo -e "[Service]\nExecStart=\nExecStart=/usr/bin/dockerd -H fd:// --log-driver=journald --exec-opt native.cgroupdriver=cgroupfs --storage-driver=devicemapper" > /etc/systemd/system/docker.service.d/cloudron.conf
curl -sL https://download.docker.com/linux/ubuntu/dists/xenial/pool/stable/amd64/docker-ce_17.03.1~ce-0~ubuntu-xenial_amd64.deb -o /tmp/docker.deb
# apt install with install deps (as opposed to dpkg -i)
apt install -y /tmp/docker.deb
rm /tmp/docker.deb
apt-get -y --allow-downgrades install docker-engine=1.12.5-0~ubuntu-xenial # apt-cache madison docker-engine
apt-mark hold docker-engine # do not update docker
storage_driver=$(docker info | grep "Storage Driver" | sed 's/.*: //')
if [[ "${storage_driver}" != "devicemapper" ]]; then
echo "Docker is using "${storage_driver}" instead of devicemapper"
@@ -92,3 +92,11 @@ if ! apt-get install -y collectd collectd-utils; then
sed -e 's/^FQDNLookup true/FQDNLookup false/' -i /etc/collectd/collectd.conf
fi
# Disable bind for good measure (on online.net, kimsufi servers these are pre-installed and conflicts with unbound)
systemctl stop bind9 || true
systemctl disable bind9 || true
# on ovh images dnsmasq seems to run by default
systemctl stop dnsmasq || true
systemctl disable dnsmasq || true
+1 -5
View File
@@ -13,8 +13,7 @@ var appHealthMonitor = require('./src/apphealthmonitor.js'),
async = require('async'),
config = require('./src/config.js'),
ldap = require('./src/ldap.js'),
server = require('./src/server.js'),
simpleauth = require('./src/simpleauth.js');
server = require('./src/server.js');
console.log();
console.log('==========================================');
@@ -33,7 +32,6 @@ console.log();
async.series([
server.start,
ldap.start,
simpleauth.start,
appHealthMonitor.start,
], function (error) {
if (error) {
@@ -48,13 +46,11 @@ var NOOP_CALLBACK = function () { };
process.on('SIGINT', function () {
server.stop(NOOP_CALLBACK);
ldap.stop(NOOP_CALLBACK);
simpleauth.stop(NOOP_CALLBACK);
setTimeout(process.exit.bind(process), 3000);
});
process.on('SIGTERM', function () {
server.stop(NOOP_CALLBACK);
ldap.stop(NOOP_CALLBACK);
simpleauth.stop(NOOP_CALLBACK);
setTimeout(process.exit.bind(process), 3000);
});
+1 -66
View File
@@ -184,7 +184,7 @@ TokenURL = ${API_ORIGIN}/api/v1/oauth/token
The token obtained via OAuth has a restricted scope wherein they can only access the [profile API](/references/api.html#profile). This restriction
is so that apps cannot make undesired changes to the user's Cloudron.
We currently provide OAuth2 integration for Ruby [omniauth](https://github.com/cloudron-io/omniauth-cloudron) and Node.js [passport](https://github.com/cloudron-io/passport-cloudron).
We currently provide OAuth2 integration for Ruby [omniauth](https://git.cloudron.io/cloudron/omniauth-cloudron) and Node.js [passport](https://git.cloudron.io/cloudron/passport-cloudron).
## postgresql
@@ -317,68 +317,3 @@ cloudron exec
> swaks --server "${MAIL_SMTP_SERVER}" -p "${MAIL_SMTP_PORT}" --from "${MAIL_SMTP_USERNAME}@${MAIL_DOMAIN}" --body "Test mail from cloudron app at $(hostname -f)" --auth-user "${MAIL_SMTP_USERNAME}" --auth-password "${MAIL_SMTP_PASSWORD}"
```
## simpleauth
Simple Auth can be used for authenticating users with a HTTP request. This method of authentication is targeted
at applications, which for whatever reason can't use the ldap addon.
The response contains an `accessToken` which can then be used to access the [Cloudron API](/references/api.html).
Exported environment variables:
```
SIMPLE_AUTH_SERVER= # the simple auth HTTP server
SIMPLE_AUTH_PORT= # the simple auth server port
SIMPLE_AUTH_URL= # the simple auth server URL. same as "http://SIMPLE_AUTH_SERVER:SIMPLE_AUTH_PORT
SIMPLE_AUTH_CLIENT_ID # a client id for identifying the request originator with the auth server
```
This addons provides two REST APIs:
**POST /api/v1/login**
Request JSON body:
```
{
"username": "<username> or <email>",
"password": "<password>"
}
```
Response 200 with JSON body:
```
{
"accessToken": "<accessToken>",
"user": {
"id": "<userId>",
"username": "<username>",
"email": "<email>",
"admin": <admin boolean>,
"displayName": "<display name>"
}
}
```
**GET /api/v1/logout**
Request params:
```
?access_token=<accessToken>
```
Response 200 with JSON body:
```
{}
```
For debugging, [cloudron exec](https://www.npmjs.com/package/cloudron) can be used to run the `curl` tool within the context of the app:
```
cloudron exec
> USERNAME=<enter username>
> PASSWORD=<enter password>
> PAYLOAD="{\"clientId\":\"${SIMPLE_AUTH_CLIENT_ID}\", \"username\":\"${USERNAME}\", \"password\":\"${PASSWORD}\"}"
> curl -H "Content-Type: application/json" -X POST -d "${PAYLOAD}" "${SIMPLE_AUTH_ORIGIN}/api/v1/login"
```
+137 -13
View File
@@ -62,7 +62,7 @@ curl -H "Content-Type: application/json" -H "Authorization: Bearer <token>" http
## OAuth
OAuth authentication is meant to be used by apps. An app can get an OAuth token using the
[oauth](addons.html#oauth) or [simpleauth](addons.html#simpleauth) addon.
[oauth](addons.html#oauth) addon.
Tokens obtained via OAuth have a restricted scope wherein they can only access the user's profile.
This restriction is so that apps cannot make undesired changes to the user's Cloudron.
@@ -117,6 +117,7 @@ Request:
cert: <string>, // pem encoded TLS cert
key: <string>, // pem encoded TLS key
memoryLimit: <number>, // memory constraint in bytes
backupId: <string>, // initialize the app from this backup
altDomain: <string>, // alternate domain from which this app can be reached
xFrameOptions: <string> // set X-Frame-Options header, to control which websites can embed this app
}
@@ -153,6 +154,8 @@ If `altDomain` is set, the app can be accessed from `https://<altDomain>`.
`memoryLimit` is the maximum memory this app can use (in bytes) including swap. If set to 0, the app uses the `memoryLimit` value set in the manifest. If set to -1, the app gets unlimited memory.
If `backupId` is provided the app will be initialized with the data from the backup.
Read more about the options at [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options).
Response (200):
@@ -199,7 +202,8 @@ Response (200):
health: <enum>, // health of the application
location: <string>, // subdomain on which app is installed
fqdn: <string>, // the FQDN of this app
altDomain: <string> // alternate domain from which this app can be reached
altDomain: <string>, // alternate domain from which this app can be reached
cnameTarget: <string> || null, // If altDomain is set, this contains the CNAME location for the app
accessRestriction: null || { // list of users and groups who can access this application
users: [ ],
groups: [ ]
@@ -209,7 +213,8 @@ Response (200):
portBindings: { // mapping from application ports to public ports
},
iconUrl: <url>, // a relative url providing the icon
memoryLimit: <number> // memory constraint in bytes
memoryLimit: <number>, // memory constraint in bytes
sso: <boolean> // Enable single sign-on
}
```
@@ -257,6 +262,8 @@ is integrated with Cloudron Authentication.
`manifest` is the [application manifest](/references/manifest.html).
For apps that support optional single sign-on, the `sso` field can be used to disable Cloudron authentication. By default, single sign-on is enabled.
### List apps
GET `/api/v1/apps/:appId` <scope>admin</scope>
@@ -278,7 +285,8 @@ Response (200):
health: <enum>, // health of the application
location: <string>, // subdomain on which app is installed
fqdn: <string>, // the FQDN of this app
altDomain: <string> // alternate domain from which this app can be reached
altDomain: <string>, // alternate domain from which this app can be reached
cnameTarget: <string> || null, // If altDomain is set, this contains the CNAME location for the app
accessRestriction: null || { // list of users and groups who can access this application
users: [ ],
groups: [ ]
@@ -449,7 +457,7 @@ POST `/api/v1/apps/:appId/configure` <scope>admin</scope>
Re-configures an existing app with id `appId`.
Configuring an app won't preserve existing data. Cloudron apps are written in a way to support reconfiguring
Configuring an app preserves existing data. Cloudron apps are written in a way to support reconfiguring
any of the parameters listed below without loss of data.
Request:
@@ -654,6 +662,55 @@ curl -L <url> | openssl aes-256-cbc -d -pass "pass:$<backupKey>" | tar -zxf -
## Cloudron
### Activate the Cloudron
POST `/api/v1/cloudron/activate`
Activates the Cloudron with an admin username and password.
Request:
```
{
username: <string>, // the admin username
password: <string>, // the admin password
email: <email> // the admin email
}
```
Response (201):
```
{
"token": "771ee724a66aa557f95af06b4e6c27992f9230f6b1d65d5fbaa34cae9318d453",
"expires": 1490224113353
}
```
The `token` parameter can be used to make further API calls.
Curl example to activate the cloudron:
```
curl -X POST -H "Content-Type: application/json" -d '{"username": "girish", "password":"MySecret123#", "email": "girish@cloudron.io" }' https://my.cloudron.info/api/v1/cloudron/activate
```
### Check for updates
POST `/api/v1/check_for_updates` <scope>admin</scope>
Checks for any available updates for the Cloudron and the installed apps.
Response (200):
```
{
box: null|<object>, // object containing information about update
apps: { // update info (if any) for each app
<appid>: <object>,
...
}
}
```
### Update the Cloudron
POST `/api/v1/cloudron/update` <scope>admin</scope>
@@ -682,8 +739,9 @@ Gets information about an in-progress Cloudron update or backup.
`update` or `backup` is `null` when there is no such activity in progress.
```
Response (200):
```
{
update: null || { percent: <number>, message: <string> },
backup: null || { percent: <number>, message: <string> }
@@ -701,7 +759,6 @@ Response (200):
{
activated: <boolean>,
version: <semver>,
boxVersionsUrl: <url>, // Location of the Cloudron versions file to check for updates
apiServerOrigin: <url>, // Always https://api.cloudron.io
provider: <string>,
cloudronName: <string>
@@ -732,7 +789,6 @@ Response (200):
{
apiServerOrigin: <string>, // Always https://api.cloudron.io
webServerOrigin: <string>, // Always https://cloudron.io
isDev: <boolean>, // internal
fqdn: <fqdn>, // The FQDN
ip: <ip>, // The public IP
version: <semver>, // Current version
@@ -756,12 +812,50 @@ Response (200):
}
```
### Get disks
## Eventlog
GET `/api/v1/cloudron/disks` <scope>admin</scope>
Gets information on the disks being used on the Cloudron server.
```
Response (200):
{
boxDataDisk: <string>, // Disk used for storing box data
platformDataDisk: <string>, // Disk used for addon databases and email
appsDataDisk: <string> // Disk used for apps' local storage
}
```
### Get logs
GET `/api/v1/cloudron/logs` <scope>admin</scope>
Get the system logs.
The `lines` query parameter can be used to specify the number of log lines to download.
The `units` query parameters can be set to `box` or `mail` to get logs of specific units.
The response has `Content-Type` set to 'application/x-logs' and `Content-Disposition` set to
`attachment; filename="log.txt`.
Response(200):
```
Line delimited JSON.
{
realtimeTimestamp: <number>, // wallclock timestamp
monotonicTimestamp: <number>, // time passed since boot
message: [ <byte>,... ], // utf8 buffer
source: <process name> // source of this message
}
```
### List events
GET `/api/v1/eventlog` <scope>admin</scope>
GET `/api/v1/cloudron/eventlog` <scope>admin</scope>
Lists all the past events.
@@ -806,13 +900,13 @@ Response (200):
* user.remove
* user.update
`source` contains information on the originator of the action. For example, for user.login, this contains the IP address, the appId and the authType (ldap or simpleauth or oauth).
`source` contains information on the originator of the action. For example, for user.login, this contains the IP address, the appId and the authType (ldap or oauth).
`data` contains information on the event itself. For example, for user.login, this contains the userId that logged in. For app.install, it contains the manifest and location of the app that was installed.
To list all the app installation events:
```
curl -X GET -H 'Authorization: Bearer cb0463455a6606482be7956fc3abd53330ae23244e3492cda3914a2c5154c47e' https://my-demo.cloudron.me/api/v1/eventlog?action=app.install
curl -X GET -H 'Authorization: Bearer cb0463455a6606482be7956fc3abd53330ae23244e3492cda3914a2c5154c47e' https://my-demo.cloudron.me/api/v1/cloudron/eventlog?action=app.install
```
## Groups
@@ -968,6 +1062,36 @@ Response (204):
## Settings
### Get Appstore Config
GET `/api/v1/settings/appstore_config` <scope>admin</scope>
Response (200):
```
{
userId: <string>, // the appstore userId
token: <string>, // appstore token
cloudronId: <string> // cloudron id
}
```
### Set Appstore Config
POST `/api/v1/settings/appstore_config` <scope>admin</scope>
Sets the credentials used for the Cloudron Store.
Request:
```
{
userId: <string>, // the appstore userId
token: <string> // token from appstore
}
```
You can get the `userId` and `token` by sending a `/api/v1/login` POST request to `api.cloudron.io`
with the `email` and `password` fields set in the request.
### Get auto update pattern
GET `/api/v1/settings/autoupdate_pattern` <scope>admin</scope>
@@ -1116,7 +1240,7 @@ POST `/api/v1/settings/mail_config` <scope>admin</scope> <scope>internal</scope>
Sets the email configuration. The Cloudron has a built-in email server for users.
This configuration can be used to enable or disable the email server. Note that
the Cloudron will always be able to send email on behalf of apps, regardless of
the Cloudron will always be able to send email on behalf of apps, regardless of
this setting.
Request:
+11 -12
View File
@@ -1,25 +1,25 @@
# Introduction
The Cloudron platform is designed to easily install and run web applications.
The application architecture is designed to let the Cloudron take care of system
The application architecture is designed to let the Cloudron take care of system
operations like updates, backups, firewalls, domain management, certificate management
etc. This allows app developers to focus on their application logic instead of deployment.
At a high level, an application provides an `image` and a `manifest`. The image is simply
a docker image that is a bundle of the application code and it's dependencies. The manifest
a docker image that is a bundle of the application code and it's dependencies. The manifest
file specifies application runtime requirements like database type and authentication scheme.
It also provides meta information for display purposes in the [Cloudron Store](/appstore.html)
It also provides meta information for display purposes in the [Cloudron Store](/appstore.html)
like the title, icon and pricing.
Web applications like blogs, wikis, password managers, code hosting, document editing,
file syncers, notes, email, forums are a natural fit for the Cloudron. Decentralized "social"
Web applications like blogs, wikis, password managers, code hosting, document editing,
file syncers, notes, email, forums are a natural fit for the Cloudron. Decentralized "social"
networks are also good app candidates for the Cloudron.
# Image
Application images are created using [Docker](https://www.docker.io). Docker provides a way
to package (and containerize) the application as a filesystem which contains it's code, system libraries
and just about anything the app requires. This flexible approach allows the application to use just
to package (and containerize) the application as a filesystem which contains it's code, system libraries
and just about anything the app requires. This flexible approach allows the application to use just
about any language or framework.
Application images are instantiated as `containers`. Cloudron can run one or more isolated instances
@@ -77,12 +77,11 @@ Authentication strategies include OAuth 2.0, LDAP or Simple Auth. See the
Authorizing users is application specific and it is only authentication that is delegated to the
Cloudron.
# Cloudron Store
# Cloudron App Library
Cloudron Store provides a market place to publish and optionally monetize your app. Submitting to the
Cloudron Store enables any Cloudron user to discover, purchase and install your application with
a few clicks.
Cloudron App Library provides a market place to publish your app.
Submitting to the app library enables any Cloudron user to discover and install your application with a few clicks.
# What next?
* [Package an existing app for the Cloudron](/tutorials/packaging.html)
* [Package an existing app for the Cloudron](/tutorials/packaging.html)
-1
View File
@@ -29,7 +29,6 @@ Cloudron provides multiple authentication strategies.
* OAuth 2.0 provided by the [OAuth addon](/references/addons.html#oauth)
* LDAP provided by the [LDAP addon](/references/addons.html#ldap)
* Simple Auth provided by [Simple Auth addon](/references/addons.html#simpleauth)
# Choosing a strategy
+8 -8
View File
@@ -1,6 +1,6 @@
# Overview
The application's Dockerfile must specify the FROM base image to be `cloudron/base:0.9.0`.
The application's Dockerfile must specify the FROM base image to be `cloudron/base:0.10.0`.
The base image already contains most popular software packages including node, nginx, apache,
ruby, PHP. Using the base image greatly reduces the size of app images.
@@ -17,16 +17,16 @@ install it yourself.
* Apache 2.4.18
* Composer 1.2.0
* Go 1.5.4, 1.6.3
* Go 1.6.4, 1.7.5 (install under `/usr/local/go-<version>`)
* Gunicorn 19.4.5
* Java 1.8
* Maven 3.3.9
* Mongo 2.6.10
* MySQL Client 5.7.13
* MySQL Client 5.7.17
* nginx 1.10.0
* Node 0.10.40, 0.12.7, 4.2.6, 4.4.7 (installed under `/usr/local/node-<version>`) [more information](#node-js)
* Node 0.10.48, 0.12.18, 4.7.3, 6.9.5 (installed under `/usr/local/node-<version>`) [more information](#node-js)
* Perl 5.22.1
* PHP 7.0.8
* PHP 7.0.13
* Postgresql client 9.5.4
* Python 2.7.12
* Redis 3.0.6
@@ -41,16 +41,16 @@ The base image can be inspected by installing [Docker](https://docs.docker.com/i
Once installed, pull down the base image locally using the following command:
```
docker pull cloudron/base:0.9.0
docker pull cloudron/base:0.10.0
```
To inspect the base image:
```
docker run -ti cloudron/base:0.9.0 /bin/bash
docker run -ti cloudron/base:0.10.0 /bin/bash
```
*Note:* Please use `docker 1.9.0` or above to pull the base image. Doing otherwise results in a base
image with an incorrect image id. The image id of `cloudron/base:0.9.0` is `d038af182821`.
image with an incorrect image id. The image id of `cloudron/base:0.10.0` is `5ec8ca8525be`.
# The `cloudron` user
-93
View File
@@ -1,93 +0,0 @@
# Best practices
## Overview
This document explains the spirit of what makes a Cloudron app.
## No Setup
Cloudron apps do not show a setup screen after installation and should choose reasonable
defaults.
Databases, email configuration should be automatically picked up using [addons](/references/addons.html).
Admin role for the application can be detected dynamically using one of the [authentication](/references/authentication.html)
strategies.
## Image
The Dockerfile contains a specification for building an application image.
* Install any required software packages in the Dockerfile.
* Create static configuration files in the Dockerfile.
* Create symlinks to dynamic configuration files under `/run` in the Dockerfile.
* Docker supports restarting processes natively. Should your application crash, it will
be restarted automatically. If your application is a single process, you do not require
any process manager.
* The main process must handle `SIGTERM` and forward it as required to child processes. `bash`
does not automatically forward signals to child processes. For this reason, when using a startup
shell script, remember to use `exec <app>` as the last line. Doing so will replace bash with your
program and allows your program to handle signals as required.
* Use `supervisor`, `pm2` or any of the other process managers if you application has more
then one component. This excludes web servers like apache, nginx which can already manage their
children by themselves. Be sure to pick a process manager that forwards signals to child processes.
* Disable auto updates for apps. Updates must be triggered through the Cloudron Store. This allows the admin
to manage updates and downtime in a central location (the Cloudron Webadmin).
## File system
The Cloudron runs the application image as read-only. The app can only write to the following directories:
* `/tmp` - use this for temporary files.
* `/run` - use this for runtime configration and any dynamic data.
* `/app/data` - When the `localstorage` addon is enabled, any data under this directory is automatically backed up.
## Logging
Cloudron applications stream their logs to stdout and stderr. In contrast to logging
to files, this approach has many advantages:
* App does not need to rotate logs and the Cloudron takes care of managing logs
* App does not need special mechanism to release log file handles (on a log rotate)
* Integrates better with tooling like `cloudron cli`
This document gives you some recipes for configuring popular libraries to log to stdout. See
[base image](/references/baseimage.html#configuring) on how to configure various libraries to log to stdout/stderr.
## Memory
By default, applications get 256MB RAM (including swap). This can be changed using the `memoryLimit` field in the manifest.
Design your application runtime for concurrent use by 10s of users. The Cloudron is not designed for concurrent access by
100s or 1000s of users.
## Startup
* Apps must not present a post-installation screen on first run. It should be already pre-configured for
a specific purpose.
* Do not run as `root`. Apps can use the `cloudron` user which is part of the [base image](/references/baseimage.html)
for this purpose or create their own.
* When using the `localstorage` addon, the application must change the ownership of files in `/app/data` as desired using `chown`. This
is necessary because file permissions may not be correctly preserved across backup, restore, application and base image
updates.
* Addon information (mail, database) is exposed as environment variables. An application must use these values directly
and not cache them across restarts. If the variables are stored in a configuration file, then the configuration file
must be regenerated on every application start. This is usually done using a configuration template that is patched
on every startup.
## Authentication
Apps should integrate with one of the [authentication strategies](/references/authentication.html).
This saves the user from having to manage separate set of users for different apps.
+6 -20
View File
@@ -47,12 +47,14 @@ Type: object
Required: no
Allowed keys
* [email](addons.html#email)
* [ldap](addons.html#ldap)
* [localstorage](addons.html#localstorage)
* [mongodb](addons.html#mongodb)
* [mysql](addons.html#mysql)
* [oauth](addons.html#oauth)
* [postgresql](addons.html#postgresql)
* [recvmail](addons.html#recvmail)
* [redis](addons.html#redis)
* [sendmail](addons.html#sendmail)
@@ -93,26 +95,6 @@ Example:
"changelog": "* Add support for IE8 \n* New logo"
```
## configurePath
Type: path string
Required: no
The `configurePath` can be used to specify the absolute path to the configuration / settings
page of the app. When this path is present, an absoluted URL is constructed from the app's
install location this path and presented to the user in the configuration dialog of the app.
This is useful for apps that have a main page which does not display a configuration / settings
url (i.e) it's hidden for aesthetic reasons. For example, a blogging app like wordpress might
keep the admin page url hidden in the main page. Setting the configurationPath makes the
configuration url discoverable by the user.
Example:
```
"configurePath": "/wp-admin"
```
## contactEmail
Type: email
@@ -298,6 +280,10 @@ The intended use of this field is to display some post installation steps that t
complete the installation. For example, displaying the default admin credentials and informing the user to
to change it.
The message can have the following special tags:
* `<sso> ... </sso>` - Content in `sso` blocks are shown if SSO enabled.
* `<nosso> ... </nosso>`- Content in `nosso` blocks are shows when SSO is disabled.
## optionalSso
Type: boolean
+162 -21
View File
@@ -19,7 +19,7 @@ The Cloudron requires a domain name when it is installed. Apps are installed int
The `my` subdomain is special and is the location of the Cloudron web interface. For this to
work, the Cloudron requires a way to programmatically configure the DNS entries of the domain.
Note that the Cloudron will never overwrite _existing_ DNS entries and refuse to install
apps on existing subdomains.
apps on existing subdomains (so, it is safe to reuse an existing domain that runs other services).
# Cloud Server
@@ -34,9 +34,10 @@ In addition to those, the Cloudron community has successfully installed the plat
* [hosttech](https://www.hosttech.ch/?promocode=53619290)
* [Linode](https://www.linode.com/?r=f68d816692c49141e91dd4cef3305da457ac0f75)
* [OVH](https://www.ovh.com/)
* [Rosehosting](https://secure.rosehosting.com/clientarea/?affid=661)
* [Scaleway](https://www.scaleway.com/)
* [So you Start](https://www.soyoustart.com/)
* [Vultr](http://www.vultr.com/?ref=7063201)
* [Vultr](http://www.vultr.com/?ref=7110116-3B)
Please let us know if any of them requires tweaks or adjustments.
@@ -44,19 +45,23 @@ Please let us know if any of them requires tweaks or adjustments.
## Create server
Create an `Ubuntu 16.04 (Xenial)` server with at-least `1gb` RAM. Do not make any changes
to vanilla ubuntu. Be sure to allocate a static IPv4 address for your server.
Create an `Ubuntu 16.04 (Xenial)` server with at-least `1gb` RAM and 20GB disk space.
Do not make any changes to vanilla ubuntu. Be sure to allocate a static IPv4 address
for your server.
Cloudron has a built-in firewall and ports are opened and closed dynamically, as and when
apps are installed, re-configured or removed. For this reason, be sure to open all TCP and
UDP traffic to the server and leave the traffic management to the Cloudron.
### Kimsufi
Be sure to check the "use the distribution kernel" checkbox in the personalized installation mode.
### Linode
Since Linode does not manage SSH keys, be sure to add the public key to
`/root/.ssh/authorized_keys`.
### Scaleway
Use the [boot script](https://github.com/scaleway-community/scaleway-docker/issues/2) to
enable memory accouting.
## Run setup
SSH into your server and run the following commands:
@@ -64,7 +69,7 @@ SSH into your server and run the following commands:
```
wget https://cloudron.io/cloudron-setup
chmod +x cloudron-setup
./cloudron-setup --provider <digitalocean|ec2|generic|scaleway>
./cloudron-setup --provider <azure|digitalocean|ec2|lightsail|linode|ovh|rosehosting|scaleway|vultr|generic>
```
The setup will take around 10-15 minutes.
@@ -84,6 +89,10 @@ Specifying `fallback` will setup the Cloudron to use the fallback wildcard certi
Initially a self-signed one is provided, which can be overwritten later in the admin interface.
This may be useful for non-public installations.
* `--data-dir` is the path where Cloudron will store platform and application data. Note: data
directory must be an `ext4` filesystem.
Optional arguments used for update and restore:
* `--version` is the version of Cloudron to install. By default, the setup script installs
@@ -99,9 +108,9 @@ IP address (`https://ip`) to complete the installation.
The setup website will show a certificate warning. Accept the self-signed certificate
and proceed to the domain setup.
Currently, only Second Level Domains are supported. For example, `example.com`,
`example.co.uk` will work fine. Choosing a domain name at any other level like
`cloudron.example.com` will not work.
Currently, only subdomains of the [Public Suffix List](https://publicsuffix.org/) are supported.
For example, `example.com`, `example.co.uk` will work fine. Choosing other non-registrable
domain names like `cloudron.example.com` will not work.
### Route 53
@@ -194,6 +203,9 @@ for most use-cases.
}
```
The `Encryption key` is an arbitrary passphrase used to encrypt the backups. Keep the passphrase safe; it is
required to decrypt the backups when restoring the Cloudron.
## Minio S3
[Minio](https://minio.io/) is a distributed object storage server, providing the same API as Amazon S3.
@@ -219,6 +231,8 @@ The information to be copied to the Cloudron's backup settings form may look sim
<img src="/docs/img/minio_backup_config.png" class="shadow"><br/>
The `Encryption key` is an arbitrary passphrase used to encrypt the backups. Keep the passphrase safe; it is
required to decrypt the backups when restoring the Cloudron.
# Email
@@ -235,18 +249,30 @@ reputation should be easy to get back.
## Checklist
* Once your Cloudron is ready, setup a Reverse DNS PTR record to be setup for the `my` subdomain.
* If you are unable to receive mail, first thing to check is if your VPS provider lets you
receive mail on port 25.
* AWS/EC2 - Fill the PTR [request form](https://aws-portal.amazon.com/gp/aws/html-forms-controller/contactus/ec2-email-limit-rdns-request.
* Digital Ocean - New accounts frequently have port 25 blocked. Write to their support to
unblock your server.
* EC2, Lightsail & Scaleway - Edit your security group to allow email.
* Setup a Reverse DNS PTR record to be setup for the `my` subdomain.
**Note:** PTR records are a feature of your VPS provider and not your domain provider.
* You can verify the PTR record [https://mxtoolbox.com/ReverseLookup.aspx](here).
* AWS EC2 & Lightsail - Fill the [PTR request form](https://aws-portal.amazon.com/gp/aws/html-forms-controller/contactus/ec2-email-limit-rdns-request).
* Digital Ocean - Digital Ocean sets up a PTR record based on the droplet's name. So, simply rename
your droplet to `my.<domain>`. Note that some new Digital Ocean accounts have [port 25 blocked](https://www.digitalocean.com/community/questions/port-25-smtp-external-access).
* Scaleway - Edit your security group to allow email. You can also set a PTR record on the interface with your
`my.<domain>`.
* Linode - Follow this [guide](https://www.linode.com/docs/networking/dns/setting-reverse-dns).
* Check if your IP is listed in any DNSBL list [here](http://multirbl.valli.org/). In most cases,
you can apply for removal of your IP by filling out a form at the DNSBL manager site.
* Scaleway - Edit your security group to allow email and [reboot the server](https://community.online.net/t/security-group-not-working/2096) for the change to take effect. You can also set a PTR record on the interface with your `my.<domain>`.
* Check if your IP is listed in any DNSBL list [here](http://multirbl.valli.org/) and [here](http://www.blk.mx).
In most cases, you can apply for removal of your IP by filling out a form at the DNSBL manager site.
* When using wildcard or manual DNS backends, you have to setup the DMARC, MX records manually.
@@ -324,9 +350,12 @@ Similar to the initial installation, a Cloudron upgrade looks like:
$ ssh root@newserverip
> wget https://cloudron.io/cloudron-setup
> chmod +x cloudron-setup
> ./cloudron-setup --provider <digitalocean|ec2|generic|scaleway> --encryption-key <key> --restore-url <publicS3Url>
> ./cloudron-setup --provider <digitalocean|ec2|generic|scaleway> --domain <example.com> --encryption-key <key> --restore-url <publicS3Url>
```
Note: When upgrading an old version of Cloudron (<= 0.94.0), pass the `--version 0.94.1` flag and then continue updating
from that.
* Finally, once you see the newest version being displayed in your Cloudron webinterface, you can safely delete the old server instance.
# Restore
@@ -342,12 +371,124 @@ To restore a Cloudron from a specific backup:
* `File system` - When storing backups in `/var/backups`, you have to make the box and the app backups available to the new Cloudron instance's `/var/backups`. This can be achieved in a variety of ways depending on the situation: like scp'ing the backup files to the new machine before Cloudron installation OR mounting an external backup hard drive into the new Cloudron's `/var/backup` OR downloading a copy of the backup using `cloudron machine backup download` and uploading them to the new machine. After doing so, pass `file:///var/backups/<path to box backup>` as the `--restore-url` below.
* Create a new Cloudron by following the [installing](/references/selfhosting.html#installing) section.
When running the setup script, pass in the `version`, `encryption-key` and `restore-url` flags.
When running the setup script, pass in the `version`, `encryption-key`, `domain` and `restore-url` flags.
The `version` field is the version of the Cloudron that the backup corresponds to (it is embedded
in the backup file name).
* Make the box backup private, once the upgrade is complete.
# Security
Security is a core feature of the Cloudron and we continue to push out updates to tighten the Cloudron's security policy. Our goal is that Cloudron users should be able to rely on Cloudron being secure out of the box without having to do manual configuration.
This section lists various security measures in place to protect the Cloudron.
## HTTP Security
* Cloudron admin has a CSP policy that prevents XSS attacks.
* Cloudron set various security related HTTP headers like `X-XSS-Protection`, `X-Download-Options`,
`X-Content-Type-Options`, `X-Permitted-Cross-Domain-Policies`, `X-Frame-Options` across all apps.
## SSL
* Cloudron enforces HTTPS across all apps. HTTP requests are automatically redirected to
HTTPS.
* The Cloudron automatically installs and renews certificates for your apps as needed. Should
installation of certificate fail for reasons beyond it's control, Cloudron admins will get a notification about it.
* Cloudron sets the `Strict-Transport-Security` header (HSTS) to protect apps against downgrade attacks
and cookie hijacking.
* Cloudron has A+ rating for SSL from [SSL Labs](https://cloudron.io/blog/2017-02-22-release-0.102.0.html).
## App isolation
* Apps are isolated completely from one another. One app cannot tamper with another apps' database or
local files. We achieve this using Linux Containers.
* Apps run with a read-only rootfs preventing attacks where the application code can be tampered with.
* Apps can only connect to addons like databases, LDAP, email relay using authentication.
* Apps are run with an AppArmor profile that disables many system calls and restricts access to `proc`
and `sys` filesystems.
* Most apps are run as non-root user. In the future, we intend to implement user namespaces.
* Each app is run in it's own subdomain as opposed to sub-paths. This ensures that XSS vulnerabilities
in one app doesn't [compromise](https://security.stackexchange.com/questions/24155/preventing-insecure-webapp-on-subdomain-compromise-security-of-main-webapp) other apps.
## Email
* Cloudron checks against the [Zen Spamhaus DNSBL](https://www.spamhaus.org/zen/) before accepting mail.
* Email can only be accessed with IMAP over TLS (IMAPS).
* Email can only be relayed (including same-domain emails) by authenticated users using SMTP/STARTTLS.
* Cloudron ensures that `MAIL FROM` is the same as the authenticated user. Users cannot spoof each other.
* All outbound mails from Cloudron are `DKIM` signed.
* Cloudron automatically sets up SPF, DMARC policies in the DNS for best email delivery.
* All incoming mail is scanned via `Spamassasin`.
## Firewall
* Cloudron blocks all incoming ports except 22 (ssh), 80 (http), 443 (https)
* When email is enabled, Cloudron allows 25 (SMTP), 587 (MSA), 993 (IMAPS) and 4190 (WebSieve)
## OS Updates
* Ubuntu [automatic security updates](https://help.ubuntu.com/community/AutomaticSecurityUpdates) are enabled
## Rate limits
The goal of rate limits is to prevent password brute force attacks.
* Cloudron password verification routes - 10 requests per second per IP.
* HTTP and HTTPS requests - 5000 requests per second per IP.
* SSH access - 5 connections per 10 seconds per IP.
* Email access (Port 25, 587, 993, 4190) - 50 connections per second per IP/App.
* Database addons access - 5000 connections per second per app (addons use 128 byte passwords).
* Email relay access - 500 connections per second per app.
* Email receive access - 50 connections per second per app.
* Auth addon access - 500 connections per second per app.
## Password restrictions
* Cloudron requires user passwords to have 1 uppercase, 1 number and 1 symbol.
* Minimum length for user passwords is 8
## Privacy
* Cloudron apps have a default `Referrer-Policy` of `no-referrer-when-downgrade`.
* Backups are optionally encrypted with AES-256-CBC.
* Let's Encrypt [submits](https://letsencrypt.org/certificates/)
all certificates to [Certificate Transparency Logs](https://www.certificate-transparency.org/).
This means that the apps that you install and use are going to be guessable. For example,
[crt.sh](https://crt.sh) can display all your subdomains and you can visit those subdomains and
guess the app. Generally, this is not a problem because using hidden DNS names is not a security
measure. If you want to avoid this, you can always use a wildcard certificate.
* Cloudron does not collect any user information and this is not our business model. We collect
information regarding the configured backend types. This helps us focus on improving backends
based on their use. You can review the specific code [here](https://git.cloudron.io/cloudron/box/blob/master/src/appstore.js#L124).
# Data directory
If you are installing a brand new Cloudron, you can configure the data directory
that Cloudron uses by passing the `--data-dir` option to `cloudron-setup`.
Note: data directory must be an `ext4` filesystem.
```
./cloudron-setup --provider <digitalocean|ec2|generic|scaleway> --data-dir /var/cloudrondata
```
If you have an existing Cloudron, we recommend moving the existing data directory
to a new location as follows (`DATA_DIR` is the location to move your data):
```
systemctl stop cloudron.target
systemctl stop docker
DATA_DIR="/var/data"
mkdir -p "${DATA_DIR}"
mv /home/yellowtent/appsdata "${DATA_DIR}"
ln -s "${DATA_DIR}/appsdata" /home/yellowtent/appsdata
mv /home/yellowtent/platformdata "${DATA_DIR}"
ln -s "${DATA_DIR}/platformdata" /home/yellowtent/platformdata
systemctl start docker
systemctl start cloudron.target
```
# Debug
You can SSH into your Cloudron and collect logs:
+17 -5
View File
@@ -160,8 +160,8 @@ domain. For this, open the app's configure dialog and choose `External Domain` i
<img src="/docs/img/app_external_domain.png" class="shadow">
This dialog will suggest you to add a `CNAME` record. Once you setup a CNAME record with your DNS provider,
the app will be accessible from that external domain.
This dialog will suggest you to add a `CNAME` record (for subdomains) or an `A` record (for naked domains).
Once you setup a record with your DNS provider, the app will be accessible from that external domain.
## Entire Cloudron on a custom domain
@@ -330,16 +330,28 @@ the apps on your Cloudron and also tracks configuration changes.
<img src="/docs/img/activity.png" class="shadow">
# API Access
All the operations listed in this manual like installing app, configuring users and groups, are
completely programmable with a [REST API](/references/api.html).
# Domains and SSL Certificates
All apps on the Cloudron can only be reached by `https`. The Cloudron automatically installs and
renews certificates for your apps as needed. Should installation of certificate fail for reasons
beyond it's control, Cloudron admins will get a notification about it.
# API Access
# OAuth Provider
All the operations listed in this manual like installing app, configuring users and groups, are
completely programmable with a [REST API](/references/api.html).
Cloudron is an OAuth 2.0 provider. To integrate Cloudron login into an external application, create
an OAuth application under `API Access`.
You can use the following OAuth URLs to add Cloudron in the external app:
```
authorizationURL: https://my.<domain>/api/v1/oauth/dialog/authorize
tokenURL: https://my.<domain>/api/v1/oauth/token
```
# Moving to a larger Cloudron
+13 -11
View File
@@ -42,12 +42,12 @@ Creating an application for Cloudron can be summarized as follows:
1. Create a web application using any language/framework. This web application must run a HTTP server
and can optionally provide other services using custom protocols (like git, ssh, TCP etc).
2. Create a [Dockerfile](http://docs.docker.com/engine/reference/builder/) that specifies how to create
2. Create a [Dockerfile](http://docs.docker.com/engine/reference/builder/) that specifies how to create
an application ```image```. An ```image``` is essentially a bundle of the application source code
and it's dependencies.
3. Create a [CloudronManifest.json](/references/manifest.html) file that provides essential information
about the app. This includes information required for the Cloudron Store like title, version, icon and
about the app. This includes information required for the Cloudron Store like title, version, icon and
runtime requirements like `addons`.
## Simple Web application
@@ -75,11 +75,11 @@ A Dockerfile contains commands to assemble an image.
Create a file named `tutorial/Dockerfile` with the following content:
```dockerfile
FROM cloudron/base:0.9.0
FROM cloudron/base:0.10.0
ADD server.js /app/code/server.js
CMD [ "/usr/local/node-0.12.7/bin/node", "/app/code/server.js" ]
CMD [ "/usr/local/node-6.9.5/bin/node", "/app/code/server.js" ]
```
The `FROM` command specifies that we want to start off with Cloudron's [base image](/references/baseimage.html).
@@ -90,7 +90,7 @@ While this example only copies a single file, the ADD command can be used to cop
See the [Dockerfile](https://docs.docker.com/reference/builder/#add) documentation for more details.
The `CMD` command specifies how to run the server. There are multiple versions of node available under `/usr/local`. We
choose node v0.12.7 for our app.
choose node v6.9.5 for our app.
## CloudronManifest.json
@@ -171,12 +171,12 @@ Login successful.
Build scheduled with id 76cebfdd-7822-4f3d-af17-b3eb393ae604
Downloading source
Building
Step 0 : FROM cloudron/base:0.9.0
Step 0 : FROM cloudron/base:0.10.0
---> 97583855cc0c
Step 1 : ADD server.js /app/code
---> b09b97ecdfbc
Removing intermediate container 03c1e1f77acb
Step 2 : CMD /usr/local/node-0.12.7/bin/node /app/code/main.js
Step 2 : CMD /usr/local/node-6.9.5/bin/node /app/code/main.js
---> Running in 370f59d87ab2
---> 53b51eabcb89
Removing intermediate container 370f59d87ab2
@@ -333,7 +333,9 @@ and modify our Dockerfile to look like this:
File `tutorial/Dockerfile`
```dockerfile
FROM cloudron/base:0.9.0
FROM cloudron/base:0.10.0
ENV PATH /usr/local/node-6.9.5/bin:$PATH
ADD server.js /app/code/server.js
ADD package.json /app/code/package.json
@@ -341,7 +343,7 @@ ADD package.json /app/code/package.json
WORKDIR /app/code
RUN npm install --production
CMD [ "/usr/local/node-0.12.7/bin/node", "/app/code/server.js" ]
CMD [ "node", "/app/code/server.js" ]
```
Notice the new `RUN` command which installs the node module dependencies in package.json using `npm install`.
@@ -588,7 +590,7 @@ Once your app is ready, you can upload it to the store for `beta testing` by
other Cloudron users. This can be done using:
```
cloudron upload
cloudron appstore upload
```
The app should now be visible in the Store view of your cloudron under
@@ -605,7 +607,7 @@ developer mode.
Once you are satisfied with the beta testing, you can submit it for review.
```
cloudron submit
cloudron appstore submit
```
The cloudron.io team will review the app and publish the app to the store.
+263 -39
View File
@@ -5,8 +5,8 @@ This tutorial outlines how to package an existing web application for the Cloudr
If you are aware of Docker and Heroku, you should feel at home packaging for the
Cloudron. Roughly, the steps involved are:
* Create a Dockerfile for your application. If your application already has
a Dockerfile, you should able to reuse most of it. By virtue of Docker, the Cloudron
* Create a Dockerfile for your application. If your application already has a Dockerfile, it
is a good starting point for packaging for the Cloudron. By virtue of Docker, the Cloudron
is able to run apps written in any language/framework.
* Create a CloudronManifest.json that provides information like title, author, description
@@ -79,22 +79,22 @@ console.log("Server running at port 8000");
The Dockerfile contains instructions on how to create an image for your application.
```Dockerfile
FROM cloudron/base:0.9.0
FROM cloudron/base:0.10.0
ADD server.js /app/code/server.js
CMD [ "/usr/local/node-4.4.7/bin/node", "/app/code/server.js" ]
CMD [ "/usr/local/node-4.7.3/bin/node", "/app/code/server.js" ]
```
The `FROM` command specifies that we want to start off with Cloudron's [base image](/references/baseimage.html).
All Cloudron apps **must** start from this base image. This approach conserves space on the Cloudron since
Docker images tend to be quiet large.
Docker images tend to be quite large and also helps us to do a security audit on apps more easily.
The `ADD` command copies the source code of the app into the directory `/app/code`. There is nothing special
about the `/app/code` directory and it is merely a convention we use to store the application code.
The `CMD` command specifies how to run the server. The base image already contains many different versions of
node.js. We use Node 4.4.7 here.
node.js. We use Node 4.7.3 here.
This Dockerfile can be built and run locally as:
```
@@ -179,7 +179,7 @@ Initiate a build using ```cloudron build```:
$ cloudron build
Building io.cloudron.tutorial@0.0.1
Appstore login:
cloudron.io login:
Email: ramakrishnan.girish@gmail.com # cloudron.io account
Password: # Enter password
Login successful.
@@ -188,7 +188,7 @@ Build scheduled with id e7706847-f2e3-4ba2-9638-3f334a9453a5
Waiting for build to begin, this may take a bit...
Downloading source
Building
Step 1 : FROM cloudron/base:0.9.0
Step 1 : FROM cloudron/base:0.10.0
---> be9fc6312b2d
Step 2 : ADD server.js /app/code/server.js
---> 10513e428d7a
@@ -348,12 +348,64 @@ show any setup screen after installation and should simply choose reasonable def
Databases, email configuration should be automatically picked up from the environment variables using
addons.
## Dockerfile
## Docker
The app is run as a read-only docker container. Because of this:
* Install any required packages in the Dockerfile.
* Create static configuration files in the Dockerfile.
* Create symlinks to dynamic configuration files under /run in the Dockerfile.
Cloudron uses Docker in the backend, so the package build script is a regular `Dockerfile`.
The app is run as a read-only docker container. Only `/run` (dynamic data), `/app/data` (backup data) and `/tmp` (temporary files) are writable at runtime. Because of this:
* Install any required packages in the Dockerfile.
* Create static configuration files in the Dockerfile.
* Create symlinks to dynamic configuration files under `/run` in the Dockerfile.
### Source directory
By convention, Cloudron apps install the source code in `/app/code`. Do not forget to create the directory for the code of the app:
```sh
RUN mkdir -p /app/code
WORKDIR /app/code
```
### Download archives
When packaging an app you often want to download and extract archives (e.g. from github).
This can be done in one line by combining `wget` and `tar` like this:
```docker
ENV VERSION 1.6.2
RUN wget "https://github.com/FreshRSS/FreshRSS/archive/${VERSION}.tar.gz" -O - \
| tar -xz -C /app/code --strip-components=1
```
The `--strip-components=1` causes the topmost directory in the archive to be skipped.
Always pin the download to a specific tag or commit instead of using `HEAD` or `master`
so that the builds are reasonably reproducible.
### Applying patches
To get the app working in Cloudron, sometimes it is necessary to patch the original sources. Patch is a safe way to modify sources, as it fails when the expected original sources changed too much.
First create a backup copy of the full sources (to be able to calculate the differences):
```sh
cp -a extensions extensions-orig
```
Then modify the sources in the original path and when finished, create a patch like this:
```sh
diff -Naru extensions-orig/ extensions/ > change-ttrss-file-path.patch
```
Add and apply this patch to the sources in the Dockerfile:
```docker
ADD change-ttrss-file-path.patch /app/code/change-ttrss-file-path.patch
RUN patch -p1 -d /app/code/extensions < /app/code/change-ttrss-file-path.patch
```
The `-p1` causes patch to ignore the topmost directory in the patch.
## Process manager
@@ -362,7 +414,7 @@ automatically. If your application is a single process, you do not require any p
Use supervisor, pm2 or any of the other process managers if you application has more then one component.
This **excludes** web servers like apache, nginx which can already manage their children by themselves.
Be sure to pick a process manager that forwards signals to child processes.
Be sure to pick a process manager that [forwards signals](#sigterm-handling) to child processes.
## Automatic updates
@@ -389,40 +441,214 @@ field in the manifest.
Design your application runtime for concurrent use by 50 users. The Cloudron is not designed for
concurrent access by 100s or 1000s of users.
An app can determine it's memory limit by reading `/sys/fs/cgroup/memory/memory.limit_in_bytes`.
## Authentication
Apps should integrate with one of the [authentication strategies](/references/authentication.html).
This saves the user from having to manage separate set of credentials for each app.
## Startup Script
## Start script
Many apps do not launch the server directly, as we did in our basic example. Instead, they execute
a `start.sh` script (named so by convention) which launches the server. Before starting the server,
the `start.sh` script does the following:
a `start.sh` script (named so by convention) which is used as the app entry point.
* When using the `localstorage` addon, it changes the ownership of files in `/app/data` as desired using `chown`. This
is necessary because file permissions may not be correctly preserved across backup, restore, application and base image
updates.
At the end of the Dockerfile you should add your start script (`start.sh`) and set it as the default command.
Ensure that the `start.sh` is executable in the app package repo. This can be done with `chmod +x start.sh`.
```docker
ADD start.sh /app/code/start.sh
CMD [ "/app/code/start.sh" ]
```
* Addon information (mail, database) exposed as environment are subject to change across restarts and an application
must use these values directly (i.e not cache them across restarts). For this reason, it usually regenerates
any config files with the current database settings on each invocation.
### One-time init
* Finally, it starts the server as a non-root user.
One common pattern is to initialize the data directory with some commands once depending on the existence of a special `.initialized` file.
The app's main process must handle SIGTERM and forward it as required to child processes. bash does not
automatically forward signals to child processes. For this reason, when using a startup shell script,
remember to use exec <app> as the last line. Doing so will replace bash with your program and allows
your program to handle signals as required.
```sh
if ! [ -f /app/data/.initialized ]; then
echo "Fresh installation, setting up data directory..."
# Setup commands here
touch /app/data/.initialized
echo "Done."
fi
```
# Beta Testing
To copy over some files from the code directory you can use the following command:
## Metadata
```sh
rsync -a /app/code/config/ /app/data/config/
```
Publishing to the Cloudron Store requires apps to have meta data specified in the `CloudronManifest.json`.
### chown data files
The `cloudron` tool will notify if any such information is missing, prior to uploading.
See more information for each field [here](/references/manifest.html).
Since the app containers use other user ids than the host, it is sometimes necessary to change the permissions on the data directory:
```sh
chown -R cloudron.cloudron /app/data
```
For Apache+PHP apps you might need to change permissions to `www-data.www-data` instead.
### Persisting random values
Some apps need a random value that is initialized once and does not change afterwards (e.g. a salt for security purposes). This can be accomplished by creating a random value and storing it in a file in the data directory like this:
```sh
if ! [ -e /app/data/.salt ]; then
dd if=/dev/urandom bs=1 count=1024 2>/dev/null | sha1sum | awk '{ print $1 }' > /app/data/.salt
fi
SALT=$(cat /app/data/.salt)
```
### Generate config
Addon information (mail, database) exposed as environment are subject to change across restarts and an application must use these values directly (i.e not cache them across restarts). For this reason, it usually regenerates any config files with the current database settings on each invocation.
First create a config file template like this:
```sh
... snipped ...
'mysql' => array(
'driver' => 'mysql',
'host' => '##MYSQL_HOST',
'port' => '##MYSQL_PORT',
'database' => '##MYSQL_DATABASE',
'username' => '##MYSQL_USERNAME',
'password' => '##MYSQL_PASSWORD',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
),
... snipped ...
```
Add the template file to the Dockerfile and create a symlink to the dynamic configuration file as follows:
```docker
ADD database.php.template /app/code/database.php.template
RUN ln -s /run/paperwork/database.php /app/code/database.php
```
Then in `start.sh`, generate the real config file under `/run` from the template like this:
```sh
sed -e "s/##MYSQL_HOST/${MYSQL_HOST}/" \
-e "s/##MYSQL_PORT/${MYSQL_PORT}/" \
-e "s/##MYSQL_DATABASE/${MYSQL_DATABASE}/" \
-e "s/##MYSQL_USERNAME/${MYSQL_USERNAME}/" \
-e "s/##MYSQL_PASSWORD/${MYSQL_PASSWORD}/" \
-e "s/##REDIS_HOST/${REDIS_HOST}/" \
-e "s/##REDIS_PORT/${REDIS_PORT}/" \
/app/code/database.php.template > /run/paperwork/database.php
```
### Non-root user
The cloudron runs the `start.sh` as root user. This is required for various commands like `chown` to
work as expected. However, to keep the app and cloudron secure, always run the app with the least
required permissions.
The `gosu` tool lets you run a binary with a specific user/group as follows:
```sh
/usr/local/bin/gosu cloudron:cloudron node /app/code/.build/bundle/main.js
```
### SIGTERM handling
bash, by default, does not automatically forward signals to child processes. This would mean that a SIGTERM sent to the parent processes does not reach the children. For this reason, be sure to `exec` as the
last line of the start.sh script. Programs like gosu, nginx, apache do proper SIGTERM handling.
For example, start apache using `exec` as below:
```sh
echo "Starting apache"
APACHE_CONFDIR="" source /etc/apache2/envvars
rm -f "${APACHE_PID_FILE}"
exec /usr/sbin/apache2 -DFOREGROUND
```
## Popular stacks
### Apache
Apache requires some configuration changes to work properly with Cloudron. The following commands configure Apache in the following way:
* Disable all default sites
* Print errors into the app's log and disable other logs
* Limit server processes to `5` (good default value)
* Change the port number to Cloudrons default `8000`
```docker
RUN rm /etc/apache2/sites-enabled/* \
&& sed -e 's,^ErrorLog.*,ErrorLog "/dev/stderr",' -i /etc/apache2/apache2.conf \
&& sed -e "s,MaxSpareServers[^:].*,MaxSpareServers 5," -i /etc/apache2/mods-available/mpm_prefork.conf \
&& a2disconf other-vhosts-access-log \
&& echo "Listen 8000" > /etc/apache2/ports.conf
```
Afterwards, add your site config to Apache:
```docker
ADD apache2.conf /etc/apache2/sites-available/app.conf
RUN a2ensite app
```
In `start.sh` Apache can be started using these commands:
```sh
echo "Starting apache..."
APACHE_CONFDIR="" source /etc/apache2/envvars
rm -f "${APACHE_PID_FILE}"
exec /usr/sbin/apache2 -DFOREGROUND
```
### PHP
PHP wants to store session data at `/var/lib/php/sessions` which is read-only in Cloudron. To fix this problem you can move this data to `/run/php/sessions` with these commands:
```docker
RUN rm -rf /var/lib/php/sessions && ln -s /run/php/sessions /var/lib/php/sessions
```
Don't forget to create this directory and it's ownership in the `start.sh`:
```sh
mkdir -p /run/php/sessions
chown www-data:www-data /run/php/sessions
```
### Java
Java scales its memory usage dynamically according to the available system memory. Due to how Docker works, Java sees the hosts total memory instead of the memory limit of the app. To restrict Java to the apps memory limit it is necessary to add a special parameter to Java calls.
```sh
LIMIT=$(($(cat /sys/fs/cgroup/memory/memory.memsw.limit_in_bytes)/2**20))
export JAVA_OPTS="-XX:MaxRAM=${LIMIT}M"
java ${JAVA_OPTS} -jar ...
```
# App Store
## Requirements
The Cloudron Store is a mechanism to share your app with others who use Cloudron. Currently, to ensure that
apps are maintained, secure and well supported there are some restrictions imposed on apps submitted to
the Cloudron Store. See [#292](https://git.cloudron.io/cloudron/box/issues/292) and [#327](https://git.cloudron.io/cloudron/box/issues/327) for an in-depth discussion.
The following criteria must be met before submitting an app for review:
* You must be willing to relocate your app packaging code to the [Cloudron Git Repo](https://git.cloudron.io/cloudron/).
* Contributed apps must have browser tests. You can see the various [app repos](https://git.cloudron.io/cloudron/) to get an idea on how to write these tests. The Cloudron team can help you write the tests.
* For all practical purposes, you are the maintainer of the app and Cloudron team will not commit to the repo
directly. Any changes will be submitted as Merge Requests.
* You agree that the Cloudron team can take over the responsibility of progressing the app further if you become unresponsive (48 hours), lose interest, lack time etc. Please send us an email if your priorities change.
* You must sign the [Cloudron CLA](https://cla.cloudron.io/).
As a token of our appreciation, 3rd party app authors can use the Cloudron for personal or business use for free.
## Upload for Testing
@@ -430,7 +656,7 @@ Once your app is ready, you can upload it to the store for `beta testing` by
other Cloudron users. This can be done using:
```
cloudron upload
cloudron appstore upload
```
You should now be able to visit `/#/appstore/<appid>?version=<appversion>` on your
@@ -439,19 +665,17 @@ Cloudron to check if the icon, description and other details appear correctly.
Other Cloudron users can install your app on their Cloudron's using
`cloudron install --appstore-id <appid@version>`.
# Publishing
## Publishing
Once you are satisfied with the beta testing, you can submit it for review.
```
cloudron submit
cloudron appstore submit
```
The cloudron.io team will review the app and publish the app to the store.
# Updating the app
## Versioning
## Versioning and Updates
To create an update for an app, simply bump up the [semver version](/references/manifest.html#version) field in
the manifest and publish a new version to the store.
+18 -15
View File
@@ -2,17 +2,18 @@
'use strict';
var ejs = require('gulp-ejs'),
gulp = require('gulp'),
del = require('del'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
serve = require('gulp-serve'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
cssnano = require('gulp-cssnano'),
var argv = require('yargs').argv,
autoprefixer = require('gulp-autoprefixer'),
argv = require('yargs').argv;
concat = require('gulp-concat'),
cssnano = require('gulp-cssnano'),
del = require('del'),
ejs = require('gulp-ejs'),
gulp = require('gulp'),
sass = require('gulp-sass'),
serve = require('gulp-serve'),
sourcemaps = require('gulp-sourcemaps'),
uglify = require('gulp-uglify'),
url = require('url');
gulp.task('3rdparty', function () {
gulp.src([
@@ -54,14 +55,16 @@ gulp.task('js', ['js-index', 'js-setup', 'js-setupdns', 'js-update'], function (
var oauth = {
clientId: argv.clientId || 'cid-webadmin',
clientSecret: argv.clientSecret || 'unused',
apiOrigin: argv.apiOrigin || ''
apiOrigin: argv.apiOrigin || '',
apiOriginHostname: argv.apiOrigin ? url.parse(argv.apiOrigin).hostname : ''
};
console.log();
console.log('Using OAuth credentials:');
console.log(' ClientId: %s', oauth.clientId);
console.log(' ClientSecret: %s', oauth.clientSecret);
console.log(' Cloudron API: %s', oauth.apiOrigin || 'default');
console.log(' ClientId: %s', oauth.clientId);
console.log(' ClientSecret: %s', oauth.clientSecret);
console.log(' Cloudron API: %s', oauth.apiOrigin || 'default');
console.log(' Cloudron Host: %s', oauth.apiOriginHostname);
console.log();
@@ -140,7 +143,7 @@ gulp.task('js-update', function () {
// --------------
gulp.task('html', ['html-views', 'html-update', 'html-templates'], function () {
return gulp.src('webadmin/src/*.html').pipe(gulp.dest('webadmin/dist'));
return gulp.src('webadmin/src/*.html').pipe(ejs({ apiOriginHostname: oauth.apiOriginHostname }, { ext: '.html' })).pipe(gulp.dest('webadmin/dist'));
});
gulp.task('html-update', function () {
Executable
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env node
'use strict';
var tar = require('tar-fs'),
fs = require('fs'),
path = require('path'),
zlib = require('zlib');
if (process.argv.length < 4) {
console.error('Usage: tarjs <cwd> <dir>');
process.exit(1);
}
var dir = process.argv[3];
var cwd = process.argv[2];
console.error('Packing directory "'+ dir +'" from within "' + cwd + '" and stream to stdout');
process.chdir(cwd);
var stat = fs.statSync(dir);
if (!stat.isDirectory()) throw(dir + ' is not a directory');
var gzipStream = zlib.createGzip({});
tar.pack(path.resolve(dir), {
ignore: function (name) {
if (name === '.') return true;
return false;
}
}).pipe(gzipStream).pipe(process.stdout);
+2 -2
View File
@@ -1,5 +1,5 @@
var dbm = require('db-migrate');
var type = dbm.dataType;
'use strict';
var url = require('url');
exports.up = function(db, callback) {
+1 -2
View File
@@ -1,5 +1,4 @@
var dbm = require('db-migrate');
var type = dbm.dataType;
'use strict';
var fs = require('fs'),
async = require('async'),
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE users ADD COLUMN resetToken VARCHAR(128) DEFAULT ""', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('DELETE FROM tokens', [], function (error) {
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE authcodes ADD COLUMN expiresAt BIGINT NOT NULL', function (error) {
@@ -13,4 +12,4 @@ exports.down = function(db, callback) {
if (error) console.error(error);
callback(error);
});
};
};
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE appPortBindings ADD COLUMN environmentVariable VARCHAR(128) NOT NULL', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE appPortBindings DROP COLUMN containerPort', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('DELETE FROM tokens', [], function (error) {
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps DROP COLUMN version', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps DROP COLUMN healthy, ADD COLUMN health VARCHAR(128)', [], function (error) {
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps ADD COLUMN lastBackupId VARCHAR(128)', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps ADD COLUMN createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
// everyday at 1am
@@ -8,5 +7,4 @@ exports.up = function(db, callback) {
exports.down = function(db, callback) {
db.runSql('DELETE * FROM settings WHERE name="autoupdate_pattern"', [ ], callback);
}
};
@@ -1,6 +1,6 @@
dbm = dbm || require('db-migrate');
'use strict';
var safe = require('safetydance');
var type = dbm.dataType;
exports.up = function(db, callback) {
var tz = safe.fs.readFileSync('/etc/timezone', 'utf8');
@@ -12,4 +12,3 @@ exports.up = function(db, callback) {
exports.down = function(db, callback) {
db.runSql('DELETE * FROM settings WHERE name="time_zone"', [ ], callback);
};
@@ -1,5 +1,5 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
var async = require('async');
exports.up = function(db, callback) {
@@ -1,5 +1,5 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
var async = require('async');
exports.up = function(db, callback) {
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps ADD COLUMN lastManifestJson VARCHAR(2048)', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps CHANGE lastManifestJson lastBackupConfigJson VARCHAR(2048)', [], function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps ADD COLUMN oldConfigJson VARCHAR(2048)', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('DELETE FROM settings', [ ], callback);
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps ADD COLUMN oauthProxy BOOLEAN DEFAULT 0', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,5 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
var async = require('async');
exports.up = function(db, callback) {
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps CHANGE accessRestriction accessRestrictionJson VARCHAR(2048)', [], function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps MODIFY manifestJson TEXT', [], function (error) {
@@ -1,5 +1,5 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
var async = require('async');
exports.up = function(db, callback) {
@@ -1,4 +1,4 @@
dbm = dbm || require('db-migrate');
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE users ADD COLUMN displayName VARCHAR(512) DEFAULT ""', function (error) {
@@ -1,4 +1,4 @@
dbm = dbm || require('db-migrate');
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps ADD COLUMN memoryLimit BIGINT DEFAULT 0', function (error) {
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
var cmd = "CREATE TABLE groups(" +
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
var cmd = "CREATE TABLE IF NOT EXISTS groupMembers(" +
@@ -1,6 +1,5 @@
'use strict';
var dbm = global.dbm || require('db-migrate');
var async = require('async');
var ADMIN_GROUP_ID = 'admin'; // see groups.js
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
var cmd = "CREATE TABLE backups(" +
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE backups ADD COLUMN configJson TEXT', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
var dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE backups DROP COLUMN configJson', function (error) {
@@ -14,4 +13,3 @@ exports.down = function(db, callback) {
callback(error);
});
};
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE backups CHANGE filename id VARCHAR(128)', [], function (error) {
@@ -1,4 +1,4 @@
dbm = dbm || require('db-migrate');
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE users MODIFY username VARCHAR(254) UNIQUE', [], function (error) {
@@ -1,7 +1,5 @@
'use strict';
var dbm = dbm || require('db-migrate');
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps ADD COLUMN altDomain VARCHAR(256)', function (error) {
if (error) console.error(error);
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
var cmd = "CREATE TABLE eventlog(" +
@@ -1,4 +1,4 @@
dbm = dbm || require('db-migrate');
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE users ADD COLUMN showTutorial BOOLEAN DEFAULT 0', function (error) {
@@ -1,8 +1,5 @@
'use strict';
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
var cmd = 'CREATE TABLE mailboxes(' +
'name VARCHAR(128) NOT NULL,' +
@@ -1,5 +1,6 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
var async = require('async');
// imports mailbox entries for existing users
exports.up = function(db, callback) {
@@ -1,5 +1,4 @@
dbm = dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps DROP COLUMN lastBackupConfigJson', function (error) {
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps MODIFY installationProgress TEXT', [], function (error) {
@@ -1,4 +1,4 @@
dbm = dbm || require('db-migrate');
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps ADD COLUMN xFrameOptions VARCHAR(512)', function (error) {
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.all('SELECT id FROM users', function (error, results) {
@@ -14,4 +13,3 @@ exports.up = function(db, callback) {
exports.down = function(db, callback) {
db.runSql('DELETE * FROM settings WHERE name="mail_config"', [ ], callback);
};
@@ -1,6 +1,6 @@
'use strict';
var dbm = dbm || require('db-migrate');
var async = require('async');
exports.up = function(db, callback) {
async.series([
@@ -71,4 +71,3 @@ exports.down = function(db, callback) {
});
});
};
+1 -2
View File
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps ADD COLUMN sso BOOLEAN DEFAULT 1', function (error) {
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps DROP COLUMN oauthProxy', function (error) {
@@ -1,5 +1,4 @@
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE users DROP COLUMN showTutorial', function (error) {
@@ -1,4 +1,4 @@
dbm = dbm || require('db-migrate');
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE apps ADD COLUMN debugModeJson TEXT', function (error) {
@@ -0,0 +1,15 @@
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE backups MODIFY dependsOn TEXT', [], function (error) {
if (error) console.error(error);
callback(error);
});
};
exports.down = function(db, callback) {
db.runSql('ALTER TABLE backups MODIFY dependsOn VARCHAR(4096)', [], function (error) {
if (error) console.error(error);
callback(error);
});
};
@@ -0,0 +1,16 @@
'use strict';
exports.up = function(db, callback) {
db.runSql('ALTER TABLE appAddonConfigs ADD COLUMN name VARCHAR(128)', function (error) {
if (error) console.error(error);
callback(error);
});
};
exports.down = function(db, callback) {
db.runSql('ALTER TABLE appAddonConfigs DROP COLUMN name', function (error) {
if (error) console.error(error);
callback(error);
});
};
@@ -0,0 +1,14 @@
'use strict';
var url = require('url');
exports.up = function(db, callback) {
var dbName = url.parse(process.env.DATABASE_URL).path.substr(1); // remove slash
// by default, mysql collates case insensitively. 'utf8_general_cs' is not available
db.runSql('ALTER DATABASE ' + dbName + ' DEFAULT CHARACTER SET=utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci', callback);
};
exports.down = function(db, callback) {
callback();
};
@@ -0,0 +1,95 @@
'use strict';
var async = require('async');
// from apps.js DO NOT UPDATE WHEN apps.js changes, as this is part of db migration!!
function postProcess(result) {
try {
result.manifest = JSON.parse(result.manifestJson);
delete result.manifestJson;
result.oldConfig = JSON.parse(result.oldConfigJson);
delete result.oldConfigJson;
result.portBindings = { };
var hostPorts = result.hostPorts === null ? [ ] : result.hostPorts.split(',');
var environmentVariables = result.environmentVariables === null ? [ ] : result.environmentVariables.split(',');
delete result.hostPorts;
delete result.environmentVariables;
for (var i = 0; i < environmentVariables.length; i++) {
result.portBindings[environmentVariables[i]] = parseInt(hostPorts[i], 10);
}
result.accessRestriction = JSON.parse(result.accessRestrictionJson);
if (result.accessRestriction && !result.accessRestriction.users) result.accessRestriction.users = [];
delete result.accessRestrictionJson;
// TODO remove later once all apps have this attribute
result.xFrameOptions = result.xFrameOptions || 'SAMEORIGIN';
result.sso = !!result.sso; // make it bool
result.debugMode = JSON.parse(result.debugModeJson);
delete result.debugModeJson;
} catch (e) {
console.error('Failed to get restoreConfig for app.', e);
console.error('Falling back to empty values to make the update succeed.');
result.manifest = null;
}
}
// from apps.js DO NOT UPDATE WHEN apps.js changes, as this is part of db migration!!
var APPS_FIELDS_PREFIXED = [ 'apps.id', 'apps.appStoreId', 'apps.installationState', 'apps.installationProgress', 'apps.runState',
'apps.health', 'apps.containerId', 'apps.manifestJson', 'apps.httpPort', 'apps.location', 'apps.dnsRecordId',
'apps.accessRestrictionJson', 'apps.lastBackupId', 'apps.oldConfigJson', 'apps.memoryLimit', 'apps.altDomain',
'apps.xFrameOptions', 'apps.sso', 'apps.debugModeJson' ].join(',');
exports.up = function(db, callback) {
async.series([
db.runSql.bind(db, 'ALTER TABLE backups ADD COLUMN restoreConfigJson TEXT'),
// fill all the backups with restoreConfigs from current apps
function addRestoreConfigs(callback) {
console.log('Importing restoreConfigs');
var appQuery = 'SELECT ' + APPS_FIELDS_PREFIXED + ',' +
'GROUP_CONCAT(CAST(appPortBindings.hostPort AS CHAR(6))) AS hostPorts, GROUP_CONCAT(appPortBindings.environmentVariable) AS environmentVariables' +
' FROM apps LEFT OUTER JOIN appPortBindings ON apps.id = appPortBindings.appId' +
' GROUP BY apps.id ORDER BY apps.id';
db.all(appQuery, function (error, apps) {
if (error) return callback(error);
apps.forEach(postProcess);
async.eachSeries(apps, function (app, next) {
if (app.manifest === null) return next();
db.all('SELECT * FROM backups WHERE type="app" AND id LIKE "%app%\\_' + app.id + '\\_%"', function (error, backups) {
if (error) return next(error);
// from apps.js:getAppConfig()
var restoreConfig = {
manifest: app.manifest,
location: app.location,
accessRestriction: app.accessRestriction,
portBindings: app.portBindings,
memoryLimit: app.memoryLimit,
xFrameOptions: app.xFrameOptions || 'SAMEORIGIN',
altDomain: app.altDomain
};
async.eachSeries(backups, function (backup, next) {
db.runSql('UPDATE backups SET restoreConfigJson=?,creationTime=creationTime WHERE id=?', [ JSON.stringify(restoreConfig), backup.id ], next);
}, next);
});
}, callback);
});
}
], callback);
};
exports.down = function(db, callback) {
db.runSql('ALTER TABLE backups DROP COLUMN restoreConfigJson', callback);
};
@@ -0,0 +1,22 @@
'use strict';
exports.up = function(db, callback) {
db.all('SELECT value FROM settings WHERE name="backup_config"', function (error, results) {
if (error || results.length === 0) return callback(error);
var backupConfig = JSON.parse(results[0].value);
if (backupConfig.provider === 'filesystem') {
backupConfig.retentionSecs = 2 * 24 * 60 * 60; // 2 days
} else if (backupConfig.provider === 's3') { // S3
backupConfig.retentionSecs = -1;
} else if (backupConfig.provider === 'caas') {
backupConfig.retentionSecs = 10 * 24 * 60 * 60; // 10 days
}
db.runSql('UPDATE settings SET value=? WHERE name="backup_config"', [ JSON.stringify(backupConfig) ], callback);
});
};
exports.down = function(db, callback) {
callback();
};
+9 -7
View File
@@ -60,7 +60,7 @@ CREATE TABLE IF NOT EXISTS apps(
manifestJson TEXT,
httpPort INTEGER, // this is the nginx proxy port and not manifest.httpPort
location VARCHAR(128) NOT NULL UNIQUE,
dnsRecordId VARCHAR(512),
dnsRecordId VARCHAR(512), // tracks any id that we got back to track dns updates (unused)
accessRestrictionJson TEXT, // { users: [ ], groups: [ ] }
createdAt TIMESTAMP(2) NOT NULL DEFAULT CURRENT_TIMESTAMP,
memoryLimit BIGINT DEFAULT 0,
@@ -69,9 +69,9 @@ CREATE TABLE IF NOT EXISTS apps(
sso BOOLEAN DEFAULT 1, // whether user chose to enable SSO
debugModeJson TEXT, // options for development mode
lastBackupId VARCHAR(128), // tracks last valid backup, can be removed
oldConfigJson TEXT, // used to pass old config for apptask, can be removed when we use a queue
// the following fields do not belong here, they can be removed when we use a queue for apptask
lastBackupId VARCHAR(128), // used to pass backupId to restore from to apptask
oldConfigJson TEXT, // used to pass old config for apptask
PRIMARY KEY(id));
@@ -97,18 +97,20 @@ CREATE TABLE IF NOT EXISTS settings(
CREATE TABLE IF NOT EXISTS appAddonConfigs(
appId VARCHAR(128) NOT NULL,
addonId VARCHAR(32) NOT NULL,
name VARCHAR(128) NOT NULL,
value VARCHAR(512) NOT NULL,
FOREIGN KEY(appId) REFERENCES apps(id));
CREATE TABLE IF NOT EXISTS backups(
filename VARCHAR(128) NOT NULL,
id VARCHAR(128) NOT NULL,
creationTime TIMESTAMP,
version VARCHAR(128) NOT NULL, /* app version or box version */
type VARCHAR(16) NOT NULL, /* 'box' or 'app' */
dependsOn VARCHAR(4096), /* comma separate list of objects this backup depends on */
dependsOn TEXT, /* comma separate list of objects this backup depends on */
state VARCHAR(16) NOT NULL,
restoreConfigJson TEXT, /* JSON including the manifest of the backed up app */
PRIMARY KEY (filename));
PRIMARY KEY (id));
CREATE TABLE IF NOT EXISTS eventlog(
id VARCHAR(128) NOT NULL,
+1022 -1824
View File
File diff suppressed because it is too large Load Diff
+17 -13
View File
@@ -13,11 +13,11 @@
"node >=4.0.0 <=4.1.1"
],
"dependencies": {
"async": "^1.2.1",
"aws-sdk": "^2.1.46",
"@sindresorhus/df": "^2.1.0",
"async": "^2.1.4",
"aws-sdk": "^2.41.0",
"body-parser": "^1.13.1",
"checksum": "^0.1.1",
"cloudron-manifestformat": "^2.6.0",
"cloudron-manifestformat": "^2.8.0",
"connect-ensure-login": "^0.1.1",
"connect-lastmile": "^0.1.0",
"connect-timeout": "^1.5.0",
@@ -25,16 +25,17 @@
"cookie-session": "^1.1.0",
"cron": "^1.0.9",
"csurf": "^1.6.6",
"db-migrate": "^0.9.2",
"db-migrate": "^0.10.0-beta.20",
"db-migrate-mysql": "^1.1.10",
"debug": "^2.2.0",
"dockerode": "^2.2.10",
"dockerode": "^2.4.3",
"ejs": "^2.2.4",
"ejs-cli": "^1.2.0",
"express": "^4.12.4",
"express-rate-limit": "^2.6.0",
"express-session": "^1.11.3",
"gulp-sass": "^3.0.0",
"hat": "0.0.3",
"hock": "https://registry.npmjs.org/hock/-/hock-1.3.2.tgz",
"json": "^9.0.3",
"ldapjs": "^1.0.0",
"mime": "^1.3.4",
@@ -42,8 +43,6 @@
"morgan": "^1.7.0",
"multiparty": "^4.1.2",
"mysql": "^2.7.0",
"native-dns": "^0.7.0",
"node-df": "^0.1.1",
"node-uuid": "^1.4.3",
"nodemailer": "^1.3.0",
"nodemailer-smtp-transport": "^1.0.3",
@@ -56,18 +55,20 @@
"passport-local": "^1.0.0",
"passport-oauth2-client-password": "^0.1.2",
"password-generator": "^2.0.2",
"progress-stream": "^2.0.0",
"proxy-middleware": "^0.13.0",
"safetydance": "^0.1.1",
"s3-block-read-stream": "^0.2.0",
"safetydance": "^0.2.0",
"semver": "^4.3.6",
"showdown": "^1.6.0",
"split": "^1.0.0",
"superagent": "^1.8.3",
"supererror": "^0.7.1",
"tar-fs": "https://registry.npmjs.org/tar-fs/-/tar-fs-1.15.2.tgz",
"tldjs": "^1.6.2",
"underscore": "^1.7.0",
"valid-url": "^1.0.9",
"validator": "^4.9.0",
"x509": "^0.2.4"
"validator": "^4.9.0"
},
"devDependencies": {
"bootstrap-sass": "^3.3.3",
@@ -87,15 +88,18 @@
"istanbul": "*",
"js2xmlparser": "^1.0.0",
"mocha": "*",
"mock-aws-s3": "^2.4.0",
"nock": "^9.0.2",
"node-sass": "^3.0.0-alpha.0",
"readdirp": "https://registry.npmjs.org/readdirp/-/readdirp-2.1.0.tgz",
"request": "^2.65.0",
"yargs": "^3.15.0"
},
"scripts": {
"migrate_local": "DATABASE_URL=mysql://root:@localhost/box node_modules/.bin/db-migrate up",
"migrate_test": "BOX_ENV=test DATABASE_URL=mysql://root:@localhost/boxtest node_modules/.bin/db-migrate up",
"test": "npm run migrate_test && src/test/setupTest && BOX_ENV=test ./node_modules/istanbul/lib/cli.js test $1 ./node_modules/mocha/bin/_mocha -- -R spec ./src/test ./src/routes/test",
"test": "npm run migrate_test && src/test/setupTest && BOX_ENV=test ./node_modules/istanbul/lib/cli.js test $1 ./node_modules/mocha/bin/_mocha -- -R spec ./src/test ./src/routes/test/[^a]*",
"test_all": "npm run migrate_test && src/test/setupTest && BOX_ENV=test ./node_modules/istanbul/lib/cli.js test $1 ./node_modules/mocha/bin/_mocha -- -R spec ./src/test ./src/routes/test",
"postmerge": "/bin/true",
"precommit": "/bin/true",
"prepush": "npm test",
+86 -43
View File
@@ -14,14 +14,16 @@ fi
# change this to a hash when we make a upgrade release
readonly LOG_FILE="/var/log/cloudron-setup.log"
readonly MINIMUM_DISK_SIZE_GB="19" # this is the size of "/" and required to fit in docker images 19 is a safe bet for different reporting on 20GB min
readonly MINIMUM_MEMORY="990" # this is mostly reported for 1GB main memory (DO 992, EC2 990)
readonly DATA_FILE="/root/cloudron-install-data.json"
readonly MINIMUM_DISK_SIZE_GB="18" # this is the size of "/" and required to fit in docker images 18 is a safe bet for different reporting on 20GB min
readonly MINIMUM_MEMORY="974" # this is mostly reported for 1GB main memory (DO 992, EC2 990, Linode 989, Serverdiscounter.com 974)
readonly curl="curl --fail --connect-timeout 20 --retry 10 --retry-delay 2 --max-time 2400"
# copied from cloudron-resize-fs.sh
readonly physical_memory=$(free -m | awk '/Mem:/ { print $2 }')
readonly disk_device="$(for d in $(find /dev -type b); do [ "$(mountpoint -d /)" = "$(mountpoint -x $d)" ] && echo $d && break; done)"
readonly disk_size_bytes=$(fdisk -l ${disk_device} | grep "Disk ${disk_device}" | awk '{ printf $5 }')
readonly disk_size_gb=$((${disk_size_bytes}/1024/1024/1024))
readonly physical_memory=$(LC_ALL=C free -m | awk '/Mem:/ { print $2 }')
readonly disk_size_bytes=$(LC_ALL=C df --output=size / | tail -n1)
readonly disk_size_gb=$((${disk_size_bytes}/1024/1024))
# verify the system has minimum requirements met
if [[ "${physical_memory}" -lt "${MINIMUM_MEMORY}" ]]; then
@@ -30,7 +32,7 @@ if [[ "${physical_memory}" -lt "${MINIMUM_MEMORY}" ]]; then
fi
if [[ "${disk_size_gb}" -lt "${MINIMUM_DISK_SIZE_GB}" ]]; then
echo "Error: Cloudron requires atleast 20GB disk space (Disk space on ${disk_device} is ${disk_size_gb}GB)"
echo "Error: Cloudron requires atleast 20GB disk space (Disk space on / is ${disk_size_gb}GB)"
exit 1
fi
@@ -42,13 +44,19 @@ encryptionKey=""
restoreUrl=""
dnsProvider="manual"
tlsProvider="le-prod"
versionsUrl="https://s3.amazonaws.com/prod-cloudron-releases/versions.json"
requestedVersion="latest"
requestedVersion=""
apiServerOrigin="https://api.cloudron.io"
webServerOrigin="https://cloudron.io"
dataJson=""
prerelease=false
prerelease="false"
sourceTarballUrl=""
rebootServer="true"
baseDataDir=""
args=$(getopt -o "" -l "domain:,help,skip-baseimage-init,data:,provider:,encryption-key:,restore-url:,tls-provider:,version:,versions-url:,api-server:,dns-provider:,env:,prerelease" -n "$0" -- "$@")
# TODO this is still there for the restore case, see other occasions below
versionsUrl="https://s3.amazonaws.com/prod-cloudron-releases/versions.json"
args=$(getopt -o "" -l "domain:,help,skip-baseimage-init,data:,data-dir:,provider:,encryption-key:,restore-url:,tls-provider:,version:,dns-provider:,env:,prerelease,skip-reboot,source-url:" -n "$0" -- "$@")
eval set -- "${args}"
while true; do
@@ -63,22 +71,25 @@ while true; do
--version) requestedVersion="$2"; shift 2;;
--env)
if [[ "$2" == "dev" ]]; then
apiServerOrigin="https://api.dev.cloudron.io"
versionsUrl="https://s3.amazonaws.com/dev-cloudron-releases/versions.json"
apiServerOrigin="https://api.dev.cloudron.io"
webServerOrigin="https://dev.cloudron.io"
tlsProvider="le-staging"
prerelease="true"
elif [[ "$2" == "staging" ]]; then
apiServerOrigin="https://api.staging.cloudron.io"
versionsUrl="https://s3.amazonaws.com/staging-cloudron-releases/versions.json"
apiServerOrigin="https://api.staging.cloudron.io"
webServerOrigin="https://staging.cloudron.io"
tlsProvider="le-staging"
prerelease="true"
fi
shift 2;;
--versions-url) versionsUrl="$2"; shift 2;;
--api-server) apiServerOrigin="$2"; shift 2;;
--skip-baseimage-init) initBaseImage="false"; shift;;
--skip-reboot) rebootServer="false"; shift;;
--data) dataJson="$2"; shift 2;;
--prerelease) prerelease="true"; shift;;
--source-url) sourceTarballUrl="$2"; version="0.0.1+custom"; shift 2;;
--data-dir) baseDataDir=$(realpath "$2"); shift 2;;
--) break;;
*) echo "Unknown option $1"; exit 1;;
esac
@@ -87,15 +98,23 @@ done
# validate arguments in the absence of data
if [[ -z "${dataJson}" ]]; then
if [[ -z "${provider}" ]]; then
echo "--provider is required (generic, scaleway, ec2, digitalocean)"
echo "--provider is required (azure, digitalocean, ec2, lightsail, linode, ovh, rosehosting, scaleway, vultr or generic)"
exit 1
elif [[ \
"${provider}" != "generic" && \
"${provider}" != "scaleway" && \
"${provider}" != "ami" && \
"${provider}" != "azure" && \
"${provider}" != "digitalocean" && \
"${provider}" != "ec2" && \
"${provider}" != "digitalocean" \
"${provider}" != "gce" && \
"${provider}" != "lightsail" && \
"${provider}" != "linode" && \
"${provider}" != "ovh" && \
"${provider}" != "rosehosting" && \
"${provider}" != "scaleway" && \
"${provider}" != "vultr" && \
"${provider}" != "generic" \
]]; then
echo "--provider must be one of: generic, scaleway, ec2, digitalocean"
echo "--provider must be one of: azure, digitalocean, ec2, gce, lightsail, linode, ovh, rosehosting, scaleway, vultr or generic"
exit 1
fi
@@ -111,11 +130,16 @@ if [[ -z "${dataJson}" ]]; then
echo "--dns-provider must be one of : manual, noop"
exit 1
fi
if [[ -n "${baseDataDir}" && ! -d "${baseDataDir}" ]]; then
echo "${baseDataDir} does not exist"
exit 1
fi
fi
echo ""
echo "##############################################"
echo " Cloudron Setup (${requestedVersion}) "
echo " Cloudron Setup (${requestedVersion:-latest})"
echo "##############################################"
echo ""
echo " Follow setup logs in a second terminal with:"
@@ -125,7 +149,7 @@ echo " Join us at https://chat.cloudron.io for any questions."
echo ""
if [[ "${initBaseImage}" == "true" ]]; then
echo "=> Updating apt and installing script dependancies"
echo "=> Updating apt and installing script dependencies"
if ! apt-get update &>> "${LOG_FILE}"; then
echo "Could not update package repositories"
exit 1
@@ -138,19 +162,26 @@ if [[ "${initBaseImage}" == "true" ]]; then
fi
echo "=> Checking version"
releaseJson=$(curl -s "${versionsUrl}")
if [[ "$requestedVersion" == "latest" ]]; then
pre=$([[ "${prerelease}" == "true" ]] && echo "null" || echo "-pre")
version=$(echo "${releaseJson}" | python3 -c "import json,sys,collections;obj=json.load(sys.stdin, object_pairs_hook=collections.OrderedDict);latest=list(v for v in obj if '${pre}' not in v)[-1];print(latest)")
else
version="${requestedVersion}"
fi
if ! sourceTarballUrl=$(echo "${releaseJson}" | python3 -c 'import json,sys;obj=json.load(sys.stdin);print(obj[sys.argv[1]]["sourceTarballUrl"])' "${version}"); then
echo "No source code for version ${requestedVersion}"
exit 1
if [[ "${sourceTarballUrl}" == "" ]]; then
if ! releaseJson=$($curl -s "${apiServerOrigin}/api/v1/releases?prerelease=${prerelease}&boxVersion=${requestedVersion}"); then
echo "Failed to get release information"
exit 1
fi
if [[ "$requestedVersion" == "" ]]; then
version=$(echo "${releaseJson}" | python3 -c 'import json,sys;obj=json.load(sys.stdin);print(obj["version"])')
else
version="${requestedVersion}"
fi
if ! sourceTarballUrl=$(echo "${releaseJson}" | python3 -c 'import json,sys;obj=json.load(sys.stdin);print(obj["info"]["sourceTarballUrl"])'); then
echo "No source code for version '${requestedVersion:-latest}'"
exit 1
fi
fi
# Build data
# TODO versionsUrl is still there for the cloudron restore case
if [[ -z "${dataJson}" ]]; then
if [[ -z "${restoreUrl}" ]]; then
data=$(cat <<EOF
@@ -159,6 +190,7 @@ if [[ -z "${dataJson}" ]]; then
"fqdn": "${domain}",
"provider": "${provider}",
"apiServerOrigin": "${apiServerOrigin}",
"webServerOrigin": "${webServerOrigin}",
"tlsConfig": {
"provider": "${tlsProvider}"
},
@@ -168,7 +200,8 @@ if [[ -z "${dataJson}" ]]; then
"backupConfig" : {
"provider": "filesystem",
"backupFolder": "/var/backups",
"key": "${encryptionKey}"
"key": "${encryptionKey}",
"retentionSecs": 172800
},
"updateConfig": {
"prerelease": ${prerelease}
@@ -184,6 +217,7 @@ EOF
"fqdn": "${domain}",
"provider": "${provider}",
"apiServerOrigin": "${apiServerOrigin}",
"webServerOrigin": "${webServerOrigin}",
"restore": {
"url": "${restoreUrl}",
"key": "${encryptionKey}"
@@ -200,7 +234,7 @@ fi
echo "=> Downloading version ${version} ..."
box_src_tmp_dir=$(mktemp -dt box-src-XXXXXX)
if ! curl -sL "${sourceTarballUrl}" | tar -zxf - -C "${box_src_tmp_dir}"; then
if ! $curl -sL "${sourceTarballUrl}" | tar -zxf - -C "${box_src_tmp_dir}"; then
echo "Could not download source tarball. See ${LOG_FILE} for details"
exit 1
fi
@@ -215,29 +249,38 @@ if [[ "${initBaseImage}" == "true" ]]; then
fi
echo "=> Installing version ${version} (this takes some time) ..."
if ! /bin/bash "${box_src_tmp_dir}/scripts/installer.sh" --data "${data}" &>> "${LOG_FILE}"; then
echo "Failed to install cloudron. See ${LOG_FILE} for details"
exit 1
echo "${data}" > "${DATA_FILE}"
# poor mans semver
if [[ ${version} == "0.10"* ]]; then
if ! /bin/bash "${box_src_tmp_dir}/scripts/installer.sh" --data-file "${DATA_FILE}" &>> "${LOG_FILE}"; then
echo "Failed to install cloudron. See ${LOG_FILE} for details"
exit 1
fi
else
if ! /bin/bash "${box_src_tmp_dir}/scripts/installer.sh" --data-file "${DATA_FILE}" --data-dir "${baseDataDir}" &>> "${LOG_FILE}"; then
echo "Failed to install cloudron. See ${LOG_FILE} for details"
exit 1
fi
fi
rm "${DATA_FILE}"
echo -n "=> Waiting for cloudron to be ready (this takes some time) ..."
while true; do
echo -n "."
if status=$(curl -q -f "http://localhost:3000/api/v1/cloudron/status" 2>/dev/null); then
if status=$($curl -q -f "http://localhost:3000/api/v1/cloudron/status" 2>/dev/null); then
[[ -z "$domain" ]] && break # with no domain, we are up and running
[[ "$status" == *"\"tls\": true"* ]] && break # with a domain, wait for the cert
fi
sleep 10
done
echo -e "\n\nRebooting this server now to let bootloader changes take effect.\n"
if [[ -n "${domain}" ]]; then
echo -e "Visit https://my.${domain} to finish setup once the server has rebooted.\n"
echo -e "\n\nVisit https://my.${domain} to finish setup once the server has rebooted.\n"
else
echo -e "Visit https://<IP> to finish setup once the server has rebooted.\n"
echo -e "\n\nVisit https://<IP> to finish setup once the server has rebooted.\n"
fi
if [[ "${initBaseImage}" == "true" ]]; then
if [[ "${rebootServer}" == "true" ]]; then
echo -e "\n\nRebooting this server now to let bootloader changes take effect.\n"
systemctl reboot
fi
+3 -26
View File
@@ -2,30 +2,23 @@
set -eu
assertNotEmpty() {
: "${!1:? "$1 is not set."}"
}
# Only GNU getopt supports long options. OS X comes bundled with the BSD getopt
# brew install gnu-getopt to get the GNU getopt on OS X
[[ $(uname -s) == "Darwin" ]] && GNU_GETOPT="/usr/local/opt/gnu-getopt/bin/getopt" || GNU_GETOPT="getopt"
readonly GNU_GETOPT
args=$(${GNU_GETOPT} -o "" -l "revision:,output:,no-upload" -n "$0" -- "$@")
args=$(${GNU_GETOPT} -o "" -l "revision:,output:" -n "$0" -- "$@")
eval set -- "${args}"
readonly SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
delete_bundle="yes"
commitish="HEAD"
upload="yes"
bundle_file=""
while true; do
case "$1" in
--revision) commitish="$2"; shift 2;;
--output) bundle_file="$2"; delete_bundle="no"; shift 2;;
--no-upload) upload="no"; shift;;
--output) bundle_file="$2"; shift 2;;
--) break;;
*) echo "Unknown option $1"; exit 1;;
esac
@@ -90,21 +83,5 @@ echo "Create final tarball"
echo "Cleaning up ${bundle_dir}"
rm -rf "${bundle_dir}"
if [[ "${upload}" == "yes" ]]; then
echo "Uploading bundle to S3"
echo "Tarball saved at ${bundle_file}"
assertNotEmpty AWS_DEV_ACCESS_KEY
assertNotEmpty AWS_DEV_SECRET_KEY
# That special header is needed to allow access with singed urls created with different aws credentials than the ones the file got uploaded
s3cmd --multipart-chunk-size-mb=5 --ssl --acl-public --access_key="${AWS_DEV_ACCESS_KEY}" --secret_key="${AWS_DEV_SECRET_KEY}" --no-mime-magic put "${bundle_file}" "s3://dev-cloudron-releases/box-${version}.tar.gz"
versions_file_url="https://dev-cloudron-releases.s3.amazonaws.com/box-${version}.tar.gz"
echo "The URL for the versions file is: ${versions_file_url}"
fi
if [[ "${delete_bundle}" == "no" ]]; then
echo "Tarball preserved at ${bundle_file}"
else
rm "${bundle_file}"
fi
+18 -2
View File
@@ -9,22 +9,26 @@ fi
readonly USER=yellowtent
readonly BOX_SRC_DIR=/home/${USER}/box
readonly BASE_DATA_DIR=/home/${USER}
readonly CLOUDRON_CONF=/home/yellowtent/configs/cloudron.conf
readonly curl="curl --fail --connect-timeout 20 --retry 10 --retry-delay 2 --max-time 2400"
readonly script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly box_src_tmp_dir="$(realpath ${script_dir}/..)"
readonly is_update=$([[ -f "${CLOUDRON_CONF}" ]] && echo "yes" || echo "no")
arg_data=""
arg_data_dir=""
args=$(getopt -o "" -l "data:,data-file:" -n "$0" -- "$@")
args=$(getopt -o "" -l "data:,data-file:,data-dir:" -n "$0" -- "$@")
eval set -- "${args}"
while true; do
case "$1" in
--data) arg_data="$2"; shift 2;;
--data-file) arg_data=$(cat $2); shift 2;;
--data-dir) arg_data_dir="$2"; shift 2;;
--) break;;
*) echo "Unknown option $1"; exit 1;;
esac
@@ -52,13 +56,25 @@ fi
if [[ "${is_update}" == "yes" ]]; then
echo "Setting up update splash screen"
"${box_src_tmp_dir}/setup/splashpage.sh" --data "${arg_data}" # show splash from new code
"${box_src_tmp_dir}/setup/splashpage.sh" --data "${arg_data}" || true # show splash from new code
${BOX_SRC_DIR}/setup/stop.sh # stop the old code
fi
# setup links to data directory
if [[ -n "${arg_data_dir}" ]]; then
echo "==> installer: setting up links to data directory"
mkdir "${arg_data_dir}/appsdata"
ln -s "${arg_data_dir}/appsdata" "${BASE_DATA_DIR}/appsdata"
mkdir "${arg_data_dir}/platformdata"
ln -s "${arg_data_dir}/platformdata" "${BASE_DATA_DIR}/platformdata"
fi
# ensure we are not inside the source directory, which we will remove now
cd /root
echo "==> installer: updating packages"
# add logic to update apt packages here
echo "==> installer: switching the box code"
rm -rf "${BOX_SRC_DIR}"
mv "${box_src_tmp_dir}" "${BOX_SRC_DIR}"
+6 -7
View File
@@ -5,7 +5,6 @@ json="${source_dir}/../node_modules/.bin/json"
# IMPORTANT: Fix cloudron.js:doUpdate if you add/remove any arg. keep these sorted for readability
arg_api_server_origin=""
arg_box_versions_url=""
arg_fqdn=""
arg_is_custom_domain="false"
arg_restore_key=""
@@ -50,8 +49,6 @@ while true; do
[[ "${arg_api_server_origin}" == "" ]] && arg_api_server_origin="https://api.cloudron.io"
arg_web_server_origin=$(echo "$2" | $json webServerOrigin)
[[ "${arg_web_server_origin}" == "" ]] && arg_web_server_origin="https://cloudron.io"
arg_box_versions_url=$(echo "$2" | $json boxVersionsUrl)
[[ "${arg_box_versions_url}" == "" ]] && arg_box_versions_url="https://s3.amazonaws.com/prod-cloudron-releases/versions.json"
# TODO check if an where this is used
arg_version=$(echo "$2" | $json version)
@@ -64,7 +61,9 @@ while true; do
[[ "${arg_is_demo}" == "" ]] && arg_is_demo="false"
arg_tls_cert=$(echo "$2" | $json tlsCert)
[[ "${arg_tls_cert}" == "null" ]] && arg_tls_cert=""
arg_tls_key=$(echo "$2" | $json tlsKey)
[[ "${arg_tls_key}" == "null" ]] && arg_tls_key=""
arg_token=$(echo "$2" | $json token)
arg_provider=$(echo "$2" | $json provider)
@@ -97,14 +96,14 @@ done
echo "Parsed arguments:"
echo "api server: ${arg_api_server_origin}"
echo "box versions url: ${arg_box_versions_url}"
echo "fqdn: ${arg_fqdn}"
echo "custom domain: ${arg_is_custom_domain}"
echo "restore key: ${arg_restore_key}"
echo "restore url: ${arg_restore_url}"
echo "tls cert: ${arg_tls_cert}"
echo "tls key: ${arg_tls_key}"
echo "token: ${arg_token}"
# do not dump these as they might become available via logs API
#echo "restore key: ${arg_restore_key}"
#echo "tls key: ${arg_tls_key}"
#echo "token: ${arg_token}"
echo "tlsConfig: ${arg_tls_config}"
echo "version: ${arg_version}"
echo "web server: ${arg_web_server_origin}"
+10 -5
View File
@@ -6,11 +6,16 @@ readonly SETUP_WEBSITE_DIR="/home/yellowtent/setup/website"
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly box_src_dir="$(realpath ${script_dir}/..)"
readonly DATA_DIR="/home/yellowtent/data"
readonly PLATFORM_DATA_DIR="/home/yellowtent/platformdata"
readonly ADMIN_LOCATION="my" # keep this in sync with constants.js
echo "Setting up nginx update page"
if [[ ! -f "${PLATFORM_DATA_DIR}/nginx/applications/admin.conf" ]]; then
echo "No admin.conf found. This Cloudron has no domain yet. Skip splash setup"
exit
fi
source "${script_dir}/argparser.sh" "$@" # this injects the arg_* variables used below
# keep this is sync with config.js appFqdn()
@@ -24,16 +29,16 @@ cp -r "${script_dir}/splash/website/"* "${SETUP_WEBSITE_DIR}"
# create nginx config
readonly current_infra=$(node -e "console.log(require('${script_dir}/../src/infra_version.js').version);")
existing_infra="none"
[[ -f "${DATA_DIR}/INFRA_VERSION" ]] && existing_infra=$(node -e "console.log(JSON.parse(require('fs').readFileSync('${DATA_DIR}/INFRA_VERSION', 'utf8')).version);")
[[ -f "${PLATFORM_DATA_DIR}/INFRA_VERSION" ]] && existing_infra=$(node -e "console.log(JSON.parse(require('fs').readFileSync('${PLATFORM_DATA_DIR}/INFRA_VERSION', 'utf8')).version);")
if [[ "${arg_retire_reason}" != "" || "${existing_infra}" != "${current_infra}" ]]; then
echo "Showing progress bar on all subdomains in retired mode or infra update. retire: ${arg_retire_reason} existing: ${existing_infra} current: ${current_infra}"
rm -f ${DATA_DIR}/nginx/applications/*
rm -f ${PLATFORM_DATA_DIR}/nginx/applications/*
${box_src_dir}/node_modules/.bin/ejs-cli -f "${script_dir}/start/nginx/appconfig.ejs" \
-O "{ \"vhost\": \"~^(.+)\$\", \"adminOrigin\": \"${admin_origin}\", \"endpoint\": \"splash\", \"sourceDir\": \"${SETUP_WEBSITE_DIR}\", \"certFilePath\": \"cert/host.cert\", \"keyFilePath\": \"cert/host.key\", \"xFrameOptions\": \"SAMEORIGIN\" }" > "${DATA_DIR}/nginx/applications/admin.conf"
-O "{ \"vhost\": \"~^(.+)\$\", \"adminOrigin\": \"${admin_origin}\", \"endpoint\": \"splash\", \"sourceDir\": \"${SETUP_WEBSITE_DIR}\", \"certFilePath\": \"cert/host.cert\", \"keyFilePath\": \"cert/host.key\", \"xFrameOptions\": \"SAMEORIGIN\" }" > "${PLATFORM_DATA_DIR}/nginx/applications/admin.conf"
else
echo "Show progress bar only on admin domain for normal update"
${box_src_dir}/node_modules/.bin/ejs-cli -f "${script_dir}/start/nginx/appconfig.ejs" \
-O "{ \"vhost\": \"${admin_fqdn}\", \"adminOrigin\": \"${admin_origin}\", \"endpoint\": \"splash\", \"sourceDir\": \"${SETUP_WEBSITE_DIR}\", \"certFilePath\": \"cert/host.cert\", \"keyFilePath\": \"cert/host.key\", \"xFrameOptions\": \"SAMEORIGIN\" }" > "${DATA_DIR}/nginx/applications/admin.conf"
-O "{ \"vhost\": \"${admin_fqdn}\", \"adminOrigin\": \"${admin_origin}\", \"endpoint\": \"splash\", \"sourceDir\": \"${SETUP_WEBSITE_DIR}\", \"certFilePath\": \"cert/host.cert\", \"keyFilePath\": \"cert/host.key\", \"xFrameOptions\": \"SAMEORIGIN\" }" > "${PLATFORM_DATA_DIR}/nginx/applications/admin.conf"
fi
if [[ "${arg_retire_reason}" == "migrate" ]]; then
+89 -102
View File
@@ -5,10 +5,11 @@ set -eu -o pipefail
echo "==> Cloudron Start"
readonly USER="yellowtent"
readonly DATA_FILE="/root/user_data.img"
readonly HOME_DIR="/home/${USER}"
readonly BOX_SRC_DIR="${HOME_DIR}/box"
readonly DATA_DIR="${HOME_DIR}/data" # app and platform data
readonly OLD_DATA_DIR="${HOME_DIR}/data";
readonly PLATFORM_DATA_DIR="${HOME_DIR}/platformdata" # platform data
readonly APPS_DATA_DIR="${HOME_DIR}/appsdata" # app data
readonly BOX_DATA_DIR="${HOME_DIR}/boxdata" # box data
readonly CONFIG_DIR="${HOME_DIR}/configs"
readonly SETUP_PROGRESS_JSON="${HOME_DIR}/setup/website/progress.json"
@@ -33,36 +34,6 @@ timedatectl set-ntp 1
timedatectl set-timezone UTC
hostnamectl set-hostname "${arg_fqdn}"
echo "==> Setting up firewall"
iptables -t filter -N CLOUDRON || true
iptables -t filter -F CLOUDRON # empty any existing rules
# NOTE: keep these in sync with src/apps.js validatePortBindings
# allow ssh, http, https, ping, dns
iptables -t filter -I CLOUDRON -m state --state RELATED,ESTABLISHED -j ACCEPT
# caas has ssh on port 202
if [[ "${arg_provider}" == "caas" ]]; then
iptables -A CLOUDRON -p tcp -m tcp -m multiport --dports 25,80,202,443,587,993,4190 -j ACCEPT
else
iptables -A CLOUDRON -p tcp -m tcp -m multiport --dports 25,80,22,443,587,993,4190 -j ACCEPT
fi
iptables -t filter -A CLOUDRON -p icmp --icmp-type echo-request -j ACCEPT
iptables -t filter -A CLOUDRON -p icmp --icmp-type echo-reply -j ACCEPT
iptables -t filter -A CLOUDRON -p udp --sport 53 -j ACCEPT
iptables -t filter -A CLOUDRON -s 172.18.0.0/16 -j ACCEPT # required to accept any connections from apps to our IP:<public port>
iptables -t filter -A CLOUDRON -i lo -j ACCEPT # required for localhost connections (mysql)
# log dropped incoming. keep this at the end of all the rules
iptables -t filter -A CLOUDRON -m limit --limit 2/min -j LOG --log-prefix "IPTables Packet Dropped: " --log-level 7
iptables -t filter -A CLOUDRON -j DROP
if ! iptables -t filter -C INPUT -j CLOUDRON 2>/dev/null; then
iptables -t filter -I INPUT -j CLOUDRON
fi
# so it gets restored across reboot
mkdir -p /etc/iptables && iptables-save > /etc/iptables/rules.v4
echo "==> Configuring docker"
cp "${script_dir}/start/docker-cloudron-app.apparmor" /etc/apparmor.d/docker-cloudron-app
systemctl enable apparmor
@@ -71,7 +42,7 @@ systemctl restart apparmor
usermod ${USER} -a -G docker
temp_file=$(mktemp)
# create systemd drop-in. some apps do not work with aufs
echo -e "[Service]\nExecStart=\nExecStart=/usr/bin/docker daemon -H fd:// --log-driver=journald --exec-opt native.cgroupdriver=cgroupfs --storage-driver=devicemapper --dns=172.18.0.1 --dns-search=." > "${temp_file}"
echo -e "[Service]\nExecStart=\nExecStart=/usr/bin/dockerd -H fd:// --log-driver=journald --exec-opt native.cgroupdriver=cgroupfs --storage-driver=devicemapper" > "${temp_file}"
systemctl enable docker
# restart docker if options changed
@@ -96,52 +67,55 @@ if [[ "${arg_provider}" == "caas" ]]; then
systemctl reload sshd
fi
echo "==> Setup btrfs data"
if ! grep -q loop.ko /lib/modules/`uname -r`/modules.builtin; then
# on scaleway loop is not built-in
echo "loop" >> /etc/modules
modprobe loop
fi
if [[ ! -d "${DATA_DIR}" ]]; then
echo "==> Mounting loopback btrfs"
truncate -s "8192m" "${DATA_FILE}" # 8gb start (this will get resized dynamically by cloudron-resize-fs.service)
mkfs.btrfs -L UserDataHome "${DATA_FILE}"
mkdir -p "${DATA_DIR}"
mount -t btrfs -o loop,nosuid "${DATA_FILE}" ${DATA_DIR}
fi
mkdir -p "${BOX_DATA_DIR}"
mkdir -p "${APPS_DATA_DIR}"
mkdir -p "${PLATFORM_DATA_DIR}"
# keep these in sync with paths.js
echo "==> Ensuring directories"
if ! btrfs subvolume show "${DATA_DIR}/mail" &> /dev/null; then
# Migrate mail data to new format
docker stop mail || true # otherwise the move below might fail if mail container writes in the middle
rm -rf "${DATA_DIR}/mail" # this used to be mail container's run directory
btrfs subvolume create "${DATA_DIR}/mail"
[[ -d "${DATA_DIR}/box/mail" ]] && mv "${DATA_DIR}/box/mail/"* "${DATA_DIR}/mail"
rm -rf "${DATA_DIR}/box/mail"
if [[ ! -d "${PLATFORM_DATA_DIR}/mail" ]]; then
if [[ -d "${OLD_DATA_DIR}/mail" ]]; then
echo "==> Migrate old mail data"
# Migrate mail data to new format
docker stop mail || true # otherwise the move below might fail if mail container writes in the middle
mkdir -p "${PLATFORM_DATA_DIR}/mail"
# we can't move the whole folder as it is a btrfs subvolume mount
mv -f "${OLD_DATA_DIR}/mail/"* "${PLATFORM_DATA_DIR}/mail/" # this used to be mail container's run directory
else
echo "==> Create new mail data dir"
mkdir -p "${PLATFORM_DATA_DIR}/mail"
fi
fi
mkdir -p "${DATA_DIR}/graphite"
mkdir -p "${DATA_DIR}/mail/dkim"
mkdir -p "${DATA_DIR}/mysql"
mkdir -p "${DATA_DIR}/postgresql"
mkdir -p "${DATA_DIR}/mongodb"
mkdir -p "${DATA_DIR}/snapshots"
mkdir -p "${DATA_DIR}/addons/mail"
mkdir -p "${DATA_DIR}/collectd/collectd.conf.d"
mkdir -p "${DATA_DIR}/acme"
mkdir -p "${PLATFORM_DATA_DIR}/graphite"
mkdir -p "${PLATFORM_DATA_DIR}/mail/dkim"
mkdir -p "${PLATFORM_DATA_DIR}/mysql"
mkdir -p "${PLATFORM_DATA_DIR}/postgresql"
mkdir -p "${PLATFORM_DATA_DIR}/mongodb"
mkdir -p "${PLATFORM_DATA_DIR}/snapshots"
mkdir -p "${PLATFORM_DATA_DIR}/addons/mail"
mkdir -p "${PLATFORM_DATA_DIR}/collectd/collectd.conf.d"
mkdir -p "${PLATFORM_DATA_DIR}/acme"
mkdir -p "${BOX_DATA_DIR}"
if btrfs subvolume show "${DATA_DIR}/box" &> /dev/null; then
# Migrate box data out of data volume
mv "${DATA_DIR}/box/"* "${BOX_DATA_DIR}"
btrfs subvolume delete "${DATA_DIR}/box"
fi
mkdir -p "${BOX_DATA_DIR}/appicons"
mkdir -p "${BOX_DATA_DIR}/certs"
mkdir -p "${BOX_DATA_DIR}/acme" # acme keys
# ensure backups folder exists and is writeable
mkdir -p /var/backups
chmod 777 /var/backups
echo "==> Check for old btrfs volumes"
if mountpoint -q "${OLD_DATA_DIR}"; then
echo "==> Cleanup btrfs volumes"
# First stop all container to be able to unmount
docker ps -q | xargs docker stop
umount "${OLD_DATA_DIR}"
rm -rf "/root/user_data.img"
else
echo "==> No btrfs volumes found";
fi
echo "==> Configuring journald"
sed -e "s/^#SystemMaxUse=.*$/SystemMaxUse=100M/" \
-e "s/^#ForwardToSyslog=.*$/ForwardToSyslog=no/" \
@@ -167,14 +141,17 @@ echo "==> Setting up unbound"
# DO uses Google nameservers by default. This causes RBL queries to fail (host 2.0.0.127.zen.spamhaus.org)
# We do not use dnsmasq because it is not a recursive resolver and defaults to the value in the interfaces file (which is Google DNS!)
# We listen on 0.0.0.0 because there is no way control ordering of docker (which creates the 172.18.0.0/16) and unbound
echo -e "server:\n\tinterface: 0.0.0.0\n\taccess-control: 127.0.0.1 allow\n\taccess-control: 172.18.0.1/16 allow" > /etc/unbound/unbound.conf.d/cloudron-network.conf
echo -e "server:\n\tinterface: 0.0.0.0\n\taccess-control: 127.0.0.1 allow\n\taccess-control: 172.18.0.1/16 allow\n\tcache-max-negative-ttl: 30" > /etc/unbound/unbound.conf.d/cloudron-network.conf
echo "==> Adding systemd services"
cp -r "${script_dir}/start/systemd/." /etc/systemd/system/
systemctl daemon-reload
systemctl enable unbound
systemctl enable cloudron.target
systemctl enable iptables-restore
systemctl enable cloudron-firewall
# update firewall rules
systemctl restart cloudron-firewall
# For logrotate
systemctl enable --now cron
@@ -188,19 +165,19 @@ cp "${script_dir}/start/sudoers" /etc/sudoers.d/${USER}
echo "==> Configuring collectd"
rm -rf /etc/collectd
ln -sfF "${DATA_DIR}/collectd" /etc/collectd
cp "${script_dir}/start/collectd.conf" "${DATA_DIR}/collectd/collectd.conf"
ln -sfF "${PLATFORM_DATA_DIR}/collectd" /etc/collectd
cp "${script_dir}/start/collectd.conf" "${PLATFORM_DATA_DIR}/collectd/collectd.conf"
systemctl restart collectd
echo "==> Configuring nginx"
# link nginx config to system config
unlink /etc/nginx 2>/dev/null || rm -rf /etc/nginx
ln -s "${DATA_DIR}/nginx" /etc/nginx
mkdir -p "${DATA_DIR}/nginx/applications"
mkdir -p "${DATA_DIR}/nginx/cert"
cp "${script_dir}/start/nginx/nginx.conf" "${DATA_DIR}/nginx/nginx.conf"
cp "${script_dir}/start/nginx/mime.types" "${DATA_DIR}/nginx/mime.types"
if ! grep "^Restart=" /etc/systemd/system/multi-user.target.wants/nginx.service; then
ln -s "${PLATFORM_DATA_DIR}/nginx" /etc/nginx
mkdir -p "${PLATFORM_DATA_DIR}/nginx/applications"
mkdir -p "${PLATFORM_DATA_DIR}/nginx/cert"
cp "${script_dir}/start/nginx/nginx.conf" "${PLATFORM_DATA_DIR}/nginx/nginx.conf"
cp "${script_dir}/start/nginx/mime.types" "${PLATFORM_DATA_DIR}/nginx/mime.types"
if ! grep -q "^Restart=" /etc/systemd/system/multi-user.target.wants/nginx.service; then
# default nginx service file does not restart on crash
echo -e "\n[Service]\nRestart=always\n" >> /etc/systemd/system/multi-user.target.wants/nginx.service
systemctl daemon-reload
@@ -208,22 +185,21 @@ fi
systemctl start nginx
# bookkeep the version as part of data
echo "{ \"version\": \"${arg_version}\", \"boxVersionsUrl\": \"${arg_box_versions_url}\" }" > "${BOX_DATA_DIR}/version"
# remove old snapshots. if we do want to keep this around, we will have to fix the chown -R below
# which currently fails because these are readonly fs
echo "==> Cleaning up snapshots"
find "${DATA_DIR}/snapshots" -mindepth 1 -maxdepth 1 | xargs --no-run-if-empty btrfs subvolume delete
echo "{ \"version\": \"${arg_version}\", \"apiServerOrigin\": \"${arg_api_server_origin}\" }" > "${BOX_DATA_DIR}/version"
# restart mysql to make sure it has latest config
# wait for all running mysql jobs
cp "${script_dir}/start/mysql.cnf" /etc/mysql/mysql.cnf
while true; do
if ! systemctl list-jobs | grep mysql; then break; fi
echo "Waiting for mysql jobs..."
sleep 1
done
systemctl restart mysql
if [[ ! -f /etc/mysql/mysql.cnf ]] || ! diff -q "${script_dir}/start/mysql.cnf" /etc/mysql/mysql.cnf >/dev/null; then
# wait for all running mysql jobs
cp "${script_dir}/start/mysql.cnf" /etc/mysql/mysql.cnf
while true; do
if ! systemctl list-jobs | grep mysql; then break; fi
echo "Waiting for mysql jobs..."
sleep 1
done
systemctl restart mysql
else
systemctl start mysql
fi
readonly mysql_root_password="password"
mysqladmin -u root -ppassword password password # reset default root password
@@ -232,11 +208,18 @@ mysql -u root -p${mysql_root_password} -e 'CREATE DATABASE IF NOT EXISTS box'
if [[ -n "${arg_restore_url}" ]]; then
set_progress "30" "Downloading restore data"
echo "==> Downloading backup: ${arg_restore_url} and key: ${arg_restore_key}"
decrypt=""
if [[ "${arg_restore_url}" == *.tar.gz.enc || -n "${arg_restore_key}" ]]; then
echo "==> Downloading encrypted backup: ${arg_restore_url} and key: ${arg_restore_key}"
decrypt=(openssl aes-256-cbc -d -nosalt -pass "pass:${arg_restore_key}")
else
echo "==> Downloading backup: ${arg_restore_url}"
decrypt=(cat -)
fi
while true; do
if $curl -L "${arg_restore_url}" | openssl aes-256-cbc -d -pass "pass:${arg_restore_key}" \
| tar -zxf - --overwrite --transform="s,^box/\?,boxdata/," --transform="s,^mail/\?,data/mail/," --show-transformed-names -C "${HOME_DIR}"; then break; fi
if $curl -L "${arg_restore_url}" | "${decrypt[@]}" \
| tar -zxf - --overwrite --transform="s,^box/\?,boxdata/," --transform="s,^mail/\?,platformdata/mail/," --show-transformed-names -C "${HOME_DIR}"; then break; fi
echo "Failed to download data, trying again"
done
@@ -263,7 +246,6 @@ cat > "${CONFIG_DIR}/cloudron.conf" <<CONF_END
"webServerOrigin": "${arg_web_server_origin}",
"fqdn": "${arg_fqdn}",
"isCustomDomain": ${arg_is_custom_domain},
"boxVersionsUrl": "${arg_box_versions_url}",
"provider": "${arg_provider}",
"isDemo": ${arg_is_demo},
"database": {
@@ -291,11 +273,11 @@ CONF_END
echo "==> Changing ownership"
chown "${USER}:${USER}" -R "${CONFIG_DIR}"
chown "${USER}:${USER}" -R "${DATA_DIR}/nginx" "${DATA_DIR}/collectd" "${DATA_DIR}/addons" "${DATA_DIR}/acme"
chown "${USER}:${USER}" -R "${PLATFORM_DATA_DIR}/nginx" "${PLATFORM_DATA_DIR}/collectd" "${PLATFORM_DATA_DIR}/addons" "${PLATFORM_DATA_DIR}/acme"
chown "${USER}:${USER}" -R "${BOX_DATA_DIR}"
chown "${USER}:${USER}" -R "${DATA_DIR}/mail/dkim" # this is owned by box currently since it generates the keys
chown "${USER}:${USER}" "${DATA_DIR}/INFRA_VERSION" 2>/dev/null || true
chown "${USER}:${USER}" "${DATA_DIR}"
chown "${USER}:${USER}" -R "${PLATFORM_DATA_DIR}/mail/dkim" # this is owned by box currently since it generates the keys
chown "${USER}:${USER}" "${PLATFORM_DATA_DIR}/INFRA_VERSION" 2>/dev/null || true
chown "${USER}:${USER}" "${PLATFORM_DATA_DIR}"
echo "==> Adding automated configs"
if [[ ! -z "${arg_backup_config}" ]]; then
@@ -318,9 +300,14 @@ if [[ ! -z "${arg_tls_config}" ]]; then
-e "REPLACE INTO settings (name, value) VALUES (\"tls_config\", '$arg_tls_config')" box
fi
echo "==> Generating dhparams (takes forever)"
if [[ ! -f "${BOX_DATA_DIR}/dhparams.pem" ]]; then
openssl dhparam -out "${BOX_DATA_DIR}/dhparams.pem" 2048
fi
set_progress "60" "Starting Cloudron"
systemctl start cloudron.target
sleep 2 # give systemd sometime to start the processes
set_progress "90" "Done"
set_progress "90" "Almost done"
+75
View File
@@ -0,0 +1,75 @@
#!/bin/bash
set -eu -o pipefail
echo "==> Setting up firewall"
iptables -t filter -N CLOUDRON || true
iptables -t filter -F CLOUDRON # empty any existing rules
# NOTE: keep these in sync with src/apps.js validatePortBindings
# allow ssh, http, https, ping, dns
iptables -t filter -I CLOUDRON -m state --state RELATED,ESTABLISHED -j ACCEPT
# caas has ssh on port 202
iptables -A CLOUDRON -p tcp -m tcp -m multiport --dports 22,25,80,202,443,587,993,4190 -j ACCEPT
iptables -t filter -A CLOUDRON -p icmp --icmp-type echo-request -j ACCEPT
iptables -t filter -A CLOUDRON -p icmp --icmp-type echo-reply -j ACCEPT
iptables -t filter -A CLOUDRON -p udp --sport 53 -j ACCEPT
iptables -t filter -A CLOUDRON -s 172.18.0.0/16 -j ACCEPT # required to accept any connections from apps to our IP:<public port>
iptables -t filter -A CLOUDRON -i lo -j ACCEPT # required for localhost connections (mysql)
# log dropped incoming. keep this at the end of all the rules
iptables -t filter -A CLOUDRON -m limit --limit 2/min -j LOG --log-prefix "IPTables Packet Dropped: " --log-level 7
iptables -t filter -A CLOUDRON -j DROP
if ! iptables -t filter -C INPUT -j CLOUDRON 2>/dev/null; then
iptables -t filter -I INPUT -j CLOUDRON
fi
# Setup rate limit chain (the recent info is at /proc/net/xt_recent)
iptables -t filter -N CLOUDRON_RATELIMIT || true
iptables -t filter -F CLOUDRON_RATELIMIT # empty any existing rules
# log dropped incoming. keep this at the end of all the rules
iptables -t filter -N CLOUDRON_RATELIMIT_LOG || true
iptables -t filter -F CLOUDRON_RATELIMIT_LOG # empty any existing rules
iptables -t filter -A CLOUDRON_RATELIMIT_LOG -m limit --limit 2/min -j LOG --log-prefix "IPTables RateLimit: " --log-level 7
iptables -t filter -A CLOUDRON_RATELIMIT_LOG -j DROP
# http https
for port in 80 443; do
iptables -A CLOUDRON_RATELIMIT -p tcp --syn --dport ${port} -m connlimit --connlimit-above 5000 -j CLOUDRON_RATELIMIT_LOG
done
# ssh smtp ssh msa imap sieve
for port in 22 202; do
iptables -A CLOUDRON_RATELIMIT -p tcp --dport ${port} -m state --state NEW -m recent --set --name "public-${port}"
iptables -A CLOUDRON_RATELIMIT -p tcp --dport ${port} -m state --state NEW -m recent --update --name "public-${port}" --seconds 10 --hitcount 5 -j CLOUDRON_RATELIMIT_LOG
done
# TODO: move docker platform rules to platform.js so it can be specialized to rate limit only when destination is the mail container
# docker translates (dnat) 25, 587, 993, 4190 in the PREROUTING step
for port in 2525 4190 9993; do
iptables -A CLOUDRON_RATELIMIT -p tcp --syn ! -s 172.18.0.0/16 -d 172.18.0.0/16 --dport ${port} -m connlimit --connlimit-above 50 -j CLOUDRON_RATELIMIT_LOG
done
# msa, ldap, imap, sieve
for port in 2525 3002 4190 9993; do
iptables -A CLOUDRON_RATELIMIT -p tcp --syn -s 172.18.0.0/16 -d 172.18.0.0/16 --dport ${port} -m connlimit --connlimit-above 500 -j CLOUDRON_RATELIMIT_LOG
done
# cloudron docker network: mysql postgresql redis mongodb
for port in 3306 5432 6379 27017; do
iptables -A CLOUDRON_RATELIMIT -p tcp --syn -s 172.18.0.0/16 -d 172.18.0.0/16 --dport ${port} -m connlimit --connlimit-above 5000 -j CLOUDRON_RATELIMIT_LOG
done
# For ssh, http, https
if ! iptables -t filter -C INPUT -j CLOUDRON_RATELIMIT 2>/dev/null; then
iptables -t filter -I INPUT 1 -j CLOUDRON_RATELIMIT
fi
# For smtp, imap etc routed via docker/nat
# Workaroud issue where Docker insists on adding itself first in FORWARD table
iptables -D FORWARD -j CLOUDRON_RATELIMIT || true
iptables -I FORWARD 1 -j CLOUDRON_RATELIMIT
+22 -29
View File
@@ -2,49 +2,42 @@
set -eu -o pipefail
readonly USER_HOME="/home/yellowtent"
readonly APPS_SWAP_FILE="/apps.swap"
readonly USER_DATA_FILE="/root/user_data.img"
readonly USER_DATA_DIR="/home/yellowtent/data"
# detect device of rootfs (http://forums.fedoraforum.org/showthread.php?t=270316)
disk_device="$(for d in $(find /dev -type b); do [ "$(mountpoint -d /)" = "$(mountpoint -x $d)" ] && echo $d && break; done)"
existing_swap=$(cat /proc/meminfo | grep SwapTotal | awk '{ printf "%.0f", $2/1024 }')
# all sizes are in mb
readonly physical_memory=$(free -m | awk '/Mem:/ { print $2 }')
readonly swap_size=$((${physical_memory} - ${existing_swap})) # if you change this, fix enoughResourcesAvailable() in client.js
readonly physical_memory=$(LC_ALL=C free -m | awk '/Mem:/ { print $2 }')
readonly swap_size=$((${physical_memory} > 4096 ? 4096 : ${physical_memory})) # min(RAM, 4GB) if you change this, fix enoughResourcesAvailable() in client.js
readonly app_count=$((${physical_memory} / 200)) # estimated app count
readonly disk_size_bytes=$(fdisk -l ${disk_device} | grep "Disk ${disk_device}" | awk '{ printf $5 }') # can't rely on fdisk human readable units, using bytes instead
readonly disk_size=$((${disk_size_bytes}/1024/1024))
readonly disk_size_bytes=$(LC_ALL=C df --output=size / | tail -n1)
readonly disk_size=$((${disk_size_bytes}/1024))
readonly system_size=10240 # 10 gigs for system libs, apps images, installer, box code, data and tmp
readonly ext4_reserved=$((disk_size * 5 / 100)) # this can be changes using tune2fs -m percent /dev/vda1
echo "Disk device: ${disk_device}"
echo "Physical memory: ${physical_memory}"
echo "Estimated app count: ${app_count}"
echo "Disk size: ${disk_size}M"
# Allocate swap for general app usage
if [[ ! -f "${APPS_SWAP_FILE}" && ${swap_size} -gt 0 ]]; then
echo "Creating Apps swap file of size ${swap_size}M"
fallocate -l "${swap_size}m" "${APPS_SWAP_FILE}"
readonly current_swap=$(swapon --show="name,size" --noheadings --bytes | awk 'BEGIN{s=0}{s+=$2}END{printf "%.0f", s/1024/1024}')
readonly needed_swap_size=$((swap_size - current_swap))
if [[ ${needed_swap_size} -gt 0 ]]; then
echo "Need more swap of ${needed_swap_size}M"
# compute size of apps.swap ignoring what is already set
without_apps_swap=$(swapon --show="name,size" --noheadings --bytes | awk 'BEGIN{s=0}{if ($1!="/apps.swap") s+=$2}END{printf "%.0f", s/1024/1024}')
apps_swap_size=$((swap_size - without_apps_swap))
echo "Creating Apps swap file of size ${apps_swap_size}M"
if [[ -f "${APPS_SWAP_FILE}" ]]; then
echo "Swapping off before resizing swap"
swapoff "${APPS_SWAP_FILE}" || true
fi
fallocate -l "${apps_swap_size}m" "${APPS_SWAP_FILE}"
chmod 600 "${APPS_SWAP_FILE}"
mkswap "${APPS_SWAP_FILE}"
swapon "${APPS_SWAP_FILE}"
echo "${APPS_SWAP_FILE} none swap sw 0 0" >> /etc/fstab
if ! grep -q "${APPS_SWAP_FILE}" /etc/fstab; then
echo "Adding swap to fstab"
echo "${APPS_SWAP_FILE} none swap sw 0 0" >> /etc/fstab
fi
else
echo "Apps Swap file already exists"
echo "Swap requirements already met"
fi
# see start.sh for the initial default size of 8gb. On small disks the calculation might be lower than 8gb resulting in a failure to resize here.
echo "Resizing data volume"
home_data_size=$((disk_size - system_size - swap_size - ext4_reserved))
echo "Resizing up btrfs user data to size ${home_data_size}M"
umount "${USER_DATA_DIR}" || true
# Do not preallocate (non-sparse). Doing so overallocates for data too much in advance and causes problems when using many apps with smaller data
# fallocate -l "${home_data_size}m" "${USER_DATA_FILE}" # does not overwrite existing data
truncate -s "${home_data_size}m" "${USER_DATA_FILE}" # this will shrink it if the file had existed. this is useful when running this script on a live system
mount -t btrfs -o loop,nosuid "${USER_DATA_FILE}" ${USER_DATA_DIR}
btrfs filesystem resize max "${USER_DATA_DIR}"
-2
View File
@@ -194,7 +194,6 @@ LoadPlugin write_graphite
<Plugin df>
FSType "ext4"
FSType "btrfs"
ReportByDevice true
IgnoreSelected false
@@ -260,4 +259,3 @@ LoadPlugin write_graphite
<Include "/etc/collectd/collectd.conf.d">
Filter "*.conf"
</Include>
+16
View File
@@ -8,3 +8,19 @@ max_connections=50
# on ec2, without this we get a sporadic connection drop when doing the initial migration
max_allowed_packet=32M
# https://mathiasbynens.be/notes/mysql-utf8mb4
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
[mysqldump]
quick
quote-names
max_allowed_packet = 16M
default-character-set = utf8mb4
[mysql]
default-character-set = utf8mb4
[client]
default-character-set = utf8mb4
+31 -7
View File
@@ -6,10 +6,10 @@ map $http_upgrade $connection_upgrade {
server {
<% if (vhost) { %>
listen 443;
listen 443 http2;
server_name <%= vhost %>;
<% } else { %>
listen 443 default_server;
listen 443 http2 default_server;
<% } %>
ssl on;
@@ -25,11 +25,28 @@ server {
# https://raymii.org/s/tutorials/Strong_SSL_Security_On_nginx.html
ssl_prefer_server_ciphers on;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # don't use SSLv3 ref: POODLE
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
add_header Strict-Transport-Security "max-age=15768000; includeSubDomains";
# ciphers according to https://weakdh.org/sysadmin.html
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
ssl_dhparam /home/yellowtent/boxdata/dhparams.pem;
add_header Strict-Transport-Security "max-age=15768000";
# https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
add_header X-Frame-Options "<%= xFrameOptions %>";
proxy_hide_header X-Frame-Options;
# https://github.com/twitter/secureheaders
# https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#tab=Compatibility_Matrix
# https://wiki.mozilla.org/Security/Guidelines/Web_Security
add_header X-XSS-Protection "1; mode=block";
proxy_hide_header X-XSS-Protection;
add_header X-Download-Options "noopen";
proxy_hide_header X-Download-Options;
add_header X-Content-Type-Options "nosniff";
proxy_hide_header X-Content-Type-Options;
add_header X-Permitted-Cross-Domain-Policies "none";
proxy_hide_header X-Permitted-Cross-Domain-Policies;
add_header Referrer-Policy "no-referrer-when-downgrade";
proxy_hide_header Referrer-Policy;
proxy_http_version 1.1;
proxy_intercept_errors on;
@@ -59,6 +76,9 @@ server {
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
# No buffering to temp files, it fails for large downloads
proxy_max_temp_file_size 0;
# Disable check to allow unlimited body sizes
client_max_body_size 0;
@@ -68,13 +88,19 @@ server {
client_max_body_size 1m;
}
location ~ ^/api/v1/(developer|session)/login$ {
proxy_pass http://127.0.0.1:3000;
client_max_body_size 1m;
limit_req zone=admin_login burst=5;
}
# the read timeout is between successive reads and not the whole connection
location ~ ^/api/v1/apps/.*/exec$ {
proxy_pass http://127.0.0.1:3000;
proxy_read_timeout 30m;
}
# graphite paths
# graphite paths (uncomment block below and visit /graphite/index.html)
# location ~ ^/(graphite|content|metrics|dashboard|render|browser|composer)/ {
# proxy_pass http://127.0.0.1:8000;
# client_max_body_size 1m;
@@ -84,7 +110,6 @@ server {
root <%= sourceDir %>/webadmin/dist;
index index.html index.htm;
}
<% } else if ( endpoint === 'app' ) { %>
proxy_pass http://127.0.0.1:<%= port %>;
<% } else if ( endpoint === 'splash' ) { %>
@@ -124,4 +149,3 @@ server {
<% } %>
}
}
+4 -2
View File
@@ -33,6 +33,9 @@ http {
# keep-alive connections timeout in 65s. this is because many browsers timeout in 60 seconds
keepalive_timeout 65s;
# zones for rate limiting
limit_req_zone $binary_remote_addr zone=admin_login:10m rate=10r/s; # 10 request a second
# HTTP server
server {
listen 80;
@@ -48,7 +51,7 @@ http {
# acme challenges
location /.well-known/acme-challenge/ {
default_type text/plain;
alias /home/yellowtent/data/acme/;
alias /home/yellowtent/platformdata/acme/;
}
location / {
@@ -59,4 +62,3 @@ http {
include applications/*.conf;
}
+6 -12
View File
@@ -10,15 +10,6 @@ yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/rmappdir.sh
Defaults!/home/yellowtent/box/src/scripts/reloadnginx.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/reloadnginx.sh
Defaults!/home/yellowtent/box/src/scripts/backupbox.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/backupbox.sh
Defaults!/home/yellowtent/box/src/scripts/backupapp.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/backupapp.sh
Defaults!/home/yellowtent/box/src/scripts/restoreapp.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/restoreapp.sh
Defaults!/home/yellowtent/box/src/scripts/reboot.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/reboot.sh
@@ -31,8 +22,11 @@ yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/collectlogs.sh
Defaults!/home/yellowtent/box/src/scripts/retire.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/retire.sh
Defaults!/home/yellowtent/box/src/scripts/rmbackup.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/rmbackup.sh
Defaults!/home/yellowtent/box/src/scripts/update.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/update.sh
Defaults!/home/yellowtent/box/src/scripts/authorized_keys.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/authorized_keys.sh
Defaults!/home/yellowtent/box/src/scripts/node.sh env_keep="HOME BOX_ENV NODE_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/node.sh
@@ -0,0 +1,12 @@
[Unit]
Description=Cloudron Firewall
After=docker.service
PartOf=docker.service
[Service]
Type=oneshot
ExecStart="/home/yellowtent/box/setup/start/cloudron-firewall.sh"
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
@@ -1,11 +0,0 @@
[Unit]
Description=IPTables Restore
Before=docker.service
[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore /etc/iptables/rules.v4
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
+75 -107
View File
@@ -20,6 +20,7 @@ var appdb = require('./appdb.js'),
async = require('async'),
clients = require('./clients.js'),
config = require('./config.js'),
constants = require('./constants.js'),
ClientsError = clients.ClientsError,
debug = require('debug')('box:addons'),
docker = require('./docker.js'),
@@ -106,18 +107,6 @@ var KNOWN_ADDONS = {
teardown: NOOP,
backup: NOOP,
restore: NOOP
},
simpleauth: {
setup: setupSimpleAuth,
teardown: teardownSimpleAuth,
backup: NOOP,
restore: setupSimpleAuth
},
_docker: {
setup: NOOP,
teardown: NOOP,
backup: NOOP,
restore: NOOP
}
};
@@ -206,7 +195,11 @@ function getEnvironment(app, callback) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof callback, 'function');
appdb.getAddonConfigByAppId(app.id, callback);
appdb.getAddonConfigByAppId(app.id, function (error, result) {
if (error) return callback(error);
return callback(null, result.map(function (e) { return e.name + '=' + e.value; }));
});
}
function getBindsSync(app, addons) {
@@ -219,8 +212,7 @@ function getBindsSync(app, addons) {
for (var addon in addons) {
switch (addon) {
case '_docker': binds.push('/var/run/docker.sock:/var/run/docker.sock:rw'); break;
case 'localstorage': binds.push(path.join(paths.DATA_DIR, app.id, 'data') + ':/app/data:rw'); break;
case 'localstorage': binds.push(path.join(paths.APPS_DATA_DIR, app.id, 'data') + ':/app/data:rw'); break;
default: break;
}
}
@@ -267,9 +259,9 @@ function setupOauth(app, options, callback) {
if (error) return callback(error);
var env = [
'OAUTH_CLIENT_ID=' + result.id,
'OAUTH_CLIENT_SECRET=' + result.clientSecret,
'OAUTH_ORIGIN=' + config.adminOrigin()
{ name: 'OAUTH_CLIENT_ID', value: result.id },
{ name: 'OAUTH_CLIENT_SECRET', value: result.clientSecret },
{ name: 'OAUTH_ORIGIN', value: config.adminOrigin() }
];
debugApp(app, 'Setting oauth addon config to %j', env);
@@ -287,57 +279,12 @@ function teardownOauth(app, options, callback) {
debugApp(app, 'teardownOauth');
clients.delByAppIdAndType(app.id, clients.TYPE_OAUTH, function (error) {
if (error && error.reason !== ClientsError.NOT_FOUND) console.error(error);
if (error && error.reason !== ClientsError.NOT_FOUND) debug(error);
appdb.unsetAddonConfig(app.id, 'oauth', callback);
});
}
function setupSimpleAuth(app, options, callback) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof options, 'object');
assert.strictEqual(typeof callback, 'function');
if (!app.sso) return callback(null);
var appId = app.id;
var scope = 'profile';
clients.delByAppIdAndType(app.id, clients.TYPE_SIMPLE_AUTH, function (error) { // remove existing creds
if (error && error.reason !== ClientsError.NOT_FOUND) return callback(error);
clients.add(appId, clients.TYPE_SIMPLE_AUTH, '', scope, function (error, result) {
if (error) return callback(error);
var env = [
'SIMPLE_AUTH_SERVER=172.18.0.1',
'SIMPLE_AUTH_PORT=' + config.get('simpleAuthPort'),
'SIMPLE_AUTH_URL=http://172.18.0.1:' + config.get('simpleAuthPort'), // obsolete, remove
'SIMPLE_AUTH_ORIGIN=http://172.18.0.1:' + config.get('simpleAuthPort'),
'SIMPLE_AUTH_CLIENT_ID=' + result.id
];
debugApp(app, 'Setting simple auth addon config to %j', env);
appdb.setAddonConfig(appId, 'simpleauth', env, callback);
});
});
}
function teardownSimpleAuth(app, options, callback) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof options, 'object');
assert.strictEqual(typeof callback, 'function');
debugApp(app, 'teardownSimpleAuth');
clients.delByAppIdAndType(app.id, clients.TYPE_SIMPLE_AUTH, function (error) {
if (error && error.reason !== ClientsError.NOT_FOUND) console.error(error);
appdb.unsetAddonConfig(app.id, 'simpleauth', callback);
});
}
function setupEmail(app, options, callback) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof options, 'object');
@@ -345,13 +292,13 @@ function setupEmail(app, options, callback) {
// note that "external" access info can be derived from MAIL_DOMAIN (since it's part of user documentation)
var env = [
'MAIL_SMTP_SERVER=mail',
'MAIL_SMTP_PORT=2525',
'MAIL_IMAP_SERVER=mail',
'MAIL_IMAP_PORT=9993',
'MAIL_SIEVE_SERVER=mail',
'MAIL_SIEVE_PORT=4190',
'MAIL_DOMAIN=' + config.fqdn()
{ name: 'MAIL_SMTP_SERVER', value: 'mail' },
{ name: 'MAIL_SMTP_PORT', value: '2525' },
{ name: 'MAIL_IMAP_SERVER', value: 'mail' },
{ name: 'MAIL_IMAP_PORT', value: '9993' },
{ name: 'MAIL_SIEVE_SERVER', value: 'mail' },
{ name: 'MAIL_SIEVE_PORT', value: '4190' },
{ name: 'MAIL_DOMAIN', value: config.fqdn() }
];
debugApp(app, 'Setting up Email');
@@ -377,13 +324,13 @@ function setupLdap(app, options, callback) {
if (!app.sso) return callback(null);
var env = [
'LDAP_SERVER=172.18.0.1',
'LDAP_PORT=' + config.get('ldapPort'),
'LDAP_URL=ldap://172.18.0.1:' + config.get('ldapPort'),
'LDAP_USERS_BASE_DN=ou=users,dc=cloudron',
'LDAP_GROUPS_BASE_DN=ou=groups,dc=cloudron',
'LDAP_BIND_DN=cn='+ app.id + ',ou=apps,dc=cloudron',
'LDAP_BIND_PASSWORD=' + hat(4 * 128) // this is ignored
{ name: 'LDAP_SERVER', value: '172.18.0.1' },
{ name: 'LDAP_PORT', value: '' + config.get('ldapPort') },
{ name: 'LDAP_URL', value: 'ldap://172.18.0.1:' + config.get('ldapPort') },
{ name: 'LDAP_USERS_BASE_DN', value: 'ou=users,dc=cloudron' },
{ name: 'LDAP_GROUPS_BASE_DN', value: 'ou=groups,dc=cloudron' },
{ name: 'LDAP_BIND_DN', value: 'cn='+ app.id + ',ou=apps,dc=cloudron' },
{ name: 'LDAP_BIND_PASSWORD', value: hat(4 * 128) } // this is ignored
];
debugApp(app, 'Setting up LDAP');
@@ -412,14 +359,15 @@ function setupSendMail(app, options, callback) {
if (error) return callback(error);
var mailbox = results.filter(function (r) { return !r.aliasTarget; })[0];
var password = generatePassword(128, false /* memorable */, /[\w\d_]/);
var env = [
"MAIL_SMTP_SERVER=mail",
"MAIL_SMTP_PORT=2525",
"MAIL_SMTP_USERNAME=" + mailbox.name,
"MAIL_SMTP_PASSWORD=" + app.id,
"MAIL_FROM=" + mailbox.name + '@' + config.fqdn(),
"MAIL_DOMAIN=" + config.fqdn()
{ name: 'MAIL_SMTP_SERVER', value: 'mail' },
{ name: 'MAIL_SMTP_PORT', value: '2525' },
{ name: 'MAIL_SMTP_USERNAME', value: mailbox.name },
{ name: 'MAIL_SMTP_PASSWORD', value: password },
{ name: 'MAIL_FROM', value: mailbox.name + '@' + config.fqdn() },
{ name: 'MAIL_DOMAIN', value: config.fqdn() }
];
debugApp(app, 'Setting sendmail addon config to %j', env);
appdb.setAddonConfig(app.id, 'sendmail', env, callback);
@@ -447,14 +395,15 @@ function setupRecvMail(app, options, callback) {
if (error) return callback(error);
var mailbox = results.filter(function (r) { return !r.aliasTarget; })[0];
var password = generatePassword(128, false /* memorable */, /[\w\d_]/);
var env = [
"MAIL_IMAP_SERVER=mail",
"MAIL_IMAP_PORT=9993",
"MAIL_IMAP_USERNAME=" + mailbox.name,
"MAIL_IMAP_PASSWORD=" + app.id,
"MAIL_TO=" + mailbox.name + '@' + config.fqdn(),
"MAIL_DOMAIN=" + config.fqdn()
{ name: 'MAIL_IMAP_SERVER', value: 'mail' },
{ name: 'MAIL_IMAP_PORT', value: '9993' },
{ name: 'MAIL_IMAP_USERNAME', value: mailbox.name },
{ name: 'MAIL_IMAP_PASSWORD', value: password },
{ name: 'MAIL_TO', value: mailbox.name + '@' + config.fqdn() },
{ name: 'MAIL_DOMAIN', value: config.fqdn() }
];
debugApp(app, 'Setting sendmail addon config to %j', env);
@@ -484,7 +433,9 @@ function setupMySql(app, options, callback) {
docker.execContainer('mysql', cmd, { bufferStdout: true }, function (error, stdout) {
if (error) return callback(error);
var env = stdout.toString('utf8').split('\n').slice(0, -1); // remove trailing newline
var result = stdout.toString('utf8').split('\n').slice(0, -1); // remove trailing newline
var env = result.map(function (r) { var idx = r.indexOf('='); return { name: r.substr(0, idx), value: r.substr(idx + 1) }; });
debugApp(app, 'Setting mysql addon config to %j', env);
appdb.setAddonConfig(app.id, 'mysql', env, callback);
});
@@ -511,7 +462,7 @@ function backupMySql(app, options, callback) {
callback = once(callback); // ChildProcess exit may or may not be called after error
var output = fs.createWriteStream(path.join(paths.DATA_DIR, app.id, 'mysqldump'));
var output = fs.createWriteStream(path.join(paths.APPS_DATA_DIR, app.id, 'mysqldump'));
output.on('error', callback);
var cmd = [ '/addons/mysql/service.sh', options.multipleDatabases ? 'backup-prefix' : 'backup', app.id ];
@@ -527,7 +478,7 @@ function restoreMySql(app, options, callback) {
debugApp(app, 'restoreMySql');
var input = fs.createReadStream(path.join(paths.DATA_DIR, app.id, 'mysqldump'));
var input = fs.createReadStream(path.join(paths.APPS_DATA_DIR, app.id, 'mysqldump'));
input.on('error', callback);
var cmd = [ '/addons/mysql/service.sh', options.multipleDatabases ? 'restore-prefix' : 'restore', app.id ];
@@ -547,7 +498,9 @@ function setupPostgreSql(app, options, callback) {
docker.execContainer('postgresql', cmd, { bufferStdout: true }, function (error, stdout) {
if (error) return callback(error);
var env = stdout.toString('utf8').split('\n').slice(0, -1); // remove trailing newline
var result = stdout.toString('utf8').split('\n').slice(0, -1); // remove trailing newline
var env = result.map(function (r) { var idx = r.indexOf('='); return { name: r.substr(0, idx), value: r.substr(idx + 1) }; });
debugApp(app, 'Setting postgresql addon config to %j', env);
appdb.setAddonConfig(app.id, 'postgresql', env, callback);
});
@@ -574,7 +527,7 @@ function backupPostgreSql(app, options, callback) {
callback = once(callback); // ChildProcess exit may or may not be called after error
var output = fs.createWriteStream(path.join(paths.DATA_DIR, app.id, 'postgresqldump'));
var output = fs.createWriteStream(path.join(paths.APPS_DATA_DIR, app.id, 'postgresqldump'));
output.on('error', callback);
var cmd = [ '/addons/postgresql/service.sh', 'backup', app.id ];
@@ -590,7 +543,7 @@ function restorePostgreSql(app, options, callback) {
debugApp(app, 'restorePostgreSql');
var input = fs.createReadStream(path.join(paths.DATA_DIR, app.id, 'postgresqldump'));
var input = fs.createReadStream(path.join(paths.APPS_DATA_DIR, app.id, 'postgresqldump'));
input.on('error', callback);
var cmd = [ '/addons/postgresql/service.sh', 'restore', app.id ];
@@ -611,7 +564,9 @@ function setupMongoDb(app, options, callback) {
docker.execContainer('mongodb', cmd, { bufferStdout: true }, function (error, stdout) {
if (error) return callback(error);
var env = stdout.toString('utf8').split('\n').slice(0, -1); // remove trailing newline
var result = stdout.toString('utf8').split('\n').slice(0, -1); // remove trailing newline
var env = result.map(function (r) { var idx = r.indexOf('='); return { name: r.substr(0, idx), value: r.substr(idx + 1) }; });
debugApp(app, 'Setting mongodb addon config to %j', env);
appdb.setAddonConfig(app.id, 'mongodb', env, callback);
});
@@ -638,7 +593,7 @@ function backupMongoDb(app, options, callback) {
callback = once(callback); // ChildProcess exit may or may not be called after error
var output = fs.createWriteStream(path.join(paths.DATA_DIR, app.id, 'mongodbdump'));
var output = fs.createWriteStream(path.join(paths.APPS_DATA_DIR, app.id, 'mongodbdump'));
output.on('error', callback);
var cmd = [ '/addons/mongodb/service.sh', 'backup', app.id ];
@@ -654,7 +609,7 @@ function restoreMongoDb(app, options, callback) {
debugApp(app, 'restoreMongoDb');
var input = fs.createReadStream(path.join(paths.DATA_DIR, app.id, 'mongodbdump'));
var input = fs.createReadStream(path.join(paths.APPS_DATA_DIR, app.id, 'mongodbdump'));
input.on('error', callback);
var cmd = [ '/addons/mongodb/service.sh', 'restore', app.id ];
@@ -668,9 +623,9 @@ function setupRedis(app, options, callback) {
assert.strictEqual(typeof options, 'object');
assert.strictEqual(typeof callback, 'function');
var redisPassword = generatePassword(64, false /* memorable */, /[\w\d_]/); // ensure no / in password for being sed friendly (and be uri friendly)
var redisPassword = generatePassword(128, false /* memorable */, /[\w\d_]/); // ensure no / in password for being sed friendly (and be uri friendly)
var redisVarsFile = path.join(paths.ADDON_CONFIG_DIR, 'redis-' + app.id + '_vars.sh');
var redisDataDir = path.join(paths.DATA_DIR, app.id + '/redis');
var redisDataDir = path.join(paths.APPS_DATA_DIR, app.id + '/redis');
if (!safe.fs.writeFileSync(redisVarsFile, 'REDIS_PASSWORD=' + redisPassword)) {
return callback(new Error('Error writing redis config'));
@@ -678,21 +633,34 @@ function setupRedis(app, options, callback) {
if (!safe.fs.mkdirSync(redisDataDir) && safe.error.code !== 'EEXIST') return callback(new Error('Error creating redis data dir:' + safe.error));
// Compute redis memory limit based on app's memory limit (this is arbitrary)
var memoryLimit = app.memoryLimit || app.manifest.memoryLimit || 0;
if (memoryLimit === -1) { // unrestricted (debug mode)
memoryLimit = 0;
} else if (memoryLimit === 0 || memoryLimit <= (2 * 1024 * 1024 * 1024)) { // less than 2G (ram+swap)
memoryLimit = 150 * 1024 * 1024; // 150m
} else {
memoryLimit = 600 * 1024 * 1024; // 600m
}
const tag = infra.images.redis.tag, redisName = 'redis-' + app.id;
const cmd = `docker run --restart=always -d --name=${redisName} \
--net cloudron \
--net-alias ${redisName} \
-m 100m \
--memory-swap 150m \
-m ${memoryLimit/2} \
--memory-swap ${memoryLimit} \
--dns 172.18.0.1 \
--dns-search=. \
-v ${redisVarsFile}:/etc/redis/redis_vars.sh:ro \
-v ${redisDataDir}:/var/lib/redis:rw \
--read-only -v /tmp -v /run ${tag}`;
var env = [
'REDIS_URL=redis://redisuser:' + redisPassword + '@redis-' + app.id,
'REDIS_PASSWORD=' + redisPassword,
'REDIS_HOST=' + redisName,
'REDIS_PORT=6379'
{ name: 'REDIS_URL', value: 'redis://redisuser:' + redisPassword + '@redis-' + app.id },
{ name: 'REDIS_PASSWORD', value: redisPassword },
{ name: 'REDIS_HOST', value: redisName },
{ name: 'REDIS_PORT', value: '6379' }
];
async.series([
-49
View File
@@ -1,49 +0,0 @@
'use strict';
var crypto = require('crypto');
// This code is taken from https://github.com/fabdrol/node-aes-helper
module.exports = {
algorithm: 'AES-256-CBC',
key: function (password, salt) {
var key = salt.toString('utf8') + password;
var hash = crypto.createHash('sha1');
hash.update(key, 'utf8');
return hash.digest('hex');
},
encrypt: function (plain, password, salt) {
var key = this.key(password, salt);
var cipher = crypto.createCipher(this.algorithm, key);
var crypted;
try {
crypted = cipher.update(plain, 'utf8', 'hex');
crypted += cipher.final('hex');
} catch (e) {
console.error('Encryption error:', e);
crypted = '';
}
return crypted;
},
decrypt: function (crypted, password, salt) {
var key = this.key(password, salt);
var decipher = crypto.createDecipher(this.algorithm, key);
var decoded;
try {
decoded = decipher.update(crypted, 'hex', 'utf8');
decoded += decipher.final('utf8');
} catch (e) {
console.error('Decryption error:', e);
decoded = '';
}
return decoded;
}
};
+33 -15
View File
@@ -14,6 +14,7 @@ exports = module.exports = {
setAddonConfig: setAddonConfig,
getAddonConfig: getAddonConfig,
getAddonConfigByAppId: getAddonConfigByAppId,
getAddonConfigByName: getAddonConfigByName,
unsetAddonConfig: unsetAddonConfig,
unsetAddonConfigByAppId: unsetAddonConfigByAppId,
@@ -52,6 +53,7 @@ var assert = require('assert'),
async = require('async'),
database = require('./database.js'),
DatabaseError = require('./databaseerror'),
mailboxdb = require('./mailboxdb.js'),
safe = require('safetydance'),
util = require('util');
@@ -189,7 +191,7 @@ function add(id, appStoreId, manifest, location, portBindings, data, callback) {
var sso = 'sso' in data ? data.sso : null;
var debugModeJson = data.debugMode ? JSON.stringify(data.debugMode) : null;
var queries = [ ];
var queries = [];
queries.push({
query: 'INSERT INTO apps (id, appStoreId, manifestJson, installationState, location, accessRestrictionJson, memoryLimit, altDomain, xFrameOptions, lastBackupId, sso, debugModeJson) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
args: [ id, appStoreId, manifestJson, installationState, location, accessRestrictionJson, memoryLimit, altDomain, xFrameOptions, lastBackupId, sso, debugModeJson ]
@@ -202,6 +204,14 @@ function add(id, appStoreId, manifest, location, portBindings, data, callback) {
});
});
// only allocate a mailbox if mailboxName is set
if (data.mailboxName) {
queries.push({
query: 'INSERT INTO mailboxes (name, ownerId, ownerType) VALUES (?, ?, ?)',
args: [ data.mailboxName, id, mailboxdb.TYPE_APP ]
});
}
database.transaction(queries, function (error) {
if (error && error.code === 'ER_DUP_ENTRY') return callback(new DatabaseError(DatabaseError.ALREADY_EXISTS, error.message));
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
@@ -242,13 +252,14 @@ function del(id, callback) {
assert.strictEqual(typeof callback, 'function');
var queries = [
{ query: 'DELETE FROM mailboxes WHERE ownerId=?', args: [ id ] },
{ query: 'DELETE FROM appPortBindings WHERE appId = ?', args: [ id ] },
{ query: 'DELETE FROM apps WHERE id = ?', args: [ id ] }
];
database.transaction(queries, function (error, results) {
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
if (results[1].affectedRows !== 1) return callback(new DatabaseError(DatabaseError.NOT_FOUND));
if (results[2].affectedRows !== 1) return callback(new DatabaseError(DatabaseError.NOT_FOUND));
callback(null);
});
@@ -403,11 +414,11 @@ function setAddonConfig(appId, addonId, env, callback) {
if (env.length === 0) return callback(null);
var query = 'INSERT INTO appAddonConfigs(appId, addonId, value) VALUES ';
var query = 'INSERT INTO appAddonConfigs(appId, addonId, name, value) VALUES ';
var args = [ ], queryArgs = [ ];
for (var i = 0; i < env.length; i++) {
args.push(appId, addonId, env[i]);
queryArgs.push('(?, ?, ?)');
args.push(appId, addonId, env[i].name, env[i].value);
queryArgs.push('(?, ?, ?, ?)');
}
database.query(query + queryArgs.join(','), args, function (error) {
@@ -446,13 +457,10 @@ function getAddonConfig(appId, addonId, callback) {
assert.strictEqual(typeof addonId, 'string');
assert.strictEqual(typeof callback, 'function');
database.query('SELECT value FROM appAddonConfigs WHERE appId = ? AND addonId = ?', [ appId, addonId ], function (error, results) {
database.query('SELECT name, value FROM appAddonConfigs WHERE appId = ? AND addonId = ?', [ appId, addonId ], function (error, results) {
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
var config = [ ];
results.forEach(function (v) { config.push(v.value); });
callback(null, config);
callback(null, results);
});
}
@@ -460,13 +468,23 @@ function getAddonConfigByAppId(appId, callback) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof callback, 'function');
database.query('SELECT value FROM appAddonConfigs WHERE appId = ?', [ appId ], function (error, results) {
database.query('SELECT name, value FROM appAddonConfigs WHERE appId = ?', [ appId ], function (error, results) {
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
var config = [ ];
results.forEach(function (v) { config.push(v.value); });
callback(null, config);
callback(null, results);
});
}
function getAddonConfigByName(appId, addonId, name, callback) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof addonId, 'string');
assert.strictEqual(typeof name, 'string');
assert.strictEqual(typeof callback, 'function');
database.query('SELECT value FROM appAddonConfigs WHERE appId = ? AND addonId = ? AND name = ?', [ appId, addonId, name ], function (error, results) {
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
if (results.length === 0) return callback(new DatabaseError(DatabaseError.NOT_FOUND));
callback(null, results[0].value);
});
}
+2 -2
View File
@@ -50,7 +50,7 @@ function setHealth(app, health, callback) {
debugApp(app, 'marking as unhealthy since not seen for more than %s minutes', UNHEALTHY_THRESHOLD/(60 * 1000));
if (app.debugMode) mailer.appDied(app); // do not send mails for dev apps
if (!app.debugMode) mailer.appDied(app); // do not send mails for dev apps
gHealthInfo[app.id].emailSent = true;
} else {
debugApp(app, 'waiting for sometime to update the app health');
@@ -138,7 +138,7 @@ function run() {
/*
OOM can be tested using stress tool like so:
docker run -ti -m 100M cloudron/base:0.9.0 /bin/bash
docker run -ti -m 100M cloudron/base:0.10.0 /bin/bash
apt-get update && apt-get install stress
stress --vm 1 --vm-bytes 200M --vm-hang 0
*/
+70 -156
View File
@@ -45,6 +45,8 @@ exports = module.exports = {
var addons = require('./addons.js'),
appdb = require('./appdb.js'),
appstore = require('./appstore.js'),
AppstoreError = require('./appstore.js').AppstoreError,
assert = require('assert'),
async = require('async'),
backups = require('./backups.js'),
@@ -64,7 +66,6 @@ var addons = require('./addons.js'),
paths = require('./paths.js'),
safe = require('safetydance'),
semver = require('semver'),
settings = require('./settings.js'),
spawn = require('child_process').spawn,
split = require('split'),
superagent = require('superagent'),
@@ -152,7 +153,6 @@ function validatePortBindings(portBindings, tcpPorts) {
config.get('sysadminPort'), /* sysadmin app server (lo) */
config.get('smtpPort'), /* internal smtp port (lo) */
config.get('ldapPort'), /* ldap server (lo) */
config.get('simpleAuthPort'), /* simple auth server (lo) */
3306, /* mysql (lo) */
4190, /* managesieve */
8000 /* graphite (lo) */
@@ -250,7 +250,7 @@ function getDuplicateErrorDetails(location, portBindings, error) {
var match = error.message.match(/ER_DUP_ENTRY: Duplicate entry '(.*)' for key/);
if (!match) {
console.error('Unexpected SQL error message.', error);
debug('Unexpected SQL error message.', error);
return new AppsError(AppsError.INTERNAL_ERROR);
}
@@ -296,11 +296,9 @@ function hasAccessTo(app, user, callback) {
if (!app.accessRestriction.groups) return callback(null, false);
async.some(app.accessRestriction.groups, function (groupId, iteratorDone) {
groups.isMember(groupId, user.id, function (error, member) {
iteratorDone(!error && member); // async.some does not take error argument in callback
});
}, function (result) {
callback(null, result);
groups.isMember(groupId, user.id, iteratorDone);
}, function (error, result) {
callback(null, !error && result);
});
}
@@ -314,6 +312,7 @@ function get(appId, callback) {
app.iconUrl = getIconUrlSync(app);
app.fqdn = app.altDomain || config.appFqdn(app.location);
app.cnameTarget = app.altDomain ? config.appFqdn(app.location) : null;
callback(null, app);
});
@@ -332,6 +331,7 @@ function getByIpAddress(ip, callback) {
app.iconUrl = getIconUrlSync(app);
app.fqdn = app.altDomain || config.appFqdn(app.location);
app.cnameTarget = app.altDomain ? config.appFqdn(app.location) : null;
callback(null, app);
});
@@ -347,6 +347,7 @@ function getAll(callback) {
apps.forEach(function (app) {
app.iconUrl = getIconUrlSync(app);
app.fqdn = app.altDomain || config.appFqdn(app.location);
app.cnameTarget = app.altDomain ? config.appFqdn(app.location) : null;
});
callback(null, apps);
@@ -360,104 +361,12 @@ function getAllByUser(user, callback) {
getAll(function (error, result) {
if (error) return callback(error);
async.filter(result, function (app, callback) {
hasAccessTo(app, user, function (error, hasAccess) {
callback(hasAccess);
});
}, callback.bind(null, null)); // never error
async.filter(result, function (app, iteratorDone) {
hasAccessTo(app, user, iteratorDone);
}, callback);
});
}
function purchase(appId, appstoreId, callback) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof appstoreId, 'string');
assert.strictEqual(typeof callback, 'function');
if (appstoreId === '') return callback(null);
function purchaseWithAppstoreConfig(appstoreConfig) {
assert.strictEqual(typeof appstoreConfig.userId, 'string');
assert.strictEqual(typeof appstoreConfig.cloudronId, 'string');
assert.strictEqual(typeof appstoreConfig.token, 'string');
var url = config.apiServerOrigin() + '/api/v1/users/' + appstoreConfig.userId + '/cloudrons/' + appstoreConfig.cloudronId + '/apps/' + appId;
var data = { appstoreId: appstoreId };
superagent.post(url).send(data).query({ accessToken: appstoreConfig.token }).timeout(30 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppsError(AppsError.EXTERNAL_ERROR, error));
if (result.statusCode === 404) return callback(new AppsError(AppsError.NOT_FOUND));
if (result.statusCode === 403 || result.statusCode === 401) return callback(new AppsError(AppsError.BILLING_REQUIRED));
if (result.statusCode !== 201 && result.statusCode !== 200) return callback(new AppsError(AppsError.EXTERNAL_ERROR, util.format('App purchase failed. %s %j', result.status, result.body)));
callback(null);
});
}
// Caas Cloudrons do not store appstore credentials in their local database
if (config.provider() === 'caas') {
var url = config.apiServerOrigin() + '/api/v1/exchangeBoxTokenWithUserToken';
superagent.post(url).query({ token: config.token() }).timeout(30 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppsError(AppsError.EXTERNAL_ERROR, error));
if (result.statusCode !== 201) return callback(new AppsError(AppsError.EXTERNAL_ERROR, util.format('App purchase failed. %s %j', result.status, result.body)));
purchaseWithAppstoreConfig(result.body);
});
} else {
settings.getAppstoreConfig(function (error, result) {
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
if (!result.token) return callback(new AppsError(AppsError.BILLING_REQUIRED));
purchaseWithAppstoreConfig(result);
});
}
}
function unpurchase(appId, appstoreId, callback) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof appstoreId, 'string');
assert.strictEqual(typeof callback, 'function');
if (appstoreId === '') return callback(null);
function unpurchaseWithAppstoreConfig(appstoreConfig) {
assert.strictEqual(typeof appstoreConfig.userId, 'string');
assert.strictEqual(typeof appstoreConfig.cloudronId, 'string');
assert.strictEqual(typeof appstoreConfig.token, 'string');
var url = config.apiServerOrigin() + '/api/v1/users/' + appstoreConfig.userId + '/cloudrons/' + appstoreConfig.cloudronId + '/apps/' + appId;
superagent.get(url).query({ accessToken: appstoreConfig.token }).timeout(30 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppsError(AppsError.EXTERNAL_ERROR, error));
if (result.statusCode === 404) return callback(null); // was never purchased
superagent.del(url).query({ accessToken: appstoreConfig.token }).timeout(30 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppsError(AppsError.EXTERNAL_ERROR, error));
if (result.statusCode !== 204) return callback(new AppsError(AppsError.EXTERNAL_ERROR, util.format('App unpurchase failed. %s %j', result.status, result.body)));
callback(null);
});
});
}
// Caas Cloudrons do not store appstore credentials in their local database
if (config.provider() === 'caas') {
var url = config.apiServerOrigin() + '/api/v1/exchangeBoxTokenWithUserToken';
superagent.post(url).query({ token: config.token() }).timeout(30 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppsError(AppsError.EXTERNAL_ERROR, error));
if (result.statusCode !== 201) return callback(new AppsError(AppsError.EXTERNAL_ERROR, util.format('App purchase failed. %s %j', result.status, result.body)));
unpurchaseWithAppstoreConfig(result.body);
});
} else {
settings.getAppstoreConfig(function (error, result) {
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
if (!result.token) return callback(new AppsError(AppsError.BILLING_REQUIRED));
unpurchaseWithAppstoreConfig(result);
});
}
}
function downloadManifest(appStoreId, manifest, callback) {
if (!appStoreId && !manifest) return callback(new AppsError(AppsError.BAD_FIELD, 'Neither manifest nor appStoreId provided'));
@@ -493,7 +402,8 @@ function install(data, auditSource, callback) {
altDomain = data.altDomain || null,
xFrameOptions = data.xFrameOptions || 'SAMEORIGIN',
sso = 'sso' in data ? data.sso : null,
debugMode = data.debugMode || null;
debugMode = data.debugMode || null,
backupId = data.backupId || null;
assert(data.appStoreId || data.manifest); // atleast one of them is required
@@ -526,9 +436,9 @@ function install(data, auditSource, callback) {
if ('sso' in data && !('optionalSso' in manifest)) return callback(new AppsError(AppsError.BAD_FIELD, 'sso can only be specified for apps with optionalSso'));
// if sso was unspecified, enable it by default if possible
if (sso === null) sso = !!manifest.addons['simpleauth'] || !!manifest.addons['ldap'] || !!manifest.addons['oauth'];
if (sso === null) sso = !!manifest.addons['ldap'] || !!manifest.addons['oauth'];
if (altDomain !== null && !validator.isFQDN(altDomain)) return callback(new AppsError(AppsError.BAD_FIELD, 'Invalid alt domain'));
if (altDomain !== null && !validator.isFQDN(altDomain)) return callback(new AppsError(AppsError.BAD_FIELD, 'Invalid external domain'));
var appId = uuid.v4();
@@ -545,8 +455,11 @@ function install(data, auditSource, callback) {
debug('Will install app with id : ' + appId);
purchase(appId, appStoreId, function (error) {
if (error) return callback(error);
appstore.purchase(appId, appStoreId, function (error) {
if (error && error.reason === AppstoreError.NOT_FOUND) return callback(new AppsError(AppsError.NOT_FOUND));
if (error && error.reason === AppstoreError.BILLING_REQUIRED) return callback(new AppsError(AppsError.BILLING_REQUIRED, error.message));
if (error && error.reason === AppstoreError.EXTERNAL_ERROR) return callback(new AppsError(AppsError.EXTERNAL_ERROR, error.message));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
var data = {
accessRestriction: accessRestriction,
@@ -554,30 +467,26 @@ function install(data, auditSource, callback) {
altDomain: altDomain,
xFrameOptions: xFrameOptions,
sso: sso,
debugMode: debugMode
debugMode: debugMode,
mailboxName: (location ? location : manifest.title.toLowerCase().replace(/[^a-zA-Z0-9]/g, '')) + '.app',
lastBackupId: backupId
};
var from = (location ? location : manifest.title.toLowerCase().replace(/[^a-zA-Z0-9]/g, '')) + '.app';
mailboxdb.add(from, appId, mailboxdb.TYPE_APP, function (error) {
if (error && error.reason === DatabaseError.ALREADY_EXISTS) return callback(new AppsError(AppsError.ALREADY_EXISTS, 'Mailbox already exists'));
appdb.add(appId, appStoreId, manifest, location, portBindings, data, function (error) {
if (error && error.reason === DatabaseError.ALREADY_EXISTS) return callback(getDuplicateErrorDetails(location, portBindings, error));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
appdb.add(appId, appStoreId, manifest, location, portBindings, data, function (error) {
if (error && error.reason === DatabaseError.ALREADY_EXISTS) return callback(getDuplicateErrorDetails(location, portBindings, error));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
// save cert to boxdata/certs
if (cert && key) {
if (!safe.fs.writeFileSync(path.join(paths.APP_CERTS_DIR, config.appFqdn(location) + '.user.cert'), cert)) return callback(new AppsError(AppsError.INTERNAL_ERROR, 'Error saving cert: ' + safe.error.message));
if (!safe.fs.writeFileSync(path.join(paths.APP_CERTS_DIR, config.appFqdn(location) + '.user.key'), key)) return callback(new AppsError(AppsError.INTERNAL_ERROR, 'Error saving key: ' + safe.error.message));
}
// save cert to boxdata/certs
if (cert && key) {
if (!safe.fs.writeFileSync(path.join(paths.APP_CERTS_DIR, config.appFqdn(location) + '.user.cert'), cert)) return callback(new AppsError(AppsError.INTERNAL_ERROR, 'Error saving cert: ' + safe.error.message));
if (!safe.fs.writeFileSync(path.join(paths.APP_CERTS_DIR, config.appFqdn(location) + '.user.key'), key)) return callback(new AppsError(AppsError.INTERNAL_ERROR, 'Error saving key: ' + safe.error.message));
}
taskmanager.restartAppTask(appId);
taskmanager.restartAppTask(appId);
eventlog.add(eventlog.ACTION_APP_INSTALL, auditSource, { appId: appId, location: location, manifest: manifest, backupId: backupId });
eventlog.add(eventlog.ACTION_APP_INSTALL, auditSource, { appId: appId, location: location, manifest: manifest });
callback(null, { id : appId });
});
callback(null, { id : appId });
});
});
});
@@ -610,7 +519,7 @@ function configure(appId, data, auditSource, callback) {
if ('altDomain' in data) {
values.altDomain = data.altDomain;
if (values.altDomain !== null && !validator.isFQDN(values.altDomain)) return callback(new AppsError(AppsError.BAD_FIELD, 'Invalid alt domain'));
if (values.altDomain !== null && !validator.isFQDN(values.altDomain)) return callback(new AppsError(AppsError.BAD_FIELD, 'Invalid external domain'));
}
if ('portBindings' in data) {
@@ -765,10 +674,9 @@ function appLogFilter(app) {
return names.map(function (name) { return 'CONTAINER_NAME=' + name; });
}
function getLogs(appId, lines, follow, callback) {
function getLogs(appId, options, callback) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof lines, 'number');
assert.strictEqual(typeof follow, 'boolean');
assert(options && typeof options === 'object');
assert.strictEqual(typeof callback, 'function');
debug('Getting logs for %s', appId);
@@ -777,13 +685,21 @@ function getLogs(appId, lines, follow, callback) {
if (error && error.reason === DatabaseError.NOT_FOUND) return callback(new AppsError(AppsError.NOT_FOUND));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
var args = [ '--output=json', '--no-pager', '--lines=' + lines ];
var lines = options.lines || 100,
follow = !!options.follow,
format = options.format || 'json';
var args = [ '--no-pager', '--lines=' + lines ];
if (follow) args.push('--follow');
if (format == 'short') args.push('--output=short', '-a'); else args.push('--output=json');
args = args.concat(appLogFilter(app));
var cp = spawn('/bin/journalctl', args);
var transformStream = split(function mapper(line) {
if (format !== 'json') return line + '\n';
var obj = safe.JSON.parse(line);
if (!obj) return undefined;
@@ -873,6 +789,7 @@ function clone(appId, data, auditSource, callback) {
backups.getRestoreConfig(backupId, function (error, restoreConfig) {
if (error && error.reason === BackupsError.EXTERNAL_ERROR) return callback(new AppsError(AppsError.EXTERNAL_ERROR, error.message));
if (error && error.reason === BackupsError.NOT_FOUND) return callback(new AppsError(AppsError.EXTERNAL_ERROR, error.message));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
if (!restoreConfig) callback(new AppsError(AppsError.EXTERNAL_ERROR, 'Could not get restore config'));
@@ -889,8 +806,11 @@ function clone(appId, data, auditSource, callback) {
var newAppId = uuid.v4(), appStoreId = app.appStoreId, manifest = restoreConfig.manifest;
purchase(newAppId, appStoreId, function (error) {
if (error) return callback(error);
appstore.purchase(newAppId, appStoreId, function (error) {
if (error && error.reason === AppstoreError.NOT_FOUND) return callback(new AppsError(AppsError.NOT_FOUND));
if (error && error.reason === AppstoreError.BILLING_REQUIRED) return callback(new AppsError(AppsError.BILLING_REQUIRED, error.message));
if (error && error.reason === AppstoreError.EXTERNAL_ERROR) return callback(new AppsError(AppsError.EXTERNAL_ERROR, error.message));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
var data = {
installationState: appdb.ISTATE_PENDING_CLONE,
@@ -898,24 +818,19 @@ function clone(appId, data, auditSource, callback) {
accessRestriction: app.accessRestriction,
xFrameOptions: app.xFrameOptions,
lastBackupId: backupId,
sso: !!app.sso
sso: !!app.sso,
mailboxName: (location ? location : manifest.title.toLowerCase().replace(/[^a-zA-Z0-9]/g, '')) + '.app'
};
var from = (location ? location : manifest.title.toLowerCase().replace(/[^a-zA-Z0-9]/g, '')) + '.app';
mailboxdb.add(from, newAppId, mailboxdb.TYPE_APP, function (error) {
if (error && error.reason === DatabaseError.ALREADY_EXISTS) return callback(new AppsError(AppsError.ALREADY_EXISTS, 'Mailbox already exists'));
appdb.add(newAppId, appStoreId, manifest, location, portBindings, data, function (error) {
if (error && error.reason === DatabaseError.ALREADY_EXISTS) return callback(getDuplicateErrorDetails(location, portBindings, error));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
appdb.add(newAppId, appStoreId, manifest, location, portBindings, data, function (error) {
if (error && error.reason === DatabaseError.ALREADY_EXISTS) return callback(getDuplicateErrorDetails(location, portBindings, error));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
taskmanager.restartAppTask(newAppId);
taskmanager.restartAppTask(newAppId);
eventlog.add(eventlog.ACTION_APP_CLONE, auditSource, { appId: newAppId, oldAppId: appId, backupId: backupId, location: location, manifest: manifest });
eventlog.add(eventlog.ACTION_APP_CLONE, auditSource, { appId: newAppId, oldAppId: appId, backupId: backupId, location: location, manifest: manifest });
callback(null, { id : newAppId });
});
callback(null, { id : newAppId });
});
});
});
@@ -932,21 +847,20 @@ function uninstall(appId, auditSource, callback) {
get(appId, function (error, result) {
if (error) return callback(error);
unpurchase(appId, result.appStoreId, function (error) {
if (error) return callback(error);
appstore.unpurchase(appId, result.appStoreId, function (error) {
if (error && error.reason === AppstoreError.NOT_FOUND) return callback(new AppsError(AppsError.NOT_FOUND));
if (error && error.reason === AppstoreError.BILLING_REQUIRED) return callback(new AppsError(AppsError.BILLING_REQUIRED, error.message));
if (error && error.reason === AppstoreError.EXTERNAL_ERROR) return callback(new AppsError(AppsError.EXTERNAL_ERROR, error.message));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
mailboxdb.delByOwnerId(appId, function (error) {
if (error && error.reason !== DatabaseError.NOT_FOUND) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
taskmanager.stopAppTask(appId, function () {
appdb.setInstallationCommand(appId, appdb.ISTATE_PENDING_UNINSTALL, function (error) {
if (error && error.reason === DatabaseError.NOT_FOUND) return callback(new AppsError(AppsError.NOT_FOUND, 'No such app'));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
taskmanager.stopAppTask(appId, function () {
appdb.setInstallationCommand(appId, appdb.ISTATE_PENDING_UNINSTALL, function (error) {
if (error && error.reason === DatabaseError.NOT_FOUND) return callback(new AppsError(AppsError.NOT_FOUND, 'No such app'));
if (error) return callback(new AppsError(AppsError.INTERNAL_ERROR, error));
eventlog.add(eventlog.ACTION_APP_UNINSTALL, auditSource, { appId: appId });
eventlog.add(eventlog.ACTION_APP_UNINSTALL, auditSource, { appId: appId });
taskmanager.startAppTask(appId, callback);
});
taskmanager.startAppTask(appId, callback);
});
});
});
+211
View File
@@ -0,0 +1,211 @@
'use strict';
exports = module.exports = {
purchase: purchase,
unpurchase: unpurchase,
sendAliveStatus: sendAliveStatus,
getAppUpdate: getAppUpdate,
getBoxUpdate: getBoxUpdate,
AppstoreError: AppstoreError
};
var assert = require('assert'),
config = require('./config.js'),
debug = require('debug')('box:appstore'),
os = require('os'),
settings = require('./settings.js'),
superagent = require('superagent'),
util = require('util');
function AppstoreError(reason, errorOrMessage) {
assert.strictEqual(typeof reason, 'string');
assert(errorOrMessage instanceof Error || typeof errorOrMessage === 'string' || typeof errorOrMessage === 'undefined');
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.reason = reason;
if (typeof errorOrMessage === 'undefined') {
this.message = reason;
} else if (typeof errorOrMessage === 'string') {
this.message = errorOrMessage;
} else {
this.message = 'Internal error';
this.nestedError = errorOrMessage;
}
}
util.inherits(AppstoreError, Error);
AppstoreError.INTERNAL_ERROR = 'Internal Error';
AppstoreError.EXTERNAL_ERROR = 'External Error';
AppstoreError.NOT_FOUND = 'Internal Error';
AppstoreError.BILLING_REQUIRED = 'Billing Required';
var NOOP_CALLBACK = function (error) { if (error) debug(error); };
function getAppstoreConfig(callback) {
assert.strictEqual(typeof callback, 'function');
// Caas Cloudrons do not store appstore credentials in their local database
if (config.provider() === 'caas') {
var url = config.apiServerOrigin() + '/api/v1/exchangeBoxTokenWithUserToken';
superagent.post(url).query({ token: config.token() }).timeout(30 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, error));
if (result.statusCode !== 201) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, util.format('App unpurchase failed. %s %j', result.status, result.body)));
callback(null, result.body);
});
} else {
settings.getAppstoreConfig(function (error, result) {
if (error) return callback(new AppstoreError(AppstoreError.INTERNAL_ERROR, error));
if (!result.token) return callback(new AppstoreError(AppstoreError.BILLING_REQUIRED));
callback(null, result);
});
}
}
function purchase(appId, appstoreId, callback) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof appstoreId, 'string');
assert.strictEqual(typeof callback, 'function');
if (appstoreId === '') return callback(null);
getAppstoreConfig(function (error, appstoreConfig) {
if (error) return callback(error);
var url = config.apiServerOrigin() + '/api/v1/users/' + appstoreConfig.userId + '/cloudrons/' + appstoreConfig.cloudronId + '/apps/' + appId;
var data = { appstoreId: appstoreId };
superagent.post(url).send(data).query({ accessToken: appstoreConfig.token }).timeout(30 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, error));
if (result.statusCode === 404) return callback(new AppstoreError(AppstoreError.NOT_FOUND));
if (result.statusCode === 403 || result.statusCode === 401) return callback(new AppstoreError(AppstoreError.BILLING_REQUIRED));
if (result.statusCode !== 201 && result.statusCode !== 200) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, util.format('App purchase failed. %s %j', result.status, result.body)));
callback(null);
});
});
}
function unpurchase(appId, appstoreId, callback) {
assert.strictEqual(typeof appId, 'string');
assert.strictEqual(typeof appstoreId, 'string');
assert.strictEqual(typeof callback, 'function');
if (appstoreId === '') return callback(null);
getAppstoreConfig(function (error, appstoreConfig) {
if (error) return callback(error);
var url = config.apiServerOrigin() + '/api/v1/users/' + appstoreConfig.userId + '/cloudrons/' + appstoreConfig.cloudronId + '/apps/' + appId;
superagent.get(url).query({ accessToken: appstoreConfig.token }).timeout(30 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, error));
if (result.statusCode === 403 || result.statusCode === 401) return callback(new AppstoreError(AppstoreError.BILLING_REQUIRED));
if (result.statusCode === 404) return callback(null); // was never purchased
if (result.statusCode !== 201 && result.statusCode !== 200) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, util.format('App purchase failed. %s %j', result.status, result.body)));
superagent.del(url).query({ accessToken: appstoreConfig.token }).timeout(30 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, error));
if (result.statusCode === 403 || result.statusCode === 401) return callback(new AppstoreError(AppstoreError.BILLING_REQUIRED));
if (result.statusCode !== 204) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, util.format('App unpurchase failed. %s %j', result.status, result.body)));
callback(null);
});
});
});
}
function sendAliveStatus(data, callback) {
callback = callback || NOOP_CALLBACK;
settings.getAll(function (error, result) {
if (error) return callback(new AppstoreError(AppstoreError.INTERNAL_ERROR, error));
var backendSettings = {
dnsConfig: {
provider: result[settings.DNS_CONFIG_KEY].provider,
wildcard: result[settings.DNS_CONFIG_KEY].provider === 'manual' ? result[settings.DNS_CONFIG_KEY].wildcard : undefined
},
tlsConfig: {
provider: result[settings.TLS_CONFIG_KEY].provider
},
backupConfig: {
provider: result[settings.BACKUP_CONFIG_KEY].provider
},
mailConfig: {
enabled: result[settings.MAIL_CONFIG_KEY].enabled
},
autoupdatePattern: result[settings.AUTOUPDATE_PATTERN_KEY],
timeZone: result[settings.TIME_ZONE_KEY]
};
var data = {
domain: config.fqdn(),
version: config.version(),
provider: config.provider(),
backendSettings: backendSettings,
machine: {
cpus: os.cpus(),
totalmem: os.totalmem()
}
};
getAppstoreConfig(function (error, appstoreConfig) {
if (error) return callback(error);
var url = config.apiServerOrigin() + '/api/v1/users/' + appstoreConfig.userId + '/cloudrons/' + appstoreConfig.cloudronId + '/alive';
superagent.post(url).send(data).query({ accessToken: appstoreConfig.token }).timeout(30 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, error));
if (result.statusCode === 404) return callback(new AppstoreError(AppstoreError.NOT_FOUND));
if (result.statusCode !== 201) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, util.format('Sending alive status failed. %s %j', result.status, result.body)));
callback(null);
});
});
});
}
function getBoxUpdate(callback) {
assert.strictEqual(typeof callback, 'function');
getAppstoreConfig(function (error, appstoreConfig) {
if (error) return callback(error);
var url = config.apiServerOrigin() + '/api/v1/users/' + appstoreConfig.userId + '/cloudrons/' + appstoreConfig.cloudronId + '/boxupdate';
superagent.get(url).query({ accessToken: appstoreConfig.token, boxVersion: config.version() }).timeout(10 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, error));
if (result.statusCode === 204) return callback(null); // no update
if (result.statusCode !== 200) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, util.format('Bad response: %s %s', result.statusCode, result.text)));
// { version, changelog, upgrade, sourceTarballUrl}
callback(null, result.body);
});
});
}
function getAppUpdate(app, callback) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof callback, 'function');
getAppstoreConfig(function (error, appstoreConfig) {
if (error) return callback(error);
var url = config.apiServerOrigin() + '/api/v1/users/' + appstoreConfig.userId + '/cloudrons/' + appstoreConfig.cloudronId + '/appupdate';
superagent.get(url).query({ accessToken: appstoreConfig.token, boxVersion: config.version(), appId: app.appStoreId, appVersion: app.manifest.version }).timeout(10 * 1000).end(function (error, result) {
if (error && !error.response) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, error));
if (result.statusCode === 204) return callback(null); // no update
if (result.statusCode !== 200) return callback(new AppstoreError(AppstoreError.EXTERNAL_ERROR, util.format('Bad response: %s %s', result.statusCode, result.text)));
// { id, creationDate, manifest }
callback(null, result.body);
});
});
}
+63 -99
View File
@@ -50,6 +50,7 @@ var addons = require('./addons.js'),
subdomains = require('./subdomains.js'),
superagent = require('superagent'),
sysinfo = require('./sysinfo.js'),
tld = require('tldjs'),
util = require('util'),
_ = require('underscore');
@@ -213,17 +214,16 @@ function downloadIcon(app, callback) {
}, callback);
}
function registerSubdomain(app, callback) {
function registerSubdomain(app, overwrite, callback) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof overwrite, 'boolean');
assert.strictEqual(typeof callback, 'function');
sysinfo.getIp(function (error, ip) {
sysinfo.getPublicIp(function (error, ip) {
if (error) return callback(error);
// even though the bare domain is already registered in the appstore, we still
// need to register it so that we have a dnsRecordId to wait for it to complete
async.retry({ times: 200, interval: 5000 }, function (retryCallback) {
debugApp(app, 'Registering subdomain location [%s]', app.location);
debugApp(app, 'Registering subdomain location [%s] overwrite: %s', app.location, overwrite);
// get the current record before updating it
subdomains.get(app.location, 'A', function (error, values) {
@@ -231,7 +231,7 @@ function registerSubdomain(app, callback) {
// refuse to update any existing DNS record for custom domains that we did not create
// note that the appstore sets up the naked domain for non-custom domains
if (config.isCustomDomain() && values.length !== 0 && !app.dnsRecordId) return retryCallback(null, new Error('DNS Record already exists'));
if (config.isCustomDomain() && values.length !== 0 && !overwrite) return retryCallback(null, new Error('DNS Record already exists'));
subdomains.upsert(app.location, 'A', [ ip ], function (error, changeId) {
if (error && (error.reason === SubdomainError.STILL_BUSY || error.reason === SubdomainError.EXTERNAL_ERROR)) return retryCallback(error); // try again
@@ -258,7 +258,7 @@ function unregisterSubdomain(app, location, callback) {
return callback(null);
}
sysinfo.getIp(function (error, ip) {
sysinfo.getPublicIp(function (error, ip) {
if (error) return callback(error);
async.retry({ times: 30, interval: 5000 }, function (retryCallback) {
@@ -296,7 +296,7 @@ function waitForDnsPropagation(app, callback) {
return callback(null);
}
sysinfo.getIp(function (error, ip) {
sysinfo.getPublicIp(function (error, ip) {
if (error) return callback(error);
subdomains.waitForDns(config.appFqdn(app.location), ip, 'A', { interval: 5000, times: 120 }, callback);
@@ -308,7 +308,16 @@ function waitForAltDomainDnsPropagation(app, callback) {
// try for 10 minutes before giving up. this allows the user to "reconfigure" the app in the case where
// an app has an external domain and cloudron is migrated to custom domain.
subdomains.waitForDns(app.altDomain, config.appFqdn(app.location), 'CNAME', { interval: 10000, times: 60 }, callback);
var isNakedDomain = tld.getDomain(app.altDomain) === app.altDomain;
if (isNakedDomain) { // check naked domains with A record since CNAME records don't work there
sysinfo.getPublicIp(function (error, ip) {
if (error) return callback(error);
subdomains.waitForDns(app.altDomain, ip, 'A', { interval: 10000, times: 60 }, callback);
});
} else {
subdomains.waitForDns(app.altDomain, config.appFqdn(app.location) + '.', 'CNAME', { interval: 10000, times: 60 }, callback);
}
}
// updates the app object and the database
@@ -344,6 +353,8 @@ function install(app, callback) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof callback, 'function');
const backupId = app.lastBackupId, isRestoring = app.installationState === appdb.ISTATE_PENDING_RESTORE;
async.series([
verifyManifest.bind(null, app),
@@ -353,9 +364,16 @@ function install(app, callback) {
removeCollectdProfile.bind(null, app),
stopApp.bind(null, app),
deleteContainers.bind(null, app),
addons.teardownAddons.bind(null, app, app.manifest.addons),
// oldConfig can be null during upgrades
addons.teardownAddons.bind(null, app, app.oldConfig ? app.oldConfig.manifest.addons : app.manifest.addons),
deleteVolume.bind(null, app),
unregisterSubdomain.bind(null, app, app.location),
// for restore case
function deleteImageIfChanged(done) {
if (!app.oldConfig || (app.oldConfig.manifest.dockerImage === app.manifest.dockerImage)) return done();
docker.deleteImage(app.oldConfig.manifest, done);
},
reserveHttpPort.bind(null, app),
@@ -363,7 +381,7 @@ function install(app, callback) {
downloadIcon.bind(null, app),
updateApp.bind(null, app, { installationProgress: '30, Registering subdomain' }),
registerSubdomain.bind(null, app),
registerSubdomain.bind(null, app, isRestoring /* overwrite */),
updateApp.bind(null, app, { installationProgress: '40, Downloading image' }),
docker.downloadImage.bind(null, app.manifest),
@@ -371,8 +389,19 @@ function install(app, callback) {
updateApp.bind(null, app, { installationProgress: '50, Creating volume' }),
createVolume.bind(null, app),
updateApp.bind(null, app, { installationProgress: '60, Setting up addons' }),
addons.setupAddons.bind(null, app, app.manifest.addons),
function restoreFromBackup(next) {
if (!backupId) {
async.series([
updateApp.bind(null, app, { installationProgress: '60, Setting up addons' }),
addons.setupAddons.bind(null, app, app.manifest.addons),
], next);
} else {
async.series([
updateApp.bind(null, app, { installationProgress: '60, Download backup and restoring addons' }),
backups.restoreApp.bind(null, app, app.manifest.addons, backupId),
], next);
}
},
updateApp.bind(null, app, { installationProgress: '70, Creating container' }),
createContainer.bind(null, app),
@@ -385,7 +414,7 @@ function install(app, callback) {
updateApp.bind(null, app, { installationProgress: '85, Waiting for DNS propagation' }),
exports._waitForDnsPropagation.bind(null, app),
updateApp.bind(null, app, { installationProgress: '90, Waiting for External Domain CNAME setup' }),
updateApp.bind(null, app, { installationProgress: '90, Waiting for External Domain setup' }),
exports._waitForAltDomainDnsPropagation.bind(null, app), // required when restoring and !lastBackupId
updateApp.bind(null, app, { installationProgress: '95, Configure nginx' }),
@@ -427,84 +456,6 @@ function backup(app, callback) {
});
}
// restore is also called for upgrades and infra updates. note that in those cases it is possible there is no backup
function restore(app, callback) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof callback, 'function');
// we don't have a backup, same as re-install. this allows us to install from install failures (update failures always
// have a backupId)
if (!app.lastBackupId) {
debugApp(app, 'No lastBackupId. reinstalling');
return install(app, callback);
}
var backupId = app.lastBackupId;
async.series([
updateApp.bind(null, app, { installationProgress: '10, Cleaning up old install' }),
unconfigureNginx.bind(null, app),
removeCollectdProfile.bind(null, app),
stopApp.bind(null, app),
deleteContainers.bind(null, app),
// oldConfig can be null during upgrades
addons.teardownAddons.bind(null, app, app.oldConfig ? app.oldConfig.manifest.addons : null),
deleteVolume.bind(null, app),
function deleteImageIfChanged(done) {
if (!app.oldConfig || (app.oldConfig.manifest.dockerImage === app.manifest.dockerImage)) return done();
docker.deleteImage(app.oldConfig.manifest, done);
},
reserveHttpPort.bind(null, app),
updateApp.bind(null, app, { installationProgress: '40, Downloading icon' }),
downloadIcon.bind(null, app),
updateApp.bind(null, app, { installationProgress: '55, Registering subdomain' }), // ip might change during upgrades
registerSubdomain.bind(null, app),
updateApp.bind(null, app, { installationProgress: '60, Downloading image' }),
docker.downloadImage.bind(null, app.manifest),
updateApp.bind(null, app, { installationProgress: '65, Creating volume' }),
createVolume.bind(null, app),
updateApp.bind(null, app, { installationProgress: '70, Download backup and restore addons' }),
backups.restoreApp.bind(null, app, app.manifest.addons, backupId),
updateApp.bind(null, app, { installationProgress: '75, Creating container' }),
createContainer.bind(null, app),
updateApp.bind(null, app, { installationProgress: '80, Setting up collectd profile' }),
addCollectdProfile.bind(null, app),
runApp.bind(null, app),
updateApp.bind(null, app, { installationProgress: '85, Waiting for DNS propagation' }),
exports._waitForDnsPropagation.bind(null, app),
updateApp.bind(null, app, { installationProgress: '90, Waiting for External Domain CNAME setup' }),
exports._waitForAltDomainDnsPropagation.bind(null, app),
updateApp.bind(null, app, { installationProgress: '95, Configuring Nginx' }),
configureNginx.bind(null, app),
// done!
function (callback) {
debugApp(app, 'restored');
updateApp(app, { installationState: appdb.ISTATE_INSTALLED, installationProgress: '', health: null }, callback);
}
], function seriesDone(error) {
if (error) {
debugApp(app, 'Error installing app: %s', error);
return updateApp(app, { installationState: appdb.ISTATE_ERROR, installationProgress: error.message }, callback.bind(null, error));
}
callback(null);
});
}
// note that configure is called after an infra update as well
function configure(app, callback) {
assert.strictEqual(typeof app, 'object');
@@ -524,8 +475,17 @@ function configure(app, callback) {
reserveHttpPort.bind(null, app),
updateApp.bind(null, app, { installationProgress: '20, Downloading icon' }),
downloadIcon.bind(null, app),
updateApp.bind(null, app, { installationProgress: '35, Registering subdomain' }),
registerSubdomain.bind(null, app),
registerSubdomain.bind(null, app, true /* overwrite */),
updateApp.bind(null, app, { installationProgress: '40, Downloading image' }),
docker.downloadImage.bind(null, app.manifest),
updateApp.bind(null, app, { installationProgress: '45, Ensuring volume' }),
createVolume.bind(null, app),
// re-setup addons since they rely on the app's fqdn (e.g oauth)
updateApp.bind(null, app, { installationProgress: '50, Setting up addons' }),
@@ -542,7 +502,7 @@ function configure(app, callback) {
updateApp.bind(null, app, { installationProgress: '80, Waiting for DNS propagation' }),
exports._waitForDnsPropagation.bind(null, app),
updateApp.bind(null, app, { installationProgress: '85, Waiting for External Domain CNAME setup' }),
updateApp.bind(null, app, { installationProgress: '85, Waiting for External Domain setup' }),
exports._waitForAltDomainDnsPropagation.bind(null, app),
updateApp.bind(null, app, { installationProgress: '90, Configuring Nginx' }),
@@ -732,13 +692,17 @@ function startTask(appId, callback) {
switch (app.installationState) {
case appdb.ISTATE_PENDING_UNINSTALL: return uninstall(app, callback);
case appdb.ISTATE_PENDING_CONFIGURE: return configure(app, callback);
case appdb.ISTATE_PENDING_UPDATE: return update(app, callback);
case appdb.ISTATE_PENDING_RESTORE: return restore(app, callback);
case appdb.ISTATE_PENDING_FORCE_UPDATE: return update(app, callback);
case appdb.ISTATE_PENDING_INSTALL: return install(app, callback);
case appdb.ISTATE_PENDING_CLONE: return install(app, callback);
case appdb.ISTATE_PENDING_RESTORE: return install(app, callback);
case appdb.ISTATE_PENDING_BACKUP: return backup(app, callback);
case appdb.ISTATE_INSTALLED: return handleRunCommand(app, callback);
case appdb.ISTATE_PENDING_INSTALL: return install(app, callback);
case appdb.ISTATE_PENDING_CLONE: return restore(app, callback);
case appdb.ISTATE_PENDING_FORCE_UPDATE: return update(app, callback);
case appdb.ISTATE_ERROR:
debugApp(app, 'Internal error. apptask launched with error status.');
return callback(null);
+1 -1
View File
@@ -100,7 +100,7 @@ function initialize(callback) {
var info = { scope: token.scope };
user.get(token.identifier, function (error, user) {
if (error && error.reason === DatabaseError.NOT_FOUND) return callback(null, false);
if (error && error.reason === UserError.NOT_FOUND) return callback(null, false);
if (error) return callback(error);
callback(null, user, info);
+70 -9
View File
@@ -3,15 +3,20 @@
var assert = require('assert'),
database = require('./database.js'),
DatabaseError = require('./databaseerror.js'),
safe = require('safetydance'),
util = require('util');
var BACKUPS_FIELDS = [ 'id', 'creationTime', 'version', 'type', 'dependsOn', 'state', ];
var BACKUPS_FIELDS = [ 'id', 'creationTime', 'version', 'type', 'dependsOn', 'state', 'restoreConfigJson' ];
exports = module.exports = {
add: add,
getPaged: getPaged,
getByTypeAndStatePaged: getByTypeAndStatePaged,
getByTypePaged: getByTypePaged,
get: get,
del: del,
update: update,
getByAppIdPaged: getByAppIdPaged,
_clear: clear,
@@ -20,21 +25,44 @@ exports = module.exports = {
BACKUP_TYPE_BOX: 'box',
BACKUP_STATE_NORMAL: 'normal', // should rename to created to avoid listing in UI?
BACKUP_STATE_CREATING: 'creating',
BACKUP_STATE_ERROR: 'error'
};
function postProcess(result) {
assert.strictEqual(typeof result, 'object');
result.dependsOn = result.dependsOn ? result.dependsOn.split(',') : [ ];
result.restoreConfig = result.restoreConfigJson ? safe.JSON.parse(result.restoreConfigJson) : null;
delete result.restoreConfigJson;
}
function getPaged(page, perPage, callback) {
function getByTypeAndStatePaged(type, state, page, perPage, callback) {
assert(type === exports.BACKUP_TYPE_APP || type === exports.BACKUP_TYPE_BOX);
assert.strictEqual(typeof state, 'string');
assert(typeof page === 'number' && page > 0);
assert(typeof perPage === 'number' && perPage > 0);
assert.strictEqual(typeof callback, 'function');
database.query('SELECT ' + BACKUPS_FIELDS + ' FROM backups WHERE type = ? AND state = ? ORDER BY creationTime DESC LIMIT ?,?',
[ exports.BACKUP_TYPE_BOX, exports.BACKUP_STATE_NORMAL, (page-1)*perPage, perPage ], function (error, results) {
[ type, state, (page-1)*perPage, perPage ], function (error, results) {
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
results.forEach(function (result) { postProcess(result); });
callback(null, results);
});
}
function getByTypePaged(type, page, perPage, callback) {
assert(type === exports.BACKUP_TYPE_APP || type === exports.BACKUP_TYPE_BOX);
assert(typeof page === 'number' && page > 0);
assert(typeof perPage === 'number' && perPage > 0);
assert.strictEqual(typeof callback, 'function');
database.query('SELECT ' + BACKUPS_FIELDS + ' FROM backups WHERE type = ? ORDER BY creationTime DESC LIMIT ?,?',
[ type, (page-1)*perPage, perPage ], function (error, results) {
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
results.forEach(function (result) { postProcess(result); });
@@ -81,12 +109,14 @@ function add(backup, callback) {
assert.strictEqual(typeof backup.version, 'string');
assert(backup.type === exports.BACKUP_TYPE_APP || backup.type === exports.BACKUP_TYPE_BOX);
assert(util.isArray(backup.dependsOn));
assert.strictEqual(typeof backup.restoreConfig, 'object');
assert.strictEqual(typeof callback, 'function');
var creationTime = backup.creationTime || new Date(); // allow tests to set the time
var restoreConfig = backup.restoreConfig ? JSON.stringify(backup.restoreConfig) : '';
database.query('INSERT INTO backups (id, version, type, creationTime, state, dependsOn) VALUES (?, ?, ?, ?, ?, ?)',
[ backup.id, backup.version, backup.type, creationTime, exports.BACKUP_STATE_NORMAL, backup.dependsOn.join(',') ],
database.query('INSERT INTO backups (id, version, type, creationTime, state, dependsOn, restoreConfigJson) VALUES (?, ?, ?, ?, ?, ?, ?)',
[ backup.id, backup.version, backup.type, creationTime, exports.BACKUP_STATE_NORMAL, backup.dependsOn.join(','), restoreConfig ],
function (error) {
if (error && error.code === 'ER_DUP_ENTRY') return callback(new DatabaseError(DatabaseError.ALREADY_EXISTS));
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
@@ -95,6 +125,26 @@ function add(backup, callback) {
});
}
function update(id, backup, callback) {
assert.strictEqual(typeof id, 'string');
assert.strictEqual(typeof backup, 'object');
assert.strictEqual(typeof callback, 'function');
var fields = [ ], values = [ ];
for (var p in backup) {
fields.push(p + ' = ?');
values.push(backup[p]);
}
values.push(id);
database.query('UPDATE backups SET ' + fields.join(', ') + ' WHERE id = ?', values, function (error) {
if (error && error.reason === DatabaseError.NOT_FOUND) return callback(new DatabaseError(DatabaseError.NOT_FOUND));
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
callback(null);
});
}
function clear(callback) {
assert.strictEqual(typeof callback, 'function');
@@ -108,8 +158,19 @@ function del(id, callback) {
assert.strictEqual(typeof id, 'string');
assert.strictEqual(typeof callback, 'function');
database.query('DELETE FROM backups WHERE id=?', [ id ], function (error) {
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
callback(null);
get(id, function (error, result) {
if (error && error.reason === DatabaseError.NOT_FOUND) return callback();
if (error) return callback(error);
var whereClause = [ 'id=?' ], whereArgs = [ result.id ];
result.dependsOn.forEach(function (id) {
whereClause.push('id=?');
whereArgs.push(id);
});
database.query('DELETE FROM backups WHERE ' + whereClause.join(' OR '), whereArgs, function (error) {
if (error) return callback(new DatabaseError(DatabaseError.INTERNAL_ERROR, error));
callback(null);
});
});
}

Some files were not shown because too many files have changed in this diff Show More