git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #55510 from florianjacob/declarative-printers

nixos/printers: declarative configuration

commitad13ebe029695f51cae4ca318bb39b11e33bb3a3 authorSilvan Mosberger <contact@infinisil.com> dateTue 3 Sep 2019, 17:46 (7 years ago) parent3a601ca18a5d23
4 files changed+242−81
nixos/doc/manual/release-notes/rl-1909.xml+10 nixos/modules/hardware/printers.nix+135 nixos/modules/module-list.nix+1 nixos/tests/printing.nix+96−81
nixos/doc/manual/release-notes/rl-1909.xml+10
@@ -135,7 +135,17 @@
135135 <literal>./programs/dwm-status.nix</literal>
136136 </para>
137137 </listitem>
138+ <listitem>
139+ <para>
140+ The new <varname>hardware.printers</varname> module allows to declaratively configure CUPS printers
141+ via the <varname>ensurePrinters</varname> and
142+ <varname>ensureDefaultPrinter</varname> options.
143+ <varname>ensurePrinters</varname> will never delete existing printers,
144+ but will make sure that the given printers are configured as declared.
145+ </para>
146+ </listitem>
138147 </itemizedlist>
148+
139149 </section>
140150
141151 <section xmlns="http://docbook.org/ns/docbook"
nixos/modules/hardware/printers.nixnew file+135
@@ -0,0 +1,135 @@
1+{ config, lib, pkgs, ... }:
2+with lib;
3+let
4+ cfg = config.hardware.printers;
5+ ppdOptionsString = options: optionalString (options != {})
6+ (concatStringsSep " "
7+ (mapAttrsToList (name: value: "-o '${name}'='${value}'") options)
8+ );
9+ ensurePrinter = p: ''
10+ ${pkgs.cups}/bin/lpadmin -p '${p.name}' -E \
11+ ${optionalString (p.location != null) "-L '${p.location}'"} \
12+ ${optionalString (p.description != null) "-D '${p.description}'"} \
13+ -v '${p.deviceUri}' \
14+ -m '${p.model}' \
15+ ${ppdOptionsString p.ppdOptions}
16+ '';
17+ ensureDefaultPrinter = name: ''
18+ ${pkgs.cups}/bin/lpoptions -d '${name}'
19+ '';
20+
21+ # "graph but not # or /" can't be implemented as regex alone due to missing lookahead support
22+ noInvalidChars = str: all (c: c != "#" && c != "/") (stringToCharacters str);
23+ printerName = (types.addCheck (types.strMatching "[[:graph:]]+") noInvalidChars)
24+ // { description = "printable string without spaces, # and /"; };
25+
26+
27+in {
28+ options = {
29+ hardware.printers = {
30+ ensureDefaultPrinter = mkOption {
31+ type = types.nullOr printerName;
32+ default = null;
33+ description = ''
34+ Ensures the named printer is the default CUPS printer / printer queue.
35+ '';
36+ };
37+ ensurePrinters = mkOption {
38+ description = ''
39+ Will regularly ensure that the given CUPS printers are configured as declared here.
40+ If a printer's options are manually changed afterwards, they will be overwritten eventually.
41+ This option will never delete any printer, even if removed from this list.
42+ You can check existing printers with <command>lpstat -s</command>
43+ and remove printers with <command>lpadmin -x &lt;printer-name&gt;</command>.
44+ Printers not listed here can still be manually configured.
45+ '';
46+ default = [];
47+ type = types.listOf (types.submodule {
48+ options = {
49+ name = mkOption {
50+ type = printerName;
51+ example = "BrotherHL_Workroom";
52+ description = ''
53+ Name of the printer / printer queue.
54+ May contain any printable characters except "/", "#", and space.
55+ '';
56+ };
57+ location = mkOption {
58+ type = types.nullOr types.str;
59+ default = null;
60+ example = "Workroom";
61+ description = ''
62+ Optional human-readable location.
63+ '';
64+ };
65+ description = mkOption {
66+ type = types.nullOr types.str;
67+ default = null;
68+ example = "Brother HL-5140";
69+ description = ''
70+ Optional human-readable description.
71+ '';
72+ };
73+ deviceUri = mkOption {
74+ type = types.str;
75+ example = [
76+ "ipp://printserver.local/printers/BrotherHL_Workroom"
77+ "usb://HP/DESKJET%20940C?serial=CN16E6C364BH"
78+ ];
79+ description = ''
80+ How to reach the printer.
81+ <command>lpinfo -v</command> shows a list of supported device URIs and schemes.
82+ '';
83+ };
84+ model = mkOption {
85+ type = types.str;
86+ example = literalExample ''
87+ gutenprint.''${lib.version.majorMinor (lib.getVersion pkgs.cups)}://brother-hl-5140/expert
88+ '';
89+ description = ''
90+ Location of the ppd driver file for the printer.
91+ <command>lpinfo -m</command> shows a list of supported models.
92+ '';
93+ };
94+ ppdOptions = mkOption {
95+ type = types.attrsOf types.str;
96+ example = {
97+ "PageSize" = "A4";
98+ "Duplex" = "DuplexNoTumble";
99+ };
100+ default = {};
101+ description = ''
102+ Sets PPD options for the printer.
103+ <command>lpoptions [-p printername] -l</command> shows suported PPD options for the given printer.
104+ '';
105+ };
106+ };
107+ });
108+ };
109+ };
110+ };
111+
112+ config = mkIf (cfg.ensurePrinters != [] && config.services.printing.enable) {
113+ systemd.services."ensure-printers" = let
114+ cupsUnit = if config.services.printing.startWhenNeeded then "cups.socket" else "cups.service";
115+ in {
116+ description = "Ensure NixOS-configured CUPS printers";
117+ wantedBy = [ "multi-user.target" ];
118+ requires = [ cupsUnit ];
119+ # in contrast to cups.socket, for cups.service, this is actually not enough,
120+ # as the cups service reports its activation before clients can actually interact with it.
121+ # Because of this, commands like `lpinfo -v` will report a bad file descriptor
122+ # due to the missing UNIX socket without sufficient sleep time.
123+ after = [ cupsUnit ];
124+
125+ serviceConfig = {
126+ Type = "oneshot";
127+ };
128+
129+ # sleep 10 is required to wait until cups.service is actually initialized and has created its UNIX socket file
130+ script = (optionalString (!config.services.printing.startWhenNeeded) "sleep 10\n")
131+ + (concatMapStringsSep "\n" ensurePrinter cfg.ensurePrinters)
132+ + optionalString (cfg.ensureDefaultPrinter != null) (ensureDefaultPrinter cfg.ensureDefaultPrinter);
133+ };
134+ };
135+}
nixos/modules/module-list.nix+1
@@ -59,6 +59,7 @@
5959 ./hardware/nitrokey.nix
6060 ./hardware/opengl.nix
6161 ./hardware/pcmcia.nix
62+ ./hardware/printers.nix
6263 ./hardware/raid/hpsa.nix
6364 ./hardware/steam-hardware.nix
6465 ./hardware/usb-wwan.nix
nixos/tests/printing.nix+96−81
@@ -1,99 +1,114 @@
11# Test printing via CUPS.
22
3−import ./make-test.nix ({pkgs, ... }: {
3+import ./make-test.nix ({pkgs, ... }:
4+let
5+ printingServer = startWhenNeeded: {
6+ services.printing.enable = true;
7+ services.printing.startWhenNeeded = startWhenNeeded;
8+ services.printing.listenAddresses = [ "*:631" ];
9+ services.printing.defaultShared = true;
10+ services.printing.extraConf =
11+ ''
12+ <Location />
13+ Order allow,deny
14+ Allow from all
15+ </Location>
16+ '';
17+ networking.firewall.allowedTCPPorts = [ 631 ];
18+ # Add a HP Deskjet printer connected via USB to the server.
19+ hardware.printers.ensurePrinters = [{
20+ name = "DeskjetLocal";
21+ deviceUri = "usb://foobar/printers/foobar";
22+ model = "drv:///sample.drv/deskjet.ppd";
23+ }];
24+ };
25+ printingClient = startWhenNeeded: {
26+ services.printing.enable = true;
27+ services.printing.startWhenNeeded = startWhenNeeded;
28+ # Add printer to the client as well, via IPP.
29+ hardware.printers.ensurePrinters = [{
30+ name = "DeskjetRemote";
31+ deviceUri = "ipp://${if startWhenNeeded then "socketActivatedServer" else "serviceServer"}/printers/DeskjetLocal";
32+ model = "drv:///sample.drv/deskjet.ppd";
33+ }];
34+ hardware.printers.ensureDefaultPrinter = "DeskjetRemote";
35+ };
36+
37+in
38+
39+{
440 name = "printing";
541 meta = with pkgs.stdenv.lib.maintainers; {
642 maintainers = [ domenkozar eelco matthewbauer ];
743 };
844
945 nodes = {
46+ socketActivatedServer = { ... }: (printingServer true);
47+ serviceServer = { ... }: (printingServer false);
1048
11− server =
12− { ... }:
13− { services.printing.enable = true;
14− services.printing.listenAddresses = [ "*:631" ];
15− services.printing.defaultShared = true;
16− services.printing.extraConf =
17− ''
18− <Location />
19− Order allow,deny
20− Allow from all
21− </Location>
22− '';
23− networking.firewall.allowedTCPPorts = [ 631 ];
24− };
25−
26− client =
27− { ... }:
28− { services.printing.enable = true;
29− };
30−
49+ socketActivatedClient = { ... }: (printingClient true);
50+ serviceClient = { ... }: (printingClient false);
3151 };
3252
3353 testScript =
3454 ''
3555 startAll;
3656
37− $client->succeed("lpstat -r") =~ /scheduler is running/ or die;
38− # check local encrypted connections work without error
39− $client->succeed("lpstat -E -r") =~ /scheduler is running/ or die;
40− # Test that UNIX socket is used for connections.
41− $client->succeed("lpstat -H") =~ "/run/cups/cups.sock" or die;
42− # Test that HTTP server is available too.
43− $client->succeed("curl --fail http://localhost:631/");
44− $client->succeed("curl --fail http://server:631/");
45− $server->fail("curl --fail --connect-timeout 2 http://client:631/");
46−
47− # Add a HP Deskjet printer connected via USB to the server.
48− $server->succeed("lpadmin -p DeskjetLocal -E -v usb://foobar/printers/foobar");
49−
50− # Add it to the client as well via IPP.
51− $client->succeed("lpadmin -p DeskjetRemote -E -v ipp://server/printers/DeskjetLocal");
52− $client->succeed("lpadmin -d DeskjetRemote");
53−
54− # Do some status checks.
55− $client->succeed("lpstat -a") =~ /DeskjetRemote accepting requests/ or die;
56− $client->succeed("lpstat -h server:631 -a") =~ /DeskjetLocal accepting requests/ or die;
57− $client->succeed("cupsdisable DeskjetRemote");
58− $client->succeed("lpq") =~ /DeskjetRemote is not ready.*no entries/s or die;
59− $client->succeed("cupsenable DeskjetRemote");
60− $client->succeed("lpq") =~ /DeskjetRemote is ready.*no entries/s or die;
61−
62− # Test printing various file types.
63− foreach my $file ("${pkgs.groff.doc}/share/doc/*/examples/mom/penguin.pdf",
64− "${pkgs.groff.doc}/share/doc/*/meref.ps",
65− "${pkgs.cups.out}/share/doc/cups/images/cups.png",
66− "${pkgs.pcre.doc}/share/doc/pcre/pcre.txt")
67− {
68− $file =~ /([^\/]*)$/; my $fn = $1;
69−
70− subtest "print $fn", sub {
71−
72− # Print the file on the client.
73− $client->succeed("lp $file");
74− $client->sleep(10);
75− $client->succeed("lpq") =~ /active.*root.*$fn/ or die;
76−
77− # Ensure that a raw PCL file appeared in the server's queue
78− # (showing that the right filters have been applied). Of
79− # course, since there is no actual USB printer attached, the
80− # file will stay in the queue forever.
81− $server->waitForFile("/var/spool/cups/d*-001");
82− $server->sleep(10);
83− $server->succeed("lpq -a") =~ /$fn/ or die;
84−
85− # Delete the job on the client. It should disappear on the
86− # server as well.
87− $client->succeed("lprm");
88− $client->sleep(10);
89− $client->succeed("lpq -a") =~ /no entries/;
90− Machine::retry sub {
91− return 1 if $server->succeed("lpq -a") =~ /no entries/;
57+ # Make sure that cups is up on both sides.
58+ $serviceServer->waitForUnit("cups.service");
59+ $serviceClient->waitForUnit("cups.service");
60+ # wait until cups is fully initialized and ensure-printers has executed with 10s delay
61+ $serviceClient->sleep(20);
62+ $socketActivatedClient->waitUntilSucceeds("systemctl status ensure-printers | grep -q -E 'code=exited, status=0/SUCCESS'");
63+ sub testPrinting {
64+ my ($client, $server) = (@_);
65+ my $clientHostname = $client->name();
66+ my $serverHostname = $server->name();
67+ $client->succeed("lpstat -r") =~ /scheduler is running/ or die;
68+ # Test that UNIX socket is used for connections.
69+ $client->succeed("lpstat -H") =~ "/var/run/cups/cups.sock" or die;
70+ # Test that HTTP server is available too.
71+ $client->succeed("curl --fail http://localhost:631/");
72+ $client->succeed("curl --fail http://$serverHostname:631/");
73+ $server->fail("curl --fail --connect-timeout 2 http://$clientHostname:631/");
74+ # Do some status checks.
75+ $client->succeed("lpstat -a") =~ /DeskjetRemote accepting requests/ or die;
76+ $client->succeed("lpstat -h $serverHostname:631 -a") =~ /DeskjetLocal accepting requests/ or die;
77+ $client->succeed("cupsdisable DeskjetRemote");
78+ $client->succeed("lpq") =~ /DeskjetRemote is not ready.*no entries/s or die;
79+ $client->succeed("cupsenable DeskjetRemote");
80+ $client->succeed("lpq") =~ /DeskjetRemote is ready.*no entries/s or die;
81+ # Test printing various file types.
82+ foreach my $file ("${pkgs.groff.doc}/share/doc/*/examples/mom/penguin.pdf",
83+ "${pkgs.groff.doc}/share/doc/*/meref.ps",
84+ "${pkgs.cups.out}/share/doc/cups/images/cups.png",
85+ "${pkgs.pcre.doc}/share/doc/pcre/pcre.txt")
86+ {
87+ $file =~ /([^\/]*)$/; my $fn = $1;
88+ subtest "print $fn", sub {
89+ # Print the file on the client.
90+ $client->succeed("lp $file");
91+ $client->waitUntilSucceeds("lpq | grep -q -E 'active.*root.*$fn'");
92+ # Ensure that a raw PCL file appeared in the server's queue
93+ # (showing that the right filters have been applied). Of
94+ # course, since there is no actual USB printer attached, the
95+ # file will stay in the queue forever.
96+ $server->waitForFile("/var/spool/cups/d*-001");
97+ $server->waitUntilSucceeds("lpq -a | grep -q -E '$fn'");
98+ # Delete the job on the client. It should disappear on the
99+ # server as well.
100+ $client->succeed("lprm");
101+ $client->waitUntilSucceeds("lpq -a | grep -q -E 'no entries'");
102+ Machine::retry sub {
103+ return 1 if $server->succeed("lpq -a") =~ /no entries/;
104+ };
105+ # The queue is empty already, so this should be safe.
106+ # Otherwise, pairs of "c*"-"d*-001" files might persist.
107+ $server->execute("rm /var/spool/cups/*");
92108 };
93− # The queue is empty already, so this should be safe.
94− # Otherwise, pairs of "c*"-"d*-001" files might persist.
95− $server->execute("rm /var/spool/cups/*");
96− };
109+ }
97110 }
98− '';
111+ testPrinting($serviceClient, $serviceServer);
112+ testPrinting($socketActivatedClient, $socketActivatedServer);
113+ '';
99114})