moved probe classes to ::Probe:: namespace
[scpubgit/System-Introspector.git] / lib / System / Introspector / State.pm
CommitLineData
60e1cc39 1package System::Introspector::State;
2use Moo;
3use Data::YAML::Writer;
4use Object::Remote;
5use Object::Remote::Future;
6use System::Introspector::Gatherer;
7
8has config => (is => 'ro', required => 1);
9
10has introspectors => (is => 'lazy');
11
12has host => (is => 'ro');
13
14has storage => (is => 'ro', required => 1);
15
16has node_path => (is => 'lazy');
17
18sub fetch {
19 my ($self) = @_;
20 my $gatherer = $self->_create_gatherer;
21 my $spec = $self->introspectors;
22 my %report;
23 for my $class_base (sort keys %$spec) {
24 $report{ $class_base } = $gatherer
25 ->gather($class_base, $spec->{ $class_base });
26 }
27 return \%report;
28}
29
30sub fetch_and_store {
31 my ($self) = @_;
32 return $self->_store($self->fetch);
33}
34
35sub _build_node_path {
36 my ($self) = @_;
37 return defined($self->host)
38 ? sprintf('host/%s', $self->host)
39 : 'local';
40}
41
42sub _build_introspectors {
43 my ($self) = @_;
44 return $self->config->{introspect};
45}
46
47sub _store {
48 my ($self, $data) = @_;
49 my $yaml = Data::YAML::Writer->new;
50 my $storage = $self->storage;
51 my @files;
52 for my $class (sort keys %$data) {
53 my $file = sprintf '%s.yml', join '/',
54 node => $self->node_path,
55 map lc, map {
56 s{([a-z0-9])([A-Z])}{${1}_${2}}g;
57 $_;
58 } split m{::}, $class;
59 my $fh = $storage->open('>:utf8', $file, mkpath => 1);
60 print "Writing $file\n";
61 $yaml->write($data->{$class}, $fh);
62 push @files, $storage->file($file);
63 }
64 $self->_cleanup(\@files);
65 return 1;
66}
67
68sub _cleanup {
69 my ($self, $known_files) = @_;
70 my %known = map { ($_ => 1) } @$known_files;
71 my $data_dir = $self->storage->file(node => $self->node_path);
72 my @files = $self->storage->find_files('yml', node => $self->node_path);
73 for my $file (@files) {
74 next if $known{$file};
75 print "Removing $file\n";
76 unlink($file)
77 or die "Unable to remove '$file': $!\n";
78 }
79 return 1;
80}
81
82sub _create_gatherer {
83 my ($self) = @_;
84 if (defined( my $host = $self->host )) {
85 return System::Introspector::Gatherer->new::on($host);
86 }
87 return System::Introspector::Gatherer->new;
88}
89
901;