1{ config, lib, pkgs, ... }: with lib;
2let
3 cfg = config.services.openiscsi;
4in
5{
6 options.services.openiscsi = with types; {
7 enable = mkEnableOption "the openiscsi iscsi daemon";
8 enableAutoLoginOut = mkEnableOption ''
9 automatic login and logout of all automatic targets.
10 You probably do not want this
11 '';
12 discoverPortal = mkOption {
13 type = nullOr str;
14 default = null;
15 description = "Portal to discover targets on";
16 };
17 name = mkOption {
18 type = str;
19 description = "Name of this iscsi initiator";
20 example = "iqn.2020-08.org.linux-iscsi.initiatorhost:example";
21 };
22 package = mkPackageOption pkgs "openiscsi" { };
23
24 extraConfig = mkOption {
25 type = str;
26 default = "";
27 description = "Lines to append to default iscsid.conf";
28 };
29
30 extraConfigFile = mkOption {
31 description = ''
32 Append an additional file's contents to /etc/iscsid.conf. Use a non-store path
33 and store passwords in this file.
34 '';
35 default = null;
36 type = nullOr str;
37 };
38 };
39
40 config = mkIf cfg.enable {
41 environment.etc."iscsi/iscsid.conf.fragment".source = pkgs.runCommand "iscsid.conf" {} ''
42 cat "${cfg.package}/etc/iscsi/iscsid.conf" > $out
43 cat << 'EOF' >> $out
44 ${cfg.extraConfig}
45 ${optionalString cfg.enableAutoLoginOut "node.startup = automatic"}
46 EOF
47 '';
48 environment.etc."iscsi/initiatorname.iscsi".text = "InitiatorName=${cfg.name}";
49
50 systemd.packages = [ cfg.package ];
51
52 systemd.services."iscsid" = {
53 wantedBy = [ "multi-user.target" ];
54 preStart =
55 let
56 extraCfgDumper = optionalString (cfg.extraConfigFile != null) ''
57 if [ -f "${cfg.extraConfigFile}" ]; then
58 printf "\n# The following is from ${cfg.extraConfigFile}:\n"
59 cat "${cfg.extraConfigFile}"
60 else
61 echo "Warning: services.openiscsi.extraConfigFile ${cfg.extraConfigFile} does not exist!" >&2
62 fi
63 '';
64 in ''
65 (
66 cat ${config.environment.etc."iscsi/iscsid.conf.fragment".source}
67 ${extraCfgDumper}
68 ) > /etc/iscsi/iscsid.conf
69 '';
70 };
71 systemd.sockets."iscsid".wantedBy = [ "sockets.target" ];
72
73 systemd.services."iscsi" = mkIf cfg.enableAutoLoginOut {
74 wantedBy = [ "remote-fs.target" ];
75 serviceConfig.ExecStartPre = mkIf (cfg.discoverPortal != null) "${cfg.package}/bin/iscsiadm --mode discoverydb --type sendtargets --portal ${escapeShellArg cfg.discoverPortal} --discover";
76 };
77
78 environment.systemPackages = [ cfg.package ];
79 boot.kernelModules = [ "iscsi_tcp" ];
80 };
81}