Browse Source

Merged in FD3-754 (pull request #40)

FD3-754
Guillermo Espinoza 6 years ago
parent
commit
f33460788f

+ 1 - 0
.gitignore

@@ -15,6 +15,7 @@
 !var/SymfonyRequirements.php
 /vendor/
 /web/bundles/
+/web/kea/
 /app/Resources/workflows/workflow_list.yml
 /app/config/bundles/hwi/oauth-bundle/parameters.yml
 /app/config/bundles/ik/audit-bundle/parameters.yml

+ 11 - 1
app/DoctrineMigrations/src/action.yml

@@ -2,8 +2,9 @@ insertorupdate:
     action:
         -
           id: 1
-          name: "Configuración KEA"
+          name: "KEA Config Subnet"
           workflow_name: "dhcp_workflow"
+          object_class: "IPv4Bundle\\Entity\\SubNet"
           event: "a:1:{i:0;s:5:\"enter\";}"
           event_reference: "active"
           template: "echo \"Config KEA\"\r\nphp /opt/dhcp/bin/console kea:config --set"
@@ -35,4 +36,13 @@ insertorupdate:
           object_class: "HostBundle\\Entity\\Host"
           event: "a:1:{i:0;s:9:\"preUpdate\";}"
           template: "echo \"Actualizando Cablemodem\"\r\n\r\nphp /opt/dhcp/bin/console cablemodem:update --id={{object.id}}"
+          tenancy_id: 1
+        -
+          id: 6
+          name: "KEA Config Pool"
+          workflow_name: "dhcp_workflow"
+          object_class: "IPv4Bundle\\Entity\\Pool"
+          event: "a:1:{i:0;s:5:\"enter\";}"
+          event_reference: "active"
+          template: "echo \"Config KEA\"\r\nphp /opt/dhcp/bin/console kea:config --set"
           tenancy_id: 1  

+ 10 - 9
src/HostBundle/EventListener/AdminDHCPOption.php

@@ -13,13 +13,13 @@ use Symfony\Component\Form\FormEvents;
 
 class AdminDHCPOption
 {
-    
+
     /**
      * @var HostService
      */
     private $hostService;
-    
-    
+
+
     /**
      * @param HostService $hostService
      */
@@ -41,6 +41,7 @@ class AdminDHCPOption
             }
             $options = array(
                 'translation_domain' => 'HostBundle',
+                'class' => 'dhcp-option-tab',
             );
             $mapper->tab('DHCP Option', $options)
                 ->with('DHCP Option', $options);
@@ -48,9 +49,9 @@ class AdminDHCPOption
                 'required' => false,
             ];
             foreach (DHCPOptions::getConstants() as $opt) {
-                
+
                 if ($opt == 'fixed_address') {
-                    $hostType = method_exists($subject, 'getHostType') 
+                    $hostType = method_exists($subject, 'getHostType')
                                 ? $subject->getHostType() : null;
                     $freeIP = $this->hostService->getFreeFixedIP($hostType);
                     $fixedAddress = $subject->getFixedAddress();
@@ -62,19 +63,19 @@ class AdminDHCPOption
                     $fieldOptions['choice_translation_domain'] = false;
                     $mapper->add($opt, ChoiceType::class, $fieldOptions);
                     unset($fieldOptions['choices'], $fieldOptions['choice_translation_domain']);
-                    
+
                     continue;
                 }
-                
+
                 $mapper->add($opt, TextType::class, $fieldOptions);
             }
             $mapper->end()->end();
-            
+
             // fix seteo de fixed IP al editar el tipo de Host
             $mapper->getFormBuilder()->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
                 $data = $event->getData();
                 $form = $event->getForm();
-                
+
                 if (isset($data['fixed_address'])) {
                     $form->add('fixed_address', null, [
                         'data' => $data['fixed_address'],

+ 25 - 14
src/HostBundle/Resources/views/CRUD/edit.html.twig

@@ -1,5 +1,13 @@
 {% extends "@SonataAdmin/CRUD/edit.html.twig" %}
 
+{% block stylesheets %}
+
+{{ parent() }}
+
+{% include "HostBundle::dhcp_options_style.html.twig" %}
+
+{% endblock stylesheets %}
+
 {% block javascripts %}
 
 {{ parent() }}
@@ -13,15 +21,15 @@ $(document).ready(function() {
     {% if object.getFixedAddress() is not null or object.getFixedAddress() != "" %}
         $fixedIP = "{{object.getFixedAddress()}}";
     {% endif %}
-    
+
     {% if object.getHostType() is not null %}
         $initHostTypeId = {{object.getHostType().getId()}};
     {% endif %}
-    
+
     showHostField();
 
     $("select[id$='hostType']").on('change', showHostField);
-    
+
 });
 
 // Al seleccionar tipo Cablemodem oculto el campo Host
@@ -32,24 +40,27 @@ function showHostField()
     var $hostTypeField = $("select[id$='hostType'] :selected");
     var $hostField = $("div.form-group[id$='host']");
     var $hostSelect = $("select[id$='host']");
-    
+
     if ($hostTypeField.html() === 'Cablemodem') {
         if ($hostSelect.find("option[value='']").length == 0) {
             $hostSelect.prepend('<option value=""></option>');
         }
         $hostSelect.val(null).trigger('change');
-        
+
         $hostField.hide();
     } else {
-        if ($hostSelect.find("option[value='']").length) {
+        var val = $hostSelect.val();
+        if (val == '' && $hostSelect.find("option[value='']").length) {
             $hostSelect.find("option[value='']").remove();
         }
-        var val = $hostSelect.find("option").first().attr('value');
-        $hostSelect.val(val).trigger('change');
-        
+        if (val == '') {
+            val = $hostSelect.find("option").first().attr('value');
+            $hostSelect.val(val).trigger('change');
+        }
+
         $hostField.show();
     }
-    
+
     updateFixedIPs();
 
     return false;
@@ -59,9 +70,9 @@ function updateFixedIPs()
 {
     var $hostTypeField = $("select[id$='hostType'] :selected");
     var $hostTypeId = $hostTypeField.val();
-    
+
     var option = '<option value=""></option>';
-    
+
     if (($hostTypeId == $initHostTypeId) && $fixedIP != false) {
         option = `<option value="${$fixedIP}" selected>${$fixedIP}</option>`;
         $("div[id$='_fixed_address'] a span.select2-chosen").html($fixedIP);
@@ -74,14 +85,14 @@ function updateFixedIPs()
         type: 'POST',
         data: {id: $hostTypeId},
         success: function(data) {
-            
+
             $('select[id$="_fixed_address"]').html(option);
             if (data.ips) {
                 $.each(data.ips, function (index, value) {
                     $('select[id$="_fixed_address"]').append('<option value="' + value + '">' + value + '</option>');
                 });
             }
-            
+
             return false;
         }
     });

+ 7 - 0
src/HostBundle/Resources/views/dhcp_options_style.html.twig

@@ -0,0 +1,7 @@
+<style>
+.dhcp-option-tab .form-group {
+    width: 48%;
+    float: left;
+    margin-right: 15px;
+}
+</style>

+ 7 - 2
src/IPv4Bundle/Admin/NetGroupAdmin.php

@@ -29,6 +29,9 @@ class NetGroupAdmin extends BaseAdmin
         $listMapper
             ->add('name')
             ->add('opcode')
+            ->add('relayString', null, [
+                'label' => 'list.label_relay',
+            ])
             ->add('_action', null, array(
                 'actions' => array(
                     'show' => array(),
@@ -48,7 +51,7 @@ class NetGroupAdmin extends BaseAdmin
             ->add('name')
             ->add('opcode')
             ->add('relay', 'collection', [
-                'allow_add' => true, 
+                'allow_add' => true,
                 'allow_delete' => true,
                 'required'  => false,
             ]);
@@ -62,7 +65,9 @@ class NetGroupAdmin extends BaseAdmin
         $showMapper
             ->add('name')
             ->add('opcode')
-            ->add('relay')
+            ->add('relayString', null, [
+                'label' => 'show.label_relay',
+            ])
         ;
     }
 }

+ 16 - 4
src/IPv4Bundle/Entity/NetGroup.php

@@ -52,7 +52,7 @@ class NetGroup implements TenancyIdTraitInterface, PreRemoveInterface
      * @ORM\OneToMany(targetEntity="SubNet", mappedBy="netGroup")
      */
     protected $subNets;
-    
+
     /**
      * @var array
      *
@@ -62,6 +62,10 @@ class NetGroup implements TenancyIdTraitInterface, PreRemoveInterface
      *     @Assert\NotBlank,
      *     @Assert\Ip
      * })
+     * @Assert\Count(
+     *      min = 1,
+     *      minMessage = "You must specify at least one relay IP address"
+     * )
      */
     protected $relay = array();
 
@@ -134,7 +138,7 @@ class NetGroup implements TenancyIdTraitInterface, PreRemoveInterface
 
         return $entities;
     }
-    
+
     /**
      * @return array
      */
@@ -142,7 +146,15 @@ class NetGroup implements TenancyIdTraitInterface, PreRemoveInterface
     {
         return $this->relay;
     }
-    
+
+    /**
+     * @return string
+     */
+    public function getRelayString()
+    {
+        return implode(',', array_values($this->relay));
+    }
+
     /**
      * @param array $relay
      *
@@ -151,7 +163,7 @@ class NetGroup implements TenancyIdTraitInterface, PreRemoveInterface
     public function setRelay($relay)
     {
         $this->relay = $relay;
-        
+
         return $this;
     }
 

+ 1 - 0
src/IPv4Bundle/Resources/config/services.yml

@@ -25,6 +25,7 @@ services:
             - { name: sonata.admin, manager_type: orm, group: IPv4, label: SubNet, label_catalogue: IPv4Bundle, label_translator_strategy: sonata.admin.label.strategy.underscore }
         calls:
             - [setTranslationDomain, [IPv4Bundle]]
+            - [setTemplate, [edit, "IPv4Bundle:CRUD:subnet_edit.html.twig"]]
         public: true
 
     pool_ipv4_service:

+ 1 - 0
src/IPv4Bundle/Resources/translations/validators.es.yml

@@ -1,3 +1,4 @@
 pool.lastip.error: La última ip debe ser mayor a la primera ip
 pool.ips.outrange: La primera ip y la última ip deben pertenecer a la subred
 subnet.address.error: La dirección no posee el formato adecuado
+You must specify at least one relay IP address: Debe especificar al menos un relay IP address

+ 9 - 0
src/IPv4Bundle/Resources/views/CRUD/subnet_edit.html.twig

@@ -0,0 +1,9 @@
+{% extends "@SonataAdmin/CRUD/edit.html.twig" %}
+
+{% block stylesheets %}
+
+{{ parent() }}
+
+{% include "HostBundle::dhcp_options_style.html.twig" %}
+
+{% endblock stylesheets %}

+ 4 - 1
src/KeaBundle/Command/KeaConfigCommand.php

@@ -46,7 +46,10 @@ class KeaConfigCommand extends ContainerAwareCommand
             }
             if ($dhcp) {
                 $config = $keaConfigService->getConfig($id, $class, $library);
-                $output->writeln($keaConfigService->setConfig($dhcp, $config));
+                $result = $keaConfigService->saveFileConfig($config);
+                if ($result) {
+                    $output->writeln($keaConfigService->getConfig($id, $class, $library));
+                }
             } else {
                 $output->writeln("KEA DHCP id:{$id} <error>not found!</error>");
             }

+ 52 - 46
src/KeaBundle/Services/BaseKea.php

@@ -61,6 +61,8 @@ class BaseKea implements KeaConfigInterface
         ],
     ];
 
+    private $client_classes = [];
+
 
     /**
      * @param array $data
@@ -87,6 +89,7 @@ class BaseKea implements KeaConfigInterface
                         'control-socket' => $this->controlSocketConfig(),
                         'lease-database' => $this->leaseDatabaseConfig($data),
                         'hosts-database' => $this->leaseDatabaseConfig($data),
+                        'client-classes' => $this->client_classes,
                         'subnet4' => $this->subnet4,
                         'hooks-libraries' => $this->hooks_libraries,
                         'interfaces-config' => $this->getInterfacesConfig(),
@@ -110,9 +113,9 @@ class BaseKea implements KeaConfigInterface
 
             $hostType = $subnet->getAllowedHostType();
             $client_class = '';
-            /* if ($hostType) {
+            if ($hostType != 'Cablemodem') {
                 $client_class = $hostType->getShortname();
-            } */
+            }
             if ($subnet->getStatus() != HostStatus::STATE_NONE && $subnet->getStatus() != '') {
                 if ($client_class != '') {
                     $client_class .= '-';
@@ -141,6 +144,9 @@ class BaseKea implements KeaConfigInterface
 
             if ($client_class != '') {
                 $subnetConf['client-class'] = $client_class;
+                $this->client_classes [] = [
+                    'name' => $client_class,
+                ];
             }
 
             $netgroup = $subnet->getNetGroup();
@@ -166,7 +172,7 @@ class BaseKea implements KeaConfigInterface
     private function hooksLibrariesConfig($data)
     {
         $this->hooks_libraries = [
-            /* [
+            [
                 'library' => '/opt/hooks/mysql/kea-hook-flowdat3-mysql.so',
                 'parameters' => [
                     "host" => $data['db']['host'],
@@ -174,7 +180,7 @@ class BaseKea implements KeaConfigInterface
                     "user" => $data['db']['user'],
                     "password" => $data['db']['password'],
                 ]
-            ], */
+            ],
             [
                 "library" => "/opt/hooks/amqp/kea-hook-flowdat3.so",
                 "parameters" => [
@@ -185,48 +191,48 @@ class BaseKea implements KeaConfigInterface
             ],
         ];
 
-        $dhcp = $data['dhcp'];
-        $hosts = $data['hosts'];
-
-        $hook = [
-            'library' => $data['library'],
-        ];
-
-        $dhcpModelParams = $dhcp && $dhcp->getDhcpModel() ? $dhcp->getDhcpModel()->getData('parameters') : null;
-
-        $option122 = isset($dhcpModelParams['option122']) ? $dhcpModelParams['option122'] : null;
-        $ip = isset($dhcpModelParams['ip']) ? $dhcpModelParams['ip'] : null;
-        if ($option122 && $ip) {
-            $macs = [];
-            foreach ($hosts as $host) {
-                if ($host->getMac()) {
-                    $macs[] = $host->getMac();
-                }
-            }
-
-            $hook['parameters']['option122'] = [
-                $ip => $macs
-            ];
-        }
-
-        $remote_id_map = isset($dhcpModelParams['remote-id-map']) ? $dhcpModelParams['remote-id-map'] : null;
-        if ($remote_id_map) {
-            $hostConfig = [];
-            foreach ($hosts as $host) {
-                if ($host->getMac()) {
-                    $mac = $host->getMac();
-                    $state = $host->getState();
-                    $shortname = $host->getHostType()->getShortname();
-
-                    $client_class = $state != HostStatus::STATE_NONE ? $state : $shortname;
-
-                    $hostConfig[$client_class][] = $mac;
-                }
-            }
-            $hook['parameters']['remote-id-map'] = $hostConfig;
-        }
-
-        $this->hooks_libraries[] = $hook;
+        // $dhcp = $data['dhcp'];
+        // $hosts = $data['hosts'];
+        //
+        // $hook = [
+        //     'library' => $data['library'],
+        // ];
+        //
+        // $dhcpModelParams = $dhcp && $dhcp->getDhcpModel() ? $dhcp->getDhcpModel()->getData('parameters') : null;
+        //
+        // $option122 = isset($dhcpModelParams['option122']) ? $dhcpModelParams['option122'] : null;
+        // $ip = isset($dhcpModelParams['ip']) ? $dhcpModelParams['ip'] : null;
+        // if ($option122 && $ip) {
+        //     $macs = [];
+        //     foreach ($hosts as $host) {
+        //         if ($host->getMac()) {
+        //             $macs[] = $host->getMac();
+        //         }
+        //     }
+        //
+        //     $hook['parameters']['option122'] = [
+        //         $ip => $macs
+        //     ];
+        // }
+        //
+        // $remote_id_map = isset($dhcpModelParams['remote-id-map']) ? $dhcpModelParams['remote-id-map'] : null;
+        // if ($remote_id_map) {
+        //     $hostConfig = [];
+        //     foreach ($hosts as $host) {
+        //         if ($host->getMac()) {
+        //             $mac = $host->getMac();
+        //             $state = $host->getState();
+        //             $shortname = $host->getHostType()->getShortname();
+        //
+        //             $client_class = $state != HostStatus::STATE_NONE ? $state : $shortname;
+        //
+        //             $hostConfig[$client_class][] = $mac;
+        //         }
+        //     }
+        //     $hook['parameters']['remote-id-map'] = $hostConfig;
+        // }
+
+        // $this->hooks_libraries[] = $hook;
     }
 
     /**

+ 11 - 11
src/KeaBundle/Services/KeaConfigService.php

@@ -14,7 +14,7 @@ class KeaConfigService
      * @var EntityManager
      */
     private $em;
-    
+
     /**
      * @var EntityRepository
      */
@@ -75,7 +75,7 @@ class KeaConfigService
      *
      * @return string
      */
-    public function getConfig($id, $className = 'BaseKea', $library = '/kea-cm-hook/kea-hook-flowdat.so')
+    public function getConfig($id, $className = 'BaseKea', $library = '/opt/hooks/kea-cm-hook/kea-hook-flowdat.so')
     {
         $config = '';
         $fullClass = 'KeaBundle\\Services\\' . $className;
@@ -180,7 +180,7 @@ class KeaConfigService
         $_params = json_decode($params, true);
         if(isset($_params[0]) && isset($_params[0]['arguments'])) {
             $json = json_encode($_params[0]['arguments'], JSON_PRETTY_PRINT);
-            file_put_contents("kea/kea-dhcp4.conf", $json);
+            file_put_contents("/opt/dhcp/web/kea/kea-dhcp4.conf", $json);
 
             return true;
         }
@@ -240,7 +240,7 @@ class KeaConfigService
 
         return $return;
     }
-    
+
     /**
      * @param SubNet $subnet
      *
@@ -262,26 +262,26 @@ class KeaConfigService
                 }
             }
         }
-        
+
         return $position;
     }
 
     /**
      * @return array
      */
-    private function getHostsReservations() 
+    private function getHostsReservations()
     {
         $subnets = $this->subnetRepository->findAll();
         $reservations = [];
-        
+
         if(is_null($subnets) || empty($subnets)) {
             return $reservations;
         }
 
         foreach ($subnets as $subnet) {
-            
+
             foreach ($subnet->getIpPool() as $pool) {
-                
+
                 $start = ip2long($pool->getFirstIp());
                 $end = ip2long($pool->getLastIp());
 
@@ -295,9 +295,9 @@ class KeaConfigService
                             $qb->expr()->between('h.ipv4Address',$start,$end)
                         )
                     );
-                
+
                 $hosts = $qb->getQuery()->getResult();
-                
+
                 $results = array();
                 if($hosts) {
                     foreach($hosts as $host) {