summary refs log tree commit diff
path: root/nixos/modules/services/networking/seafile.nix
blob: 2839ffb60a1fd97ff1f508c46a6736a6a0306d43 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
{ config, lib, pkgs, ... }:
with lib;
let
  cfg = config.services.seafile;
  settingsFormat = pkgs.formats.ini { };

  ccnetConf = settingsFormat.generate "ccnet.conf" cfg.ccnetSettings;

  seafileConf = settingsFormat.generate "seafile.conf" cfg.seafileSettings;

  seahubSettings = pkgs.writeText "seahub_settings.py" ''
    FILE_SERVER_ROOT = '${cfg.ccnetSettings.General.SERVICE_URL}/seafhttp'
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': '${seahubDir}/seahub.db',
        }
    }
    MEDIA_ROOT = '${seahubDir}/media/'
    THUMBNAIL_ROOT = '${seahubDir}/thumbnail/'

    with open('${seafRoot}/.seahubSecret') as f:
        SECRET_KEY = f.readline().rstrip()

    ${cfg.seahubExtraConf}
  '';

  seafRoot = "/var/lib/seafile"; # hardcode it due to dynamicuser
  ccnetDir = "${seafRoot}/ccnet";
  dataDir = "${seafRoot}/data";
  seahubDir = "${seafRoot}/seahub";

in {

  ###### Interface

  options.services.seafile = {
    enable = mkEnableOption "Seafile server";

    ccnetSettings = mkOption {
      type = types.submodule {
        freeformType = settingsFormat.type;

        options = {
          General = {
            SERVICE_URL = mkOption {
              type = types.str;
              example = "https://www.example.com";
              description = ''
                Seahub public URL.
              '';
            };
          };
        };
      };
      default = { };
      description = ''
        Configuration for ccnet, see
        <link xlink:href="https://manual.seafile.com/config/ccnet-conf/"/>
        for supported values.
      '';
    };

    seafileSettings = mkOption {
      type = types.submodule {
        freeformType = settingsFormat.type;

        options = {
          fileserver = {
            port = mkOption {
              type = types.port;
              default = 8082;
              description = ''
                The tcp port used by seafile fileserver.
              '';
            };
            host = mkOption {
              type = types.str;
              default = "127.0.0.1";
              example = "0.0.0.0";
              description = ''
                The binding address used by seafile fileserver.
              '';
            };
          };
        };
      };
      default = { };
      description = ''
        Configuration for seafile-server, see
        <link xlink:href="https://manual.seafile.com/config/seafile-conf/"/>
        for supported values.
      '';
    };

    workers = mkOption {
      type = types.int;
      default = 4;
      example = 10;
      description = ''
        The number of gunicorn worker processes for handling requests.
      '';
    };

    adminEmail = mkOption {
      example = "john@example.com";
      type = types.str;
      description = ''
        Seafile Seahub Admin Account Email.
      '';
    };

    initialAdminPassword = mkOption {
      example = "someStrongPass";
      type = types.str;
      description = ''
        Seafile Seahub Admin Account initial password.
        Should be change via Seahub web front-end.
      '';
    };

    seafilePackage = mkOption {
      type = types.package;
      description = "Which package to use for the seafile server.";
      default = pkgs.seafile-server;
      defaultText = literalExpression "pkgs.seafile-server";
    };

    seahubExtraConf = mkOption {
      default = "";
      type = types.lines;
      description = ''
        Extra config to append to `seahub_settings.py` file.
        Refer to <link xlink:href="https://manual.seafile.com/config/seahub_settings_py/" />
        for all available options.
      '';
    };
  };

  ###### Implementation

  config = mkIf cfg.enable {

    environment.etc."seafile/ccnet.conf".source = ccnetConf;
    environment.etc."seafile/seafile.conf".source = seafileConf;
    environment.etc."seafile/seahub_settings.py".source = seahubSettings;

    systemd.targets.seafile = {
      wantedBy = [ "multi-user.target" ];
      description = "Seafile components";
    };

    systemd.services = let
      securityOptions = {
        ProtectHome = true;
        PrivateUsers = true;
        PrivateDevices = true;
        ProtectClock = true;
        ProtectHostname = true;
        ProtectProc = "invisible";
        ProtectKernelModules = true;
        ProtectKernelTunables = true;
        ProtectKernelLogs = true;
        ProtectControlGroups = true;
        RestrictNamespaces = true;
        LockPersonality = true;
        RestrictRealtime = true;
        RestrictSUIDSGID = true;
        MemoryDenyWriteExecute = true;
        SystemCallArchitectures = "native";
        RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" ];
      };
    in {
      seaf-server = {
        description = "Seafile server";
        partOf = [ "seafile.target" ];
        after = [ "network.target" ];
        wantedBy = [ "seafile.target" ];
        restartTriggers = [ ccnetConf seafileConf ];
        serviceConfig = securityOptions // {
          User = "seafile";
          Group = "seafile";
          DynamicUser = true;
          StateDirectory = "seafile";
          RuntimeDirectory = "seafile";
          LogsDirectory = "seafile";
          ConfigurationDirectory = "seafile";
          ExecStart = ''
            ${cfg.seafilePackage}/bin/seaf-server \
            --foreground \
            -F /etc/seafile \
            -c ${ccnetDir} \
            -d ${dataDir} \
            -l /var/log/seafile/server.log \
            -P /run/seafile/server.pid \
            -p /run/seafile
          '';
        };
        preStart = ''
          if [ ! -f "${seafRoot}/server-setup" ]; then
              mkdir -p ${dataDir}/library-template
              mkdir -p ${ccnetDir}/{GroupMgr,misc,OrgMgr,PeerMgr}
              ${pkgs.sqlite}/bin/sqlite3 ${ccnetDir}/GroupMgr/groupmgr.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/groupmgr.sql"
              ${pkgs.sqlite}/bin/sqlite3 ${ccnetDir}/misc/config.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/config.sql"
              ${pkgs.sqlite}/bin/sqlite3 ${ccnetDir}/OrgMgr/orgmgr.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/org.sql"
              ${pkgs.sqlite}/bin/sqlite3 ${ccnetDir}/PeerMgr/usermgr.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/user.sql"
              ${pkgs.sqlite}/bin/sqlite3 ${dataDir}/seafile.db ".read ${cfg.seafilePackage}/share/seafile/sql/sqlite/seafile.sql"
              echo "${cfg.seafilePackage.version}-sqlite" > "${seafRoot}"/server-setup
          fi
          # checking for upgrades and handling them
          # WARNING: needs to be extended to actually handle major version migrations
          installedMajor=$(cat "${seafRoot}/server-setup" | cut -d"-" -f1 | cut -d"." -f1)
          installedMinor=$(cat "${seafRoot}/server-setup" | cut -d"-" -f1 | cut -d"." -f2)
          pkgMajor=$(echo "${cfg.seafilePackage.version}" | cut -d"." -f1)
          pkgMinor=$(echo "${cfg.seafilePackage.version}" | cut -d"." -f2)
          if [ $installedMajor != $pkgMajor ] || [ $installedMinor != $pkgMinor ]; then
              echo "Unsupported upgrade" >&2
              exit 1
          fi
        '';
      };

      seahub = {
        description = "Seafile Server Web Frontend";
        wantedBy = [ "seafile.target" ];
        partOf = [ "seafile.target" ];
        after = [ "network.target" "seaf-server.service" ];
        requires = [ "seaf-server.service" ];
        restartTriggers = [ seahubSettings ];
        environment = {
          PYTHONPATH = "${pkgs.seahub.pythonPath}:${pkgs.seahub}/thirdpart:${pkgs.seahub}";
          DJANGO_SETTINGS_MODULE = "seahub.settings";
          CCNET_CONF_DIR = ccnetDir;
          SEAFILE_CONF_DIR = dataDir;
          SEAFILE_CENTRAL_CONF_DIR = "/etc/seafile";
          SEAFILE_RPC_PIPE_PATH = "/run/seafile";
          SEAHUB_LOG_DIR = "/var/log/seafile";
        };
        serviceConfig = securityOptions // {
          User = "seafile";
          Group = "seafile";
          DynamicUser = true;
          RuntimeDirectory = "seahub";
          StateDirectory = "seafile";
          LogsDirectory = "seafile";
          ConfigurationDirectory = "seafile";
          ExecStart = ''
            ${pkgs.seahub.python.pkgs.gunicorn}/bin/gunicorn seahub.wsgi:application \
            --name seahub \
            --workers ${toString cfg.workers} \
            --log-level=info \
            --preload \
            --timeout=1200 \
            --limit-request-line=8190 \
            --bind unix:/run/seahub/gunicorn.sock
          '';
        };
        preStart = ''
          mkdir -p ${seahubDir}/media
          # Link all media except avatars
          for m in `find ${pkgs.seahub}/media/ -maxdepth 1 -not -name "avatars"`; do
            ln -sf $m ${seahubDir}/media/
          done
          if [ ! -e "${seafRoot}/.seahubSecret" ]; then
              ${pkgs.seahub.python}/bin/python ${pkgs.seahub}/tools/secret_key_generator.py > ${seafRoot}/.seahubSecret
              chmod 400 ${seafRoot}/.seahubSecret
          fi
          if [ ! -f "${seafRoot}/seahub-setup" ]; then
              # avatars directory should be writable
              install -D -t ${seahubDir}/media/avatars/ ${pkgs.seahub}/media/avatars/default.png
              install -D -t ${seahubDir}/media/avatars/groups ${pkgs.seahub}/media/avatars/groups/default.png
              # init database
              ${pkgs.seahub}/manage.py migrate
              # create admin account
              ${pkgs.expect}/bin/expect -c 'spawn ${pkgs.seahub}/manage.py createsuperuser --email=${cfg.adminEmail}; expect "Password: "; send "${cfg.initialAdminPassword}\r"; expect "Password (again): "; send "${cfg.initialAdminPassword}\r"; expect "Superuser created successfully."'
              echo "${pkgs.seahub.version}-sqlite" > "${seafRoot}/seahub-setup"
          fi
          if [ $(cat "${seafRoot}/seahub-setup" | cut -d"-" -f1) != "${pkgs.seahub.version}" ]; then
              # update database
              ${pkgs.seahub}/manage.py migrate
              echo "${pkgs.seahub.version}-sqlite" > "${seafRoot}/seahub-setup"
          fi
        '';
      };
    };
  };
}