فهرست منبع

Merged in FD3-751 (pull request #37)

FD3-751 update comando para actualizar cablemodem desde dhcp

Approved-by: Maximiliano Schvindt <maximiliano@interlink.com.ar>
Guillermo Espinoza 6 سال پیش
والد
کامیت
53978014b5

+ 2 - 2
app/DoctrineMigrations/src/action.yml

@@ -6,7 +6,7 @@ insertorupdate:
           workflow_name: "dhcp_workflow"
           event: "a:1:{i:0;s:5:\"enter\";}"
           event_reference: "active"
-          template: "echo \"Config KEA\"\r\nphp /opt/dhcp/bin/console kea:config --set=1"
+          template: "echo \"Config KEA\"\r\nphp /opt/dhcp/bin/console kea:config --set"
           tenancy_id: 1
         -
           id: 2
@@ -34,5 +34,5 @@ insertorupdate:
           name: "Update fixed address Cablemodem"
           object_class: "HostBundle\\Entity\\Host"
           event: "a:1:{i:0;s:9:\"preUpdate\";}"
-          template: "echo \"Actualizando Cablemodem\"\r\n\r\nphp bin/console cablemodem:update --id={{object.id}}"
+          template: "echo \"Actualizando Cablemodem\"\r\n\r\nphp /opt/dhcp/bin/console cablemodem:update --id={{object.id}}"
           tenancy_id: 1  

+ 3 - 3
composer.lock

@@ -1647,7 +1647,7 @@
             "source": {
                 "type": "git",
                 "url": "ssh://git@200.50.168.30:222/VendorSoftwareFlowdat3/WorkflowBundle.git",
-                "reference": "13431443af6cd4038230a15e05f593363a642ad1"
+                "reference": "8919bf2fec49fa73cd31b07a83a542bbd0767136"
             },
             "require": {
                 "php-amqplib/rabbitmq-bundle": "^1.12"
@@ -1677,7 +1677,7 @@
                 "bundle",
                 "workflow"
             ],
-            "time": "2018-11-22T18:10:58+00:00"
+            "time": "2018-11-23T13:16:02+00:00"
         },
         {
             "name": "incenteev/composer-parameter-handler",
@@ -6283,7 +6283,7 @@
         "voryx/restgeneratorbundle": 20
     },
     "prefer-stable": false,
-    "prefer-lowest": false,
+    "prefer-lowest": true,
     "platform": {
         "php": ">=5.5.9"
     },

+ 1 - 0
src/HostBundle/Admin/HostAdmin.php

@@ -181,6 +181,7 @@ class HostAdmin extends BaseAdmin
         if (!$object->getFixedAddress() && $object->getFixedIP() == true) {
             $object->setFixedIP(false);
         }
+        $object->setOptions(json_encode($object->getDHCPOption()));
     
         return parent::preUpdate($object);
     }

+ 2 - 2
src/HostBundle/Command/CablemodemUpdateCommand.php

@@ -114,7 +114,7 @@ EOT
         // Consulto en Cablemodem
         $cablemodem = null;
         $url = $ws->buildUrl($urlGET, compact('mac'));
-        $cablemodemJSON = $ws->makeGetRequest($url, HttpRequestInterface::METHOD_GET, [], $this->credentials);
+        $cablemodemJSON = $ws->makeGetRequest($url);
         if ($cablemodemJSON) {
             $cablemodem = current(json_decode($cablemodemJSON, true));
         }
@@ -150,7 +150,7 @@ EOT
                 break;
         }
         
-        $cablemodemJSON = $ws->makeGetRequest($urlPUT, HttpRequestInterface::METHOD_PUT, $data, $this->credentials);
+        $cablemodemJSON = $ws->makeGetRequest($urlPUT, HttpRequestInterface::METHOD_PUT, $data);
         if ($cablemodemJSON) {
             $cablemodem = current(json_decode($cablemodemJSON, true));
         }

+ 79 - 57
src/HostBundle/EventListener/KEAHostReservationSubscriber.php

@@ -66,68 +66,90 @@ class KEAHostReservationSubscriber implements EventSubscriber
      */
     public function execute(LifecycleEventArgs $args, $remove = false)
     {
-        $entity = $args->getEntity();
-        if ($entity instanceof Host) {
-            $query = "SELECT COUNT(*) AS `exists`
-                    FROM information_schema.tables 
-                    WHERE table_schema = 'kea' 
-                    AND table_name = 'hosts';";
-            
-            $databaseConnection = $this->serviceContainer->get('database_connection');
-            $stmt = $databaseConnection->prepare($query);
-            $stmt->execute();
-            $tableExists = $stmt->fetchAll();
-            if (!isset($tableExists[0]['exists']) || $tableExists[0]['exists'] == '0') {
-                return;
-            }
-            
-            if ($entity->getFixedAddress() && $remove == false) {
-                $query = "
-                INSERT INTO kea.hosts (dhcp_identifier,
-                dhcp_identifier_type,
-                ipv4_address, 
-                hostname)
-                VALUES (:mac,
-                (SELECT type FROM kea.host_identifier_type WHERE name=:type),
-                INET_ATON(:ip),
-                :hostname);
-                ";
-            } else {
-                $query = "
-                DELETE FROM kea.hosts
-                WHERE dhcp_identifier = :mac;
-                ";
-            }
-            
-            $databaseConnection = $this->serviceContainer->get('database_connection');
-            $stmt = $databaseConnection->prepare($query);
-            $hostType = $entity->getHostType();
-            $shortname = $hostType->getShortname();
-            // calculo el campo dhcp_identifier_type de kea.hosts
-            if ($shortname == 'cablemodem' || $shortname == 'cm') {
-                $stmt->bindValue("mac", hex2bin(str_replace(':', '', $entity->getMac())));
-            } else {
-                // mta|cpe
-                $hex = '';
-                $prefix = $shortname . '-';
-                for ($i = 0; $i < strlen($prefix); $i++) {
-                    $ord = ord($prefix[$i]);
-                    $hexCode = dechex($ord);
-                    $hex .= substr('0'.$hexCode, -2);
+        try {
+            $entity = $args->getEntity();
+            if ($entity instanceof Host) {
+                $query = "SELECT COUNT(*) AS `exists`
+                FROM information_schema.tables 
+                WHERE table_schema = 'kea' 
+                AND table_name = 'hosts';";
+                
+                $databaseConnection = $this->serviceContainer->get('database_connection');
+                $stmt = $databaseConnection->prepare($query);
+                $stmt->execute();
+                $tableExists = $stmt->fetchAll();
+                if (!isset($tableExists[0]['exists']) || $tableExists[0]['exists'] == '0') {
+                    return;
                 }
-                $stmt->bindValue("mac", hex2bin($hex . str_replace(':', '', $entity->getHost()->getMac())));
-            }
-            if ($entity->getFixedAddress() && $remove == false) {
+                
+                if ($entity->getFixedAddress() && $remove == false) {
+                    $query = "
+                    DELETE FROM kea.hosts
+                    WHERE dhcp_identifier = :mac
+                    ;
+                    INSERT INTO kea.hosts (dhcp_identifier,
+                    dhcp_identifier_type,
+                    dhcp4_subnet_id,
+                    ipv4_address, 
+                    hostname)
+                    VALUES (:mac,
+                    (SELECT type FROM kea.host_identifier_type WHERE name=:type),
+                    :dhcp4_subnet_id,
+                    INET_ATON(:ip),
+                    :hostname)
+                    ON DUPLICATE KEY UPDATE
+                    dhcp_identifier_type=(SELECT type FROM kea.host_identifier_type WHERE name=:type),
+                    dhcp4_subnet_id=:dhcp4_subnet_id, ipv4_address=INET_ATON(:ip),
+                    hostname=:hostname
+                    ;
+                    ";
+                } else {
+                    $query = "
+                    DELETE FROM kea.hosts
+                    WHERE dhcp_identifier = :mac;
+                    ";
+                }
+                
+                $databaseConnection = $this->serviceContainer->get('database_connection');
+                $stmt = $databaseConnection->prepare($query);
+                $hostType = $entity->getHostType();
+                $shortname = $hostType->getShortname();
+                // calculo el campo dhcp_identifier_type de kea.hosts
                 if ($shortname == 'cablemodem' || $shortname == 'cm') {
-                    $stmt->bindValue("type", 'hw-address');
+                    $stmt->bindValue("mac", hex2bin(str_replace(':', '', $entity->getMac())));
                 } else {
-                    $stmt->bindValue("type", 'flex-id');
+                    // mta|cpe
+                    $hex = '';
+                    $prefix = $shortname . '-';
+                    for ($i = 0; $i < strlen($prefix); $i++) {
+                        $ord = ord($prefix[$i]);
+                        $hexCode = dechex($ord);
+                        $hex .= substr('0'.$hexCode, -2);
+                    }
+                    $stmt->bindValue("mac", hex2bin($hex . str_replace(':', '', $entity->getHost()->getMac())));
+                }
+                if ($entity->getFixedAddress() && $remove == false) {
+                    if ($shortname == 'cablemodem' || $shortname == 'cm') {
+                        $stmt->bindValue("type", 'hw-address');
+                    } else {
+                        $stmt->bindValue("type", 'flex-id');
+                    }
+                    $stmt->bindValue("hostname", $entity->getHostName());
+                    $stmt->bindValue("ip", $entity->getFixedAddress());
+                    
+                    // calculo el valor de la subnet según la config de KEA
+                    $subnet = $this->serviceContainer->get('dhcp.host_service')->getSubnet($entity->getFixedAddress());
+                    $stmt->bindValue("dhcp4_subnet_id", $this->serviceContainer->get('kea.config')->getSubnetInConfig($subnet));
                 }
-                $stmt->bindValue("hostname", $entity->getHostName());
-                $stmt->bindValue("ip", $entity->getFixedAddress());
+                $stmt->execute();
             }
-            $stmt->execute();
-        }
+        } catch (\Exception $ex) {
+            $flashbag = $this->serviceContainer->get('session')->getFlashBag();
+            $flashbag->add("error", $ex->getMessage());
+        } catch (\Throwable $ex) {
+            $flashbag = $this->serviceContainer->get('session')->getFlashBag();
+            $flashbag->add("error", $ex->getMessage());
+        }    
     }
 
 }

+ 16 - 0
src/HostBundle/Services/HostService.php

@@ -92,4 +92,20 @@ class HostService
         
         return $hostsFixedIP;
     }
+    
+    /**
+     * @param string $fixedIP
+     *
+     * @return int
+     */
+    public function getSubnet($fixedIP)
+    {
+        $pool = $this->poolService->getPoolFromFixedIP($fixedIP);
+        if ($pool) {
+            return $pool->getSubnet() ? $pool->getSubnet() : null;
+        }
+        
+        return null;
+    }
+    
 }

+ 1 - 1
src/HostBundle/Traits/DHCPOptionTrait.php

@@ -227,4 +227,4 @@ trait DHCPOptionTrait
         return @$this->json_dhcp_option_config['fixed_address'];
     }
 
-}
+}

+ 24 - 0
src/IPv4Bundle/Services/PoolService.php

@@ -48,6 +48,30 @@ class PoolService
         return null;
     }
     
+    
+    /**
+     * Retorna el primer pool donde se encuentra la $fixedIP
+     *
+     * @param string $fixedIP
+     *
+     * @return Pool
+     */
+    public function getPoolFromFixedIP($fixedIP)
+    {
+        $address = ip2long($fixedIP);
+        $pools = $this->poolRepository->findAll();
+        foreach ($pools as $pool) {
+            $firstIp = ip2long($pool->getFirstIp());
+            $lastIp =  ip2long($pool->getLastIp());
+            
+            if ($firstIp <= $address && $address <= $lastIp) {
+                return $pool;
+            }
+        }
+        
+        return null;
+    }
+    
     /**
      * @param HostType $hostType
      *

+ 16 - 7
src/KeaBundle/Command/KeaConfigCommand.php

@@ -19,7 +19,7 @@ class KeaConfigCommand extends ContainerAwareCommand
             ->addOption('class', null, InputOption::VALUE_OPTIONAL, 'Kea Class Config in KeaBundle\Services. e.g. BaseKea', 'BaseKea')
             ->addOption('id', null, InputOption::VALUE_OPTIONAL, 'DHCP Entity ID. e.g.: 1', 1)
             ->addOption('library', null, InputOption::VALUE_OPTIONAL, 'Hook library path', '/kea-cm-hook/kea-hook-flowdat.so')
-            ->addOption('set', null, InputOption::VALUE_REQUIRED, 'Send Config DHCP4 to KEA', 0)
+            ->addOption('set', null, InputOption::VALUE_NONE, 'Send Config DHCP4 to KEA')
             ;
     }
 
@@ -29,18 +29,27 @@ class KeaConfigCommand extends ContainerAwareCommand
      */
     protected function execute(InputInterface $input, OutputInterface $output)
     {
-        $setConfig = (int) $input->getOption('set');
-
         $this->output = $output;
         $class = $input->getOption('class');
         $id = $input->getOption('id');
         $library = $input->getOption('library');
         $keaConfigService = $this->getContainer()->get('kea.config');
 
-        if($setConfig) {
-            $config = $keaConfigService->getConfig($id, $class, $library);
-            $dhcp = $this->getContainer()->get("doctrine.orm.entity_manager")->getRepository("DHCPBundle\Entity\DHCP")->findOneById($id);
-            $output->writeln($keaConfigService->setConfig($dhcp, $config));
+        $setConfig = (int) $input->getOption('set');
+        if ($setConfig) {
+            $dhcpRepository = $this->getContainer()->get("doctrine.orm.entity_manager")->getRepository("DHCPBundle\Entity\DHCP");
+            $dhcp = $dhcpRepository->findOneById($id);
+            // selecciono el primer KEA DHCP que se encuentre 
+            if (!$dhcp) {
+                $dhcpAll = $dhcpRepository->findAll();
+                $dhcp = count($dhcpAll) ? current($dhcpAll) : null;
+            }
+            if ($dhcp) {
+                $config = $keaConfigService->getConfig($id, $class, $library);
+                $output->writeln($keaConfigService->setConfig($dhcp, $config));
+            } else {
+                $output->writeln("KEA DHCP id:{$id} <error>not found!</error>");
+            }
         } else {
             $output->writeln($keaConfigService->getConfig($id, $class, $library));
         }

+ 25 - 0
src/KeaBundle/Services/KeaConfigService.php

@@ -233,5 +233,30 @@ class KeaConfigService
 
         return $return;
     }
+    
+    /**
+     * @param SubNet $subnet
+     *
+     * @return int
+     */
+    public function getSubnetInConfig($subnet)
+    {
+        $position = 1;
+        if ($subnet) {
+            // se usan valores por defecto
+            $config = $this->getConfig(1, 'BaseKea', '/kea-cm-hook/kea-hook-flowdat.so');
+            $configDecode = json_decode($config, true);
+            if (isset($configDecode[0]['arguments']['Dhcp4']['subnet4'])) {
+                foreach ($configDecode[0]['arguments']['Dhcp4']['subnet4'] as $subnetConfig) {
+                    if ($subnetConfig['subnet'] == $subnet->getAddress()) {
+                        break;
+                    }
+                    $position++;
+                }
+            }
+        }
+        
+        return $position;
+    }
 
 }