update_wiki_eye.pl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #!/usr/bin/perl
  2. #
  3. # Синхронизация метаданных устройств в Wiki через API
  4. #
  5. # Запуск: perl /path/to/update_wiki_eye.pl
  6. #
  7. use utf8;
  8. use warnings;
  9. use Encode;
  10. use open qw(:std :encoding(UTF-8));
  11. no warnings 'utf8';
  12. use strict;
  13. use English;
  14. use lib "/opt/Eye/scripts";
  15. use FindBin '$Bin';
  16. use eyelib::config;
  17. use Data::Dumper;
  18. use File::Find;
  19. use File::Basename;
  20. use Fcntl qw(:flock);
  21. use LWP::UserAgent;
  22. use HTTP::Request;
  23. use JSON::XS;
  24. use URI::Escape;
  25. use Encode qw(decode_utf8 encode_utf8);
  26. # Блокировка для предотвращения параллельных запусков
  27. open(SELF, "<", $0) or die "Cannot open $0 - $!";
  28. flock(SELF, LOCK_EX | LOCK_NB) or exit 1;
  29. # Настройка API - аутентификация через параметры
  30. my $api_base = $config_ref{api_base} || 'http://localhost/api.php';
  31. my $api_key = $config_ref{api_key} || die "Ошибка: не настроен параметр api_key в конфигурации\n";
  32. my $api_login = $config_ref{api_login} || die "Ошибка: не настроен параметр api_login в конфигурации\n";
  33. # Базовые параметры аутентификации для всех запросов
  34. my $auth_params = "api_key=" . uri_escape($api_key) . "&api_login=" . uri_escape($api_login);
  35. # Инициализация HTTP-клиента
  36. my $ua = LWP::UserAgent->new(
  37. timeout => 30,
  38. agent => 'EyeWikiSync/1.0'
  39. );
  40. my $api_request_url = $api_base."?".$auth_params;
  41. my $option_filter = encode_json({ option_id => '61' });
  42. # === Получение пути к вики из таблицы config (id=61) ===
  43. my $api_request = $api_request_url."&get=table_record&table=config&filter=".uri_escape($option_filter);
  44. my $config_response = api_call($ua, 'GET', $api_request);
  45. if ($config_response->{error}) {
  46. die "Ошибка: не удалось получить путь к вики из таблицы config (id=61): " . $config_response->{error} . "\n";
  47. }
  48. my $wiki_path = $config_response->{data}->{value};
  49. if (!$wiki_path || !-d $wiki_path) {
  50. die "Ошибка: путь к вики не настроен или директория не существует: $wiki_path\n";
  51. }
  52. print "Путь к вики: $wiki_path\n\n";
  53. # Поиск подходящих файлов
  54. my %content;
  55. find(\&wanted, $wiki_path);
  56. my $processed = 0;
  57. my $errors = 0;
  58. foreach my $fname (sort keys %content) {
  59. print "Analyze $content{$fname}...";
  60. # Чтение файла
  61. open(my $fh, '<:encoding(UTF-8)', $content{$fname}) or do {
  62. warn "Не удалось открыть файл $content{$fname}: $!\n";
  63. $errors++;
  64. next;
  65. };
  66. my @lines = <$fh>;
  67. close($fh);
  68. chomp(@lines);
  69. # Извлечение IP из метаданных
  70. my $ip;
  71. foreach my $line (@lines) {
  72. if ($line =~ /\%META\:FIELD\{name="DeviceIP"/) {
  73. if ($line =~ /value="([0-9]{1,3}(?:\.[0-9]{1,3}){3})"/) {
  74. $ip = $1;
  75. last;
  76. }
  77. }
  78. }
  79. print "IP not found!\n" and next unless $ip && is_valid_ipv4($ip);
  80. print "$ip \n";
  81. # Получение записи из user_auth по IP через API
  82. my $auth_response = api_call($ua, 'GET', $api_request_url. "&get=user_auth&ip=" . uri_escape($ip));
  83. if ($auth_response->{error} || !$auth_response->{data}->{wikiname}) {
  84. next;
  85. }
  86. my $auth = $auth_response->{data};
  87. # Пропускаем шлюзы
  88. next if $auth->{wikiname} =~ /^Gateway/;
  89. print "Found: $auth->{ip} $auth->{mac} ";
  90. my ($device_name, $device_port);
  91. my $error_msg;
  92. # Определение типа устройства и получение родительских данных
  93. eval {
  94. if ($auth->{wikiname} =~ /^(Switch|Router)/) {
  95. # Для коммутаторов/маршрутизаторов: получаем данные через цепочку устройств
  96. my $device_response = api_call($ua, 'GET', $api_request_url. "&get=table_record&table=devices&filter=" . uri_escape(encode_json({ ip => $ip })));
  97. die "Unknown device" unless $device_response->{data};
  98. my $device = $device_response->{data};
  99. # Получаем аплинк-порт
  100. my $uplink_ports_response = api_call($ua, 'GET', $api_request_url . "&get=table_list&table=device_ports&filter=" . uri_escape(encode_json({ device_id => $device->{id}, uplink => 1 })));
  101. die "Unknown connection" unless $uplink_ports_response->{data} && ref($uplink_ports_response->{data}) eq 'ARRAY' && @{$uplink_ports_response->{data}} > 0;
  102. my $parent_connect = $uplink_ports_response->{data}->[0];
  103. # Получаем целевой порт
  104. my $parent_port_response = api_call($ua, 'GET', $api_request_url . "&get=table_record&table=device_ports&id=" . $parent_connect->{id});
  105. die "Unknown port connection" unless $parent_port_response->{data};
  106. my $parent_port = $parent_port_response->{data};
  107. # Получаем родительское устройство
  108. my $device_parent_response = api_call($ua, 'GET', $api_request_url . "&get=table_record&table=devices&id=" . $parent_port->{device_id});
  109. die "Unknown parent device" unless $device_parent_response->{data};
  110. my $device_parent = $device_parent_response->{data};
  111. # Получаем авторизацию родительского устройства
  112. my $auth_parent_response = api_call($ua, 'GET', $api_request_url . "&get=user_auth&ip=" . uri_escape($device_parent->{ip}));
  113. die "Unknown auth for device" unless $auth_parent_response->{data} && $auth_parent_response->{data}->{wikiname};
  114. my $auth_parent = $auth_parent_response->{data};
  115. $device_name = $auth_parent->{wikiname};
  116. $device_port = $parent_port->{port};
  117. }
  118. else {
  119. # Для других устройств: получаем данные через соединения
  120. my $conn_response = api_call($ua, 'GET', $api_request_url . "&get=table_list&table=connections&filter=" . uri_escape(encode_json({ auth_id => $auth->{id} })));
  121. die "Unknown connection" unless $conn_response->{data} && ref($conn_response->{data}) eq 'ARRAY' && @{$conn_response->{data}} > 0;
  122. my $conn = $conn_response->{data}->[0];
  123. # Получаем порт устройства
  124. my $device_port_rec_response = api_call($ua, 'GET', $api_request_url . "&get=table_record&table=device_ports&id=" . $conn->{port_id});
  125. die "Unknown device port" unless $device_port_rec_response->{data};
  126. my $device_port_rec = $device_port_rec_response->{data};
  127. # Получаем устройство
  128. my $device_response = api_call($ua, 'GET', $api_request_url . "&get=table_record&table=devices&id=" . $device_port_rec->{device_id});
  129. die "Unknown device" unless $device_response->{data} && $device_response->{data}->{user_id};
  130. my $device = $device_response->{data};
  131. # Получаем авторизацию устройства по user_id и IP
  132. my $device_auth_list_response = api_call($ua, 'GET', $api_request_url . "&get=table_list&table=user_auth&filter=" . uri_escape(encode_json({ user_id => $device->{user_id}, ip => $device->{ip} })));
  133. die "Unknown device auth" unless $device_auth_list_response->{data} && ref($device_auth_list_response->{data}) eq 'ARRAY' && @{$device_auth_list_response->{data}} > 0;
  134. my $device_auth = $device_auth_list_response->{data}->[0];
  135. die "Device auth has no wikiname" unless $device_auth->{wikiname};
  136. $device_name = $device_auth->{wikiname};
  137. $device_port = $device_port_rec->{port};
  138. }
  139. };
  140. if ($@) {
  141. $error_msg = $@;
  142. chomp($error_msg);
  143. print "Error: $error_msg\n";
  144. next;
  145. }
  146. # Подготовка обновленного содержимого файла
  147. my @wiki_dev;
  148. my %empty_fields = (parent => 1, parent_port => 1, mac => 1);
  149. foreach my $line (@lines) {
  150. if ($line =~ /\%META\:FIELD\{name="Parent"/) {
  151. $empty_fields{parent} = 0;
  152. if ($device_name) {
  153. push(@wiki_dev, '%META:FIELD{name="Parent" title="Parent" value="' . $device_name . '"}%');
  154. next;
  155. }
  156. }
  157. elsif ($line =~ /\%META\:FIELD\{name="ParentPort"/) {
  158. $empty_fields{parent_port} = 0;
  159. if ($device_port) {
  160. push(@wiki_dev, '%META:FIELD{name="ParentPort" title="Parent Port" value="' . $device_port . '"}%');
  161. next;
  162. }
  163. }
  164. elsif ($line =~ /\%META\:FIELD\{name="Mac"/) {
  165. $empty_fields{mac} = 0;
  166. if ($auth->{mac}) {
  167. push(@wiki_dev, '%META:FIELD{name="Mac" title="Mac" value="' . $auth->{mac} . '"}%');
  168. next;
  169. }
  170. }
  171. push(@wiki_dev, $line);
  172. }
  173. # Добавление отсутствующих полей
  174. if ($empty_fields{parent} && $device_name) {
  175. push(@wiki_dev, '%META:FIELD{name="Parent" title="Parent" value="' . $device_name . '"}%');
  176. }
  177. if ($empty_fields{parent_port} && $device_port) {
  178. push(@wiki_dev, '%META:FIELD{name="ParentPort" title="Parent Port" value="' . $device_port . '"}%');
  179. }
  180. if ($empty_fields{mac} && $auth->{mac}) {
  181. push(@wiki_dev, '%META:FIELD{name="Mac" title="Mac" value="' . $auth->{mac} . '"}%');
  182. }
  183. $device_name ||= 'None';
  184. $device_port ||= 'None';
  185. print "at $device_name $device_port\n";
  186. # Запись обновленного файла
  187. open(my $out_fh, '>:encoding(UTF-8)', $content{$fname}) or do {
  188. warn "Ошибка записи файла $content{$fname}: $!\n";
  189. $errors++;
  190. next;
  191. };
  192. print $out_fh $_ . "\n" for @wiki_dev;
  193. close($out_fh);
  194. $processed++;
  195. }
  196. print "\n=== ИТОГИ ===\n";
  197. print "Обработано файлов: $processed\n";
  198. print "Ошибок: $errors\n";
  199. print "Синхронизация завершена.\n";
  200. exit 0;
  201. sub api_call {
  202. my ($ua, $method, $url) = @_;
  203. my $req = HTTP::Request->new($method => $url);
  204. my $res = $ua->request($req);
  205. my $result = {};
  206. if (!$res->is_success) {
  207. $result->{error} = $res->status_line;
  208. return $result;
  209. }
  210. eval {
  211. $result->{data} = decode_json($res->decoded_content);
  212. };
  213. if ($@) {
  214. $result->{error} = "JSON parse error: $@";
  215. }
  216. return $result;
  217. }
  218. sub is_valid_ipv4 {
  219. my ($ip) = @_;
  220. return $ip =~ /^([0-9]{1,3}\.){3}[0-9]{1,3}$/ &&
  221. !grep { $_ > 255 } split(/\./, $ip);
  222. }
  223. sub wanted {
  224. my $filename = $File::Find::name;
  225. my $dev_name = basename($filename);
  226. if ($dev_name =~ /\.txt$/ && $dev_name =~ /^(Device|Switch|Ups|Sensor|Gateway|Router|Server|Bras)/) {
  227. $dev_name =~ s/\.txt$//;
  228. $content{$dev_name} = $filename;
  229. }
  230. return;
  231. }