123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294 |
- <?php
- //-
- // Copyright (c) 2011-2018 Joe Clarke <jclarke@cisco.com>
- // All rights reserved.
- // Redistribution and use in source and binary forms, with or without
- // modification, are permitted provided that the following conditions
- // are met:
- // 1. Redistributions of source code must retain the above copyright
- // notice, this list of conditions and the following disclaimer.
- // 2. Redistributions in binary form must reproduce the above copyright
- // notice, this list of conditions and the following disclaimer in the
- // documentation and/or other materials provided with the distribution.
- // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
- // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- // SUCH DAMAGE.
- include_once 'db.inc.php';
- include_once 'swreg/swreg.inc.php';
- include_once 'swreg_creds.inc.php';
- require_once 'Log.php';
- require_once 'functions.php';
- function error_to_exception($severity, $message, $file, $line)
- {
- if (!(error_reporting() & $severity)) {
- return;
- }
- throw new ErrorException($message, 0, $severity, $file, $line);
- }
- set_error_handler('error_to_exception');
- $dsn = "$db_driver:host=$db_host;dbname=$db_name";
- $options = [
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
- PDO::ATTR_EMULATE_PREPARES => false,
- ];
- try {
- $dbh = new PDO($dsn, $db_user, $db_pass, $options);
- } catch (PDOException $e) {
- die($e->getMessage() . "\n");
- }
- $logger = Log::singleton('file', LOGFILE, TOOL_NAME.' : Exporter');
- if ($logger === false) {
- die("Failed to open logfile.\n");
- }
- $mask = Log::UPTO(LOG_LEVEL);
- $logger->setMask($mask);
- $is_script = false;
- if (isset($argv) && $argv !== null) {
- $is_script = true;
- $options = getopt('t:f');
- if (!isset($options['t'])) {
- echo "usage: {$argv[0]} -t <TIME> [-f]\n";
- exit(1);
- }
- $sql = "SELECT value FROM SYS_PROPERTIES WHERE name='last_logic_update'";
- try {
- $res = $dbh->query($sql);
- } catch (PDOException $e) {
- echo "ERROR: Failed to get last update time: '{$e->getMessage()}'\n";
- exit(1);
- }
- $now = time();
- $row = $res->fetch();
- if ($now - $row['value'] >= ($options['t'] * 60)) {
- if (!isset($options['f'])) {
- // Logic data was not updated recently enough.
- exit(0);
- } else {
- echo "Logic data was not updated recently enough, but forcing run anyway.\n";
- }
- }
- }
- $sql = "SELECT * FROM DEVICE_MAP WHERE checked_out='1' AND (device_status='1' OR device_status='2') ORDER BY LPAD(lower(assigned_switch), 10, 0)";
- $res = null;
- try {
- $res = $dbh->query($sql);
- } catch (PDOException $e) {
- $msg = "Error querying for physical switches: {$e->getMessage()}";
- if ($is_script) {
- echo $msg."\n";
- } else {
- echo "<p><font color=\"red\">{$msg}</font></p>\r\n";
- }
- exit(1);
- }
- // Map from defined constant to variable.
- $GIT_HOME = GIT_HOME;
- $YAML_FILE = "{$GIT_HOME}/network/ansible/vars/targets.yml";
- exec("cd $GIT_HOME && GIT_SSH_COMMAND='ssh -i $GIT_HOME/../../.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' /usr/local/bin/git pull", $output, $result);
- if ($result != 0) {
- if (!$is_script) {
- echo "<p><font color=\"red\">Error updating git repo:</p>\r\n";
- echo "<pre>\r\n";
- } else {
- echo "Error updating git repo:\n";
- }
- foreach ($output as $line) {
- echo "$line";
- if ($is_script) {
- echo "\n";
- } else {
- echo "\r\n";
- }
- }
- if (!$is_script) {
- echo "</pre></font>\r\n";
- }
- exit(1);
- }
- try {
- $targets = yaml_parse_file($YAML_FILE);
- } catch (Exception $e) {
- $msg = "Error parsing YAML file: '{$e->getMessage()}'";
- if ($is_script) {
- echo $msg."\n";
- } else {
- echo "<p><font color=\"red\">{$msg}</font></p>\r\n";
- }
- exit(1);
- }
- $infra = $targets['targets']['infra'];
- $new_infra = [];
- foreach ($infra as $target) {
- if (!preg_match('/^sw-[0-9]+/', $target['name'])) {
- array_push($new_infra, $target);
- continue;
- }
- }
- while ($row = $res->fetch()) {
- $target = [];
- $target['name'] = $row['assigned_switch'];
- $sql = 'SELECT ip_address, location FROM SWITCHES WHERE name = :name';
- $sw_res = null;
- try {
- $sw_res = $dbh->prepare($sql);
- $sw_res->execute(['name' => $row['assigned_switch']]);
- } catch (PDOException $e) {
- $msg = "Error querying for IP address for {$row['assigned_switch']}: {$e->getMessage()}";
- if ($is_script) {
- echo $msg."\n";
- } else {
- echo "<p><font color=\"red\">{$msg}</font></p>\r\n";
- }
- continue;
- }
- $sw_row = $sw_res->fetch();
- if ($sw_row['location'] === null || $sw_row['location'] == '') {
- continue;
- }
- $target['ipv4'] = $sw_row['ip_address'];
- $target['location'] = $sw_row['location'];
- $target['platform'] = 'ietfcisco';
- $target['deployed'] = 'True';
- array_push($new_infra, $target);
- }
- $targets['targets']['infra'] = $new_infra;
- try {
- $yaml = yaml_emit($targets, YAML_UTF8_ENCODING, YAML_LN_BREAK);
- $yaml = preg_replace('/^---/', '', $yaml);
- } catch (Exception $e) {
- $msg = "Failed to generate YAML: '{$e->getMessage()}'";
- if ($is_script) {
- echo $msg."\n";
- } else {
- echo "<p><font color=\"red\">{$msg}</font></p>";
- }
- exit(1);
- }
- try {
- $fd = fopen($YAML_FILE, 'w');
- $header = <<<'HEADER'
- ---
- # Targets for Smokeping and Deadman
- # Target format:
- # name: Display name of the target
- # hostname: Hostname of the target
- # ipv4: IPv4 address
- # ipv6: IPv6 address
- # deployed (optional): If False, then the target will not be added (default:
- # True)
- # location (optional): Location where element is deployed
- #
- #
- # If the target doesn't have a v4 or v6, then the target will be looked
- # up by hostname and one v4 and one v6 address will be added to the config.
- ###
- HEADER;
- fwrite($fd, $header);
- fwrite($fd, $yaml);
- fclose($fd);
- } catch (Exception $e) {
- $msg = "Failed to write data to file: '{$e->getMessage()}";
- if ($is_script) {
- echo $msg."\n";
- } else {
- echo "<p><font color=\"red\">{$msg}</font></p>";
- }
- exit(1);
- }
- exec("cd $GIT_HOME && GIT_SSH_COMMAND='ssh -i $GIT_HOME/../../.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' /usr/local/bin/git commit -m 'Update switch targets from ZTP' $YAML_FILE", $output, $result);
- if ($result != 0) {
- if ($output[0] != "Your branch is up to date" && $output[0] != "Already up to date.") {
- if (!$is_script) {
- echo "<p><font color=\"red\">Error committing changes to git:</p>\r\n";
- echo "<pre>\r\n";
- } else {
- echo "Error committing changes to git:\n";
- }
- foreach ($output as $line) {
- echo "$line";
- if ($is_script) {
- echo "\n";
- } else {
- echo "\r\n";
- }
- }
- if (!$is_script) {
- echo "</pre></font>\r\n";
- }
- exit(1);
- } else {
- if ($is_script) {
- exit(0);
- } else {
- echo "<script>window.close();</script>";
- }
- }
- }
- exec("cd $GIT_HOME && GIT_SSH_COMMAND='ssh -i $GIT_HOME/../../.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' /usr/local/bin/git push", $output, $result);
- if ($result != 0) {
- if (!$is_script) {
- echo "<p><font color=\"red\">Error pushing changes to git:</p>\r\n";
- echo "<pre>\r\n";
- } else {
- echo "Error pushing changes to git:\n";
- }
- foreach ($output as $line) {
- echo "$line";
- if ($is_script) {
- echo "\n";
- } else {
- echo "\r\n";
- }
- }
- if (!$is_script) {
- echo "</pre></font>\r\n";
- }
- exit(1);
- }
- touch('/tmp/deadman_change.dat');
- if ($is_script) {
- exit(0);
- }
- ?>
- <script>
- window.close();
- </script>
|