reworked gatherer to be more flexible, added sudo support
[scpubgit/System-Introspector.git] / lib / System / Introspector / State.pm
index 3506a1c..2d423b1 100644 (file)
@@ -1,8 +1,5 @@
 package System::Introspector::State;
 use Moo;
-use Data::YAML::Writer;
-use Object::Remote;
-use Object::Remote::Future;
 use System::Introspector::Gatherer;
 
 use JSON::Diffable qw( encode_json );
@@ -13,25 +10,49 @@ has introspectors => (is => 'lazy');
 
 has host => (is => 'ro');
 
+has user => (is => 'ro');
+
+has sudo_user => (is => 'ro');
+
 has storage => (is => 'ro', required => 1);
 
 has node_path => (is => 'lazy');
 
 sub fetch {
     my ($self) = @_;
-    my $gatherer = $self->_create_gatherer;
-    my $spec     = $self->introspectors;
+    my $spec = $self->introspectors;
+    my (@sudo, @nosudo);
+    push(@{ $spec->{$_}{sudo} ? \@sudo : \@nosudo}, [$_, $spec->{$_}])
+        for sort keys %$spec;
     my %report;
-    for my $class_base (sort keys %$spec) {
+    if (@nosudo) {
+        my $gatherer = $self->_create_gatherer;
+        %report = %{ $self->_fetch_with_gatherer($gatherer, @nosudo) || {} };
+    }
+    if (@sudo) {
+        my $gatherer = $self->_create_gatherer(sudo => 1);
+        %report = (%report, %{ $self->_fetch_with_gatherer($gatherer, @sudo) || {} });
+    }
+    return \%report;
+}
+
+sub _fetch_with_gatherer {
+    my ($self, $gatherer, @spec) = @_;
+    my %report;
+    for my $class_spec (@spec) {
+        my ($class_base, $args) = @$class_spec;
+        print "Gathering $class_base data\n";
         $report{ $class_base } = $gatherer
-            ->gather($class_base, $spec->{ $class_base });
+            ->gather($class_base, $args);
     }
+    print "All gathered\n";
     return \%report;
 }
 
 sub fetch_and_store {
     my ($self) = @_;
-    return $self->_store($self->fetch);
+    my $data = $self->fetch;
+    return $self->_store($data);
 }
 
 sub _build_node_path {
@@ -81,11 +102,12 @@ sub _cleanup {
 }
 
 sub _create_gatherer {
-    my ($self) = @_;
-    if (defined( my $host = $self->host )) {
-        return System::Introspector::Gatherer->new::on($host);
-    }
-    return System::Introspector::Gatherer->new;
+    my ($self, %arg) = @_;
+    return System::Introspector::Gatherer->new_from_spec(
+        user        => $self->user,
+        host        => $self->host,
+        sudo_user   => $arg{sudo} && $self->sudo_user,
+    );
 }
 
 1;