apt-get tests for Packages::Apt probe
[scpubgit/System-Introspector.git] / lib / System / Introspector / Probe / Packages / Apt.pm
CommitLineData
afd7c030 1package System::Introspector::Probe::Packages::Apt;
97b10529 2use Moo;
3
9ee104cc 4use System::Introspector::Util qw(
5 handle_from_command
6 transform_exceptions
7);
8
025e0d3f 9has apt_lists_dir => (is => 'ro', builder => 1);
10has apt_update_after => (is => 'ro', default => sub { 86400 });
11has apt_update => (is => 'ro');
12
13sub _build_apt_lists_dir { '/var/lib/apt/lists' }
14
97b10529 15sub gather {
16 my ($self) = @_;
17 return {
025e0d3f 18 update => {
19 last => $self->_last_apt_update,
20 run => transform_exceptions {
21 return { result => $self->_check_apt_state };
22 },
23 },
9ee104cc 24 installed => transform_exceptions {
25 return { packages => $self->_gather_installed };
26 },
025e0d3f 27 upgradable => transform_exceptions {
28 return { actions => $self->_gather_upgradable };
29 },
97b10529 30 };
31}
32
025e0d3f 33sub _last_apt_update {
34 my ($self) = @_;
35 return scalar( (stat($self->apt_lists_dir))[9] );
36}
37
38sub _check_apt_state {
39 my ($self) = @_;
40 return 'disabled' unless $self->apt_update;
41 my $threshold = $self->apt_update_after;
42 my $last_change = $self->_last_apt_update;
43 return 'no'if ($last_change + $threshold) > time;
44 handle_from_command 'apt-get update';
45 return 'yes';
46}
47
3d4ae7f9 48sub _open_dpkg_query_pipe {
97b10529 49 my ($self) = @_;
9ee104cc 50 return handle_from_command 'dpkg-query --show';
3d4ae7f9 51}
52
025e0d3f 53sub _open_apt_get_upgrade_simulation_pipe {
54 my ($self) = @_;
55 return handle_from_command 'apt-get -s upgrade';
56}
57
58sub _gather_upgradable {
59 my ($self) = @_;
60 my $pipe = $self->_open_apt_get_upgrade_simulation_pipe;
61 my %action;
62 while (defined( my $line = <$pipe> )) {
63 chomp $line;
64 if ($line =~ m{^(inst|remv)\s+(\S+)\s+(.+)$}i) {
65 $action{ lc($1) }{ $2 } = $3;
66 }
67 }
68 return \%action;
69}
70
3d4ae7f9 71sub _gather_installed {
72 my ($self) = @_;
73 my $pipe = $self->_open_dpkg_query_pipe;
97b10529 74 my %package;
75 while (defined( my $line = <$pipe> )) {
76 chomp $line;
77 my ($package, $version) = split m{\s+}, $line;
78 $package{ $package } = {
79 version => $version,
80 };
81 }
82 return \%package;
83}
84
851;
535e84b6 86
87__END__
88
89=head1 NAME
90
91System::Introspector::Packages::Apt - Gather APT package status
92
93=head1 DESCRIPTION
94
95Uses C<dpkg-query> to list all installed packages.
96
97=head1 SEE ALSO
98
99=over
100
101=item L<System::Introspector>
102
103=back
104
105=cut