ソースを参照

FD3-536 Se añaden métodos para obtener config desde kea, generar config desde el sistema y para cargar config en kea.

Maxi Schvindt 7 年 前
コミット
18a7370542

+ 44 - 3
src/KeaBundle/Controller/ConfigController.php

@@ -14,6 +14,8 @@ use KeaBundle\Entity\Config;
 use Symfony\Component\Form\Extension\Core\Type\TextType;
 use Symfony\Component\Form\Extension\Core\Type\DateType;
 use Symfony\Component\Form\Extension\Core\Type\SubmitType;
+use Symfony\Bridge\Doctrine\Form\Type\EntityType;
+
 use WebserviceBundle\Form\Type\RemoteClientType;
 use FOS\RestBundle\Controller\Annotations\RouteResource;
 
@@ -24,10 +26,49 @@ use FOS\RestBundle\Controller\Annotations\RouteResource;
 class ConfigController extends Controller
 {
 
-    public function getAction() 
+    public function getAction(Request $request) 
     {
-        print_r("getAction");
-        die;
+        $adminPool = $this->get('sonata.admin.pool');
+        $translator = $this->get('translator');
+        $flashbag = $this->get('session')->getFlashBag();
+
+        $form = $this->createFormBuilder()
+            ->add('dhcpId', EntityType::class, array('class' => 'DHCPBundle\Entity\DHCP', 'choice_label' => 'name', 'label' => $translator->trans("form.label_dhcp", array(), "KeaBundle")))
+            ->getForm();
+
+        //$flashbag->add("warning", $translator->trans("msg_select_map", array(), "KeaBundle"));
+
+        if ($dhcpId = $request->get('dhcpId')) {
+            $action = $request->get('action');
+
+            $dhcp = $this->container->get("doctrine.orm.entity_manager")->getRepository("DHCPBundle\Entity\DHCP")->findOneById($dhcpId);
+            
+            $keaConfigService = $this->get('kea.config');
+
+            if($action == 'get') {
+                $config = $keaConfigService->getRemoteConfig($dhcp);
+            } elseif($action == 'generate') {
+                $config = $keaConfigService->getConfig($dhcpId);
+            } elseif($action == 'set') {
+                $params = $request->get('params');
+                $config = $keaConfigService->setConfig($dhcp, $params);
+            } else {
+                $config = json_encode(array("error" => "Acción no definida"));
+            }
+
+            $decode = json_decode($config);
+            $response = new JsonResponse();
+            $response->setData(json_encode($decode, JSON_PRETTY_PRINT));
+
+            return $response;
+        }
+
+        return $this->render('KeaBundle:Config:get.html.twig', array(
+            'base_template' => $adminPool->getTemplate('layout'),
+            'admin_pool' => $adminPool,
+            'admin' => $adminPool->getAdminByClass("KeaBundle\Entity\Config"),
+            'form' => $form->createView()
+        ));
     }
 
     public function setAction() 

+ 1 - 1
src/KeaBundle/Resources/config/services.yml

@@ -1,7 +1,7 @@
 services:
     kea.config:
         class: KeaBundle\Services\KeaConfigService
-        arguments: ["@doctrine.orm.entity_manager"]
+        arguments: ["@webservice", "@doctrine.orm.entity_manager"]
 
     sonata.admin.kea_config:
         class: KeaBundle\Admin\ConfigAdmin

+ 6 - 1
src/KeaBundle/Resources/translations/KeaBundle.es.yml

@@ -28,4 +28,9 @@ filter:
     label_description: Descripción
     label_dhcp: DHCP
     label_created: Creado
-    label_template: Plantilla
+    label_template: Plantilla
+
+msg_import_kea_config: Obtener configuración de Kea
+select_dhcp_and_get_config: Seleccionar DHCP y obtener configuración
+get_config: Obtener configuración
+generate_config: Generar configuración

+ 180 - 0
src/KeaBundle/Resources/views/Config/get.html.twig

@@ -0,0 +1,180 @@
+{% extends 'SonataAdminBundle:CRUD:base_list.html.twig' %}
+
+{% block stylesheets %}
+{{ parent() }}
+<style>
+.ace_editor {height: 450px!important;}
+</style>
+{% endblock %}
+
+{% block javascripts %}
+{{ parent() }}
+<script src="{{ asset('bundles/baseadmin') }}/ace_editor/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
+<script src="{{ asset('bundles/baseadmin') }}/ace_editor/textarea-as-ace-editor.js" type="text/javascript" charset="utf-8"></script>
+{% endblock %}
+
+{% block actions %}{% endblock %}
+
+{% block tab_menu %}
+<ol class="nav navbar-top-links breadcrumb">
+    <li>
+        <a href="{{url('sonata_admin_dashboard')}}"><i class="fa fa-home"></i></a>
+    </li>
+    <li class="active"><span>{{ 'msg_import_kea_config'|trans({}, 'KeaBundle') }}</span></li>
+</ol>
+{% endblock %}
+
+{% block title %}
+{% endblock %}
+
+{% block navbar_title %}
+{% endblock %}
+
+{% block list_filters_actions %}
+<ul class="nav navbar-nav navbar-right">
+    <li><a class="sonata-action-element" href="{{url('admin_kea_config_list')}}"><i class="fa fa-list" aria-hidden="true"></i>
+        {{ 'link_action_list'|trans({}, 'SonataAdminBundle') }}
+    </a></li>
+</ul>
+{% endblock %}
+
+{% block list_filters %}
+{% endblock %}
+
+{% block list_table %}
+{% endblock %}
+
+{% block sonata_wrapper %}
+{{ parent() }}
+{# <footer class="footer">
+    <span id="statusBar" class="statusBar"></span>
+</footer> #}
+{% endblock %}
+
+{% block content %}
+
+<div id='wrapper' class="box box-primary">
+    <div id='page-content-wrapper'>
+        <div class="row">
+            <div class="col-md-12">
+                <div class="box box-primary" style="border-top:0px">
+                    <div class="box-header">
+                        <h4 class="box-title">
+                            {{ 'select_dhcp_and_get_config'|trans({}, 'KeaBundle') }}
+                        </h4>
+                    </div>
+                    <div class="box-body">  
+                        <div class="sonata-ba-collapsed-fields">
+                            <div class="form-group clearfix">
+                                {{ form_widget(form) }}
+                                <br />
+                                <textarea id="textarea_ace_editor"></textarea>
+                            </div>
+                        </div>
+                    </div>
+                </div>
+            </div>
+        </div>
+
+    </div>
+</div>
+
+<div class="sonata-ba-form-actions well well-small form-actions">
+    <button class="btn btn-success" type="submit" id="btn_get_config">
+        <i class="fa fa-download" aria-hidden="true"></i>&nbsp;{{ 'get_config'|trans({}, 'KeaBundle') }}
+    </button>
+    <button class="btn btn-success" type="submit" id="btn_generate_config">
+        <i class="fa fas fa-cog" aria-hidden="true"></i>&nbsp;{{ 'generate_config'|trans({}, 'KeaBundle') }}
+    </button>
+    <button class="btn btn-success" type="submit" id="btn_set_config">
+        <i class="fa fa-upload" aria-hidden="true"></i>&nbsp;{{ 'set_config'|trans({}, 'KeaBundle') }}
+    </button>
+</div>
+
+
+<script type="text/javascript">
+
+$(document).ready(function() {
+    $("#textarea_ace_editor").asAceEditor();
+    editor = $('#textarea_ace_editor').data('ace-editor');
+
+    editor.setTheme("ace/theme/github");
+    editor.getSession().setMode("ace/mode/json");
+    editor.setReadOnly(false);
+    editor.setFontSize(14);
+    editor.setShowInvisibles(true);
+    editor.getSession().setTabSize(2);
+    editor.getSession().setUseSoftTabs(true);
+    editor.getSession().setUseWrapMode(true); 
+
+    $("#btn_get_config").click(function(){
+        $("#btn_get_config").attr('disabled','disabled');
+        
+        dhcpId = $("#form_dhcpId").val();
+
+        if(!dhcpId) {
+            $("#btn_get_config").removeAttr('disabled');
+            alert("{{ 'alert_select_dhcp'|trans({}, 'KeaBundle') }}");
+            return;
+        }
+
+        result = getConfig(dhcpId, 'get');
+        
+        $("#btn_get_config").removeAttr('disabled');
+    });
+
+    $("#btn_generate_config").click(function(){
+        $("#btn_generate_config").attr('disabled','disabled');
+        
+        dhcpId = $("#form_dhcpId").val();
+
+        if(!dhcpId) {
+            $("#btn_generate_config").removeAttr('disabled');
+            alert("{{ 'alert_select_dhcp'|trans({}, 'KeaBundle') }}");
+            return;
+        }
+
+        result = getConfig(dhcpId, 'generate');
+        
+        $("#btn_generate_config").removeAttr('disabled');
+    });
+    
+    $("#btn_set_config").click(function(){
+        $("#btn_set_config").attr('disabled','disabled');
+        
+        dhcpId = $("#form_dhcpId").val();
+
+        if(!dhcpId) {
+            $("#btn_set_config").removeAttr('disabled');
+            alert("{{ 'alert_select_dhcp'|trans({}, 'KeaBundle') }}");
+            return;
+        }
+
+        result = getConfig(dhcpId, 'set');
+        
+        $("#btn_set_config").removeAttr('disabled');
+    });
+
+    
+});
+
+function getConfig(dhcpId, action) {
+
+    var r = false;
+    params = editor.getSession().getValue();
+    
+    $.ajax({
+        method: "POST",
+        async: false,
+        cache: false,
+        url: "{{url('kea_get_config')}}?_=" + new Date().getTime(),
+        data: { dhcpId: dhcpId, action: action, params: params }
+    }).done(function( result ) {
+        editor.setValue(result, -1);
+    });
+
+    return true;
+}
+
+</script>
+{% endblock %}

+ 41 - 5
src/KeaBundle/Services/BaseKea.php

@@ -37,6 +37,8 @@ class BaseKea implements KeaConfigInterface
 
         return json_encode([
             'Dhcp4' => [
+                'control-socket' => $this->controlSocketConfig(),
+                'lease-database' =>$this->leaseDatabaseConfig(),
                 'subnet4' => $this->subnet4,
                 'hooks-libraries' => $this->hooks_libraries,
             ],
@@ -114,18 +116,52 @@ class BaseKea implements KeaConfigInterface
     }
 
     /**
-     * @return string
+     * @return array
      */
     private function loggingConfig()
     {
         return array(
             'loggers' => array(
-                'name' => 'kea-dhcp4',
-                'severity' => 'DEBUG',
-                'debuglevel' => 99,
-                'output_options' => array(array('output' => 'stdout')),
+                array(
+                    'debuglevel' => 0,
+                    'name' => 'kea-dhcp4',
+                    'output_options' => array(
+                        array(
+                            'flush' => true,
+                            'maxsize' => 10240000,
+                            'maxver' => 1,
+                            'output' => '/usr/local/var/log/kea-dhcp4.log'
+                        )
+                    ),
+                    'severity' => 'INFO'
+                )
             )
         );
     }
 
+    /**
+     * @return array
+     */
+    private function controlSocketConfig() 
+    {
+        /* "control-socket": {"socket-name": "\/tmp\/kea-dhcp4-ctrl.sock","socket-type": "unix"} */
+        return array(
+            'socket-name' => '/tmp/kea-dhcp4-ctrl.sock',
+            'socket-type' => 'unix'
+        );
+    }
+
+    /**
+     * @return array
+     */
+    private function leaseDatabaseConfig() 
+    {
+        /* "lease-database": {"lfc-interval": 3600,"type": "memfile"} */
+        return array(
+            'lfc-interval' => 3600,
+            'type' => 'memfile'
+        );
+
+    }
+
 }

+ 76 - 1
src/KeaBundle/Services/KeaConfigService.php

@@ -3,6 +3,7 @@
 namespace KeaBundle\Services;
 
 use KeaBundle\Interfaces\KeaConfigInterface;
+use DHCPBundle\Entity\DHCP;
 
 class KeaConfigService
 {
@@ -22,15 +23,22 @@ class KeaConfigService
      */
     private $hostRepository;
 
+    /**
+     * @var Service
+     */
+    private $webService;
+
+
 
     /**
      * @param EntityManager $em
      */
-    public function __construct($em)
+    public function __construct($ws, $em)
     {
         $this->dhcpRepository = $em->getRepository('DHCPBundle:DHCP');
         $this->subnetRepository = $em->getRepository('IPv4Bundle:SubNet');
         $this->hostRepository = $em->getRepository('IPv4Bundle:Host');
+        $this->webService = $ws;
     }
 
     /**
@@ -60,4 +68,71 @@ class KeaConfigService
         return $config;
     }
 
+    /**
+     * @param DHCP $dhcp
+     *
+     * @return string
+     */
+    public function getRemoteConfig(DHCP $dhcp, $service = null)
+    {
+        $host = $dhcp->getHost();
+        if(is_null($host)) $host = "kea:8080";
+        
+        $_params = array("command" => "config-get", "service" => array("dhcp4"));
+        
+        $params = json_encode($_params);
+        
+        $config = $this->curlPost($host, $params);
+
+        return $config;
+
+    }
+
+    /**
+     * @param DHCP $dhcp
+     * @param json params
+     * 
+     * @return string
+     */
+    public function setConfig(DHCP $dhcp, $params = null)
+    {
+        $host = $dhcp->getHost();
+        if(is_null($host)) $host = "kea:8080";
+
+        $_params = json_decode($params, true);
+        $json = json_encode($_params);
+        
+        if(isset($_params['Dhcp4'])) {
+            $_params = array("command" => "config-set", "service" => array("dhcp4"), "arguments" => $_params);
+        } else {
+            return json_encode(array("error" => "Config Error."));
+        }
+        
+        $config = $this->curlPost($host, json_encode($_params));
+
+        return $config;
+
+    }
+
+    private function curlPost($host, $params) 
+    {
+        $ch = curl_init();
+
+        curl_setopt($ch, CURLOPT_URL, "http://{$host}");
+        curl_setopt($ch, CURLOPT_POST, true);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
+        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($params)));
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+        try {
+            $return = curl_exec($ch);
+        } catch (\Exception $ex) {
+            // $ex->getMessage()
+            return json_encode(array("error" => "Connection Error."));
+        }
+
+        return $return;
+
+    }
+
 }