forked from mikeda/ZabbixAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZabbixAPI.pm
134 lines (105 loc) · 2.3 KB
/
ZabbixAPI.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package ZabbixAPI;
use strict;
use warnings;
use JSON;
use LWP::UserAgent;
use Data::Dumper;
our $VERSION = "0.01";
our $DEBUG = 0;
sub new {
my ($class, $url, $id) = @_;
$id ||= 1;
if($url !~ /\/api_jsonrpc\.php$/){
if($url !~ /\/$/){
$url .= '/';
}
$url .= 'api_jsonrpc.php';
}
my $json = JSON->new->utf8;
$DEBUG && $json->pretty;
my $self = {
url => $url,
id => $id,
auth => undef,
json => $json
};
return bless $self, $class;
}
sub DESTROY {};
sub AUTOLOAD{
my $self = shift;
my $method = our $AUTOLOAD;
$method =~ s/.*:://;
if($method =~ tr/_/./ == 1){
$self->_call_api($method, @_);
}else{
die "bad method:$AUTOLOAD";
}
}
sub _call_api {
my $self = shift;
my ($method, $params, $keyname, $valname) = @_;
$params ||= {};
# create JSON request
my $json_req = $self->{json}->encode(
{
method => $method,
auth => $self->{auth},
id => $self->{id},
jsonrpc => '2.0',
params => $params
}
);
$DEBUG && _dprint("Request:\n" . $json_req);
# POST HTTP request
my $ua = LWP::UserAgent->new;
my $http_res = $ua->post(
$self->{url},
'Content-Type' => "application/json-rpc",
'User-Agent' => "ZabbixAPI/mikeda v$VERSION",
'Content' => $json_req
);
if($http_res->is_error){
die "HTTP Error\n" . $http_res->status_line;
}
my $json_res = $http_res->content;
$DEBUG && _dprint("Response:\n" . $json_res);
# decode JSON response
my $api_res = $self->{json}->decode($json_res);
if($api_res->{error}){
die "API Error\n" . Dumper($api_res->{error});
}
my $res = $api_res->{result};
# modify result
if(defined($keyname)){
if(defined($valname)){
# return hash
my %h;
$h{$_->{$keyname}} = $_->{$valname} for @$res;
$res = \%h;
}else{
# return array
$res = [map {$_->{$keyname}} @$res];
}
}
return $res;
}
sub _dprint {
my ($pkg, $file, $line) = caller 0;
my $msg = shift;
print STDERR "# $file:$line\n";
for my $m (split "\n", $msg){
print STDERR "# $m\n";
}
print STDERR "\n";
}
sub login {
my $self = shift;
my ($user, $password) = @_;
my %params = (
user => $user,
password => $password
);
$self->{auth} = $self->_call_api('user.login', \%params);
}
1;