Skip to content

Instantly share code, notes, and snippets.

@toritori0318
Created December 13, 2012 06:42
Show Gist options
  • Select an option

  • Save toritori0318/4274566 to your computer and use it in GitHub Desktop.

Select an option

Save toritori0318/4274566 to your computer and use it in GitHub Desktop.
growthforecastのグラフを削除するCLI
use strict;
use Web::Scraper;
use URI;
use LWP::UserAgent;
use YAML::Tiny;
use Data::Dumper;
use Getopt::Long;
my @graph_list;
my $host = 'localhost:5009';
my $service = '';
my $section = '';
my $dry_run;
GetOptions('host=s' => \$host, 'service=s' => \$service, 'section=s' => \$section, 'dry-run' => \$dry_run);
die '--service or --section is require.' if !$service && !$section;
sub scrape_links {
my $url = "http://$host/";
my $scraper = scraper {
process '//table[@class="zebra-striped"]/tr/td/a', 'link[]' => '@href';
};
my $result = $scraper->scrape(URI->new($url));
my @paths;
for my $uri (@{$result->{link}}) {
my $path = $uri->path;
if($path =~ m|^/list/([^/]+)/([^/]+)|) {
if((!$service || ($service && $service eq $1))
&& (!$section || ($section && $section eq $2)) ) {
push @paths, {
service_name => $1,
section_name => $2,
};
}
}
}
#print Dumper \@paths;
return @paths;
}
sub scrape_graph_list {
my $url = "http://$host/add_complex?service_name=hoge";
my $scraper = scraper {
process '//select[@name="path-1"]/option', 'items[]' => scraper {
process '//*', 'key' => 'TEXT';
process '//*', 'value' => '@value';
};
};
my $result = $scraper->scrape(URI->new($url));
return @{$result->{items}};
}
sub filter_graph_list {
my ($path) = @_;
my @hit = ();
for my $row (@graph_list) {
my ($dummy, $service, $section, $graph) = split /\//, $row->{key};
if($service eq $path->{service_name} && $section eq $path->{section_name}) {
push @hit, $row;
}
}
return @hit;
}
sub request_delete_graph {
my ($path, $graph_list) = @_;
for my $graph (@$graph_list) {
post($graph->{key});
}
}
sub post {
my ($graph_path) = @_;
my $ua = LWP::UserAgent->new;
$ua->timeout(3);
my $response = $ua->post("http://$host/delete". $graph_path);
if ($response->is_success) {
print $response->decoded_content; # or whatever
} else {
die $response->status_line;
}
}
sub main {
# grawthforecastのURL一覧を取得
my @paths = scrape_links();
die 'Not found paths.' if scalar @paths == 0;
# 設定されているメトリクス一覧を取得
@graph_list = scrape_graph_list();
die 'Not found graphlist.' if scalar @graph_list == 0;
for my $path (@paths) {
my @matches_graph_list = filter_graph_list($path);
next if scalar @matches_graph_list <= 1;
# グラフ削除URLへリクエスト
request_delete_graph($path, \@matches_graph_list);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment