Просмотр исходного кода

Merged in FD3-536 (pull request #16)

FD3-536 - Configurar KEA desde Flowdat

Approved-by: Guillermo Espinoza <guillermo@interlink.com.ar>
Approved-by: Maximiliano Schvindt <maximiliano@interlink.com.ar>
Maximiliano Schvindt 7 лет назад
Родитель
Сommit
ee6a348822

+ 6 - 0
app/config/roles.yml

@@ -52,6 +52,12 @@ security:
         ROLE_SONATA_TEMPLATE_EDITOR: [ROLE_SONATA_TEMPLATE_READER, ROLE_SONATA_ADMIN_TEMPLATE_CREATE, ROLE_SONATA_ADMIN_TEMPLATE_EDIT]
         ROLE_SONATA_TEMPLATE_ADMIN: [ROLE_SONATA_TEMPLATE_EDITOR, ROLE_SONATA_ADMIN_TEMPLATE_DELETE, ROLE_SONATA_ADMIN_TEMPLATE_EXPORT]
 
+        # KEA
+        ROLE_SONATA_KEA_CONFIG_READER: [ROLE_ADMIN, ROLE_SONATA_ADMIN_KEA_CONFIG_LIST, ROLE_SONATA_ADMIN_KEA_CONFIG_VIEW]
+        ROLE_SONATA_KEA_CONFIG_EDITOR: [ROLE_SONATA_KEA_CONFIG_READER, ROLE_SONATA_ADMIN_KEA_CONFIG_CREATE, ROLE_SONATA_ADMIN_KEA_CONFIG_EDIT]
+        ROLE_SONATA_KEA_CONFIG_ADMIN: [ROLE_SONATA_KEA_CONFIG_EDITOR, ROLE_SONATA_ADMIN_KEA_CONFIG_DELETE, ROLE_SONATA_ADMIN_KEA_CONFIG_EXPORT]
+
         ROLE_ADMIN_TENANCIES: ROLE_ADMIN_TENANCIES
         ROLE_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN]
         ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_USER_CREATE, ROLE_ADMIN_TENANCIES, ROLE_ALLOWED_TO_SWITCH]
+

+ 5 - 0
app/config/routing.yml

@@ -13,6 +13,10 @@ dhcp:
     type:     annotation
     prefix:   /
 
+KeaBundle:
+    resource: "@KeaBundle/Resources/config/routing/admin.xml"
+    prefix: /
+
 i_pv4_sub_net_api:
     resource: "@IPv4Bundle/Controller/REST/SubNetRESTController.php"
     type:   rest
@@ -97,3 +101,4 @@ _sonata:
 admin_tenancy_change_tenancy_global_ajax:
     path: changeTenancyAjaxAction
     defaults: { _controller: BaseAdminBundle:RedirectionAjax:changeTenancyAjax }
+

+ 105 - 0
src/KeaBundle/Admin/ConfigAdmin.php

@@ -0,0 +1,105 @@
+<?php
+
+namespace KeaBundle\Admin;
+
+use Base\AdminBundle\Admin\BaseAdmin;
+use Sonata\AdminBundle\Datagrid\DatagridMapper;
+use Sonata\AdminBundle\Datagrid\ListMapper;
+use Sonata\AdminBundle\Form\FormMapper;
+use Sonata\AdminBundle\Show\ShowMapper;
+use Sonata\AdminBundle\Route\RouteCollection;
+
+class ConfigAdmin extends BaseAdmin
+{
+
+    public function getTemplate($name)
+    {
+        switch ($name) {
+            case 'edit':
+                return 'TemplateBundle:Template:template_edit.html.twig';
+                break;
+
+            default:
+                return parent::getTemplate($name);
+                break;
+        }
+    }
+
+    protected function configureRoutes(RouteCollection $collection)
+    {
+        $collection->remove('history')->remove('create');
+    }
+
+    /**
+     * @param string $action
+     * @param Object $object
+     * 
+     * @return array
+     */
+    public function configureActionButtons($action, $object = null)
+    {
+        $actions = parent::configureActionButtons($action, $object);
+        $actions['config_manager'] = array(
+            'template' => 'KeaBundle:Config:config_manager_button.html.twig',
+        );
+
+        return $actions;
+    }
+
+    /**
+     * @param DatagridMapper $datagridMapper
+     */
+    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
+    {
+        $datagridMapper
+            ->add('description')
+            ->add('dhcp')
+            ->add('template')
+        ;
+    }
+
+    /**
+     * @param ListMapper $listMapper
+     */
+    protected function configureListFields(ListMapper $listMapper)
+    {
+        $listMapper
+            ->add('dhcp')
+            ->add('description')
+            //->add('template')
+            ->add('created')
+            ->add('_action', null, array(
+                'actions' => array(
+                    'show' => array(),
+                    'edit' => array(),
+                    'delete' => array(),
+                ),
+            ))
+        ;
+    }
+
+    /**
+     * @param FormMapper $formMapper
+     */
+    protected function configureFormFields(FormMapper $formMapper)
+    {
+        $formMapper
+            ->add('dhcp')
+            ->add('description')
+            ->add('template')
+        ;
+    }
+
+    /**
+     * @param ShowMapper $showMapper
+     */
+    protected function configureShowFields(ShowMapper $showMapper)
+    {
+        $showMapper
+            ->add('dhcp')
+            ->add('description')
+            ->add('created')
+            ->add('template', 'string', array('template' => 'TemplateBundle:CRUD:content_field.html.twig','data' => 'show'))
+        ;
+    }
+}

+ 96 - 0
src/KeaBundle/Controller/ConfigController.php

@@ -0,0 +1,96 @@
+<?php
+
+namespace KeaBundle\Controller;
+
+use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
+use Symfony\Bundle\FrameworkBundle\Controller\Controller;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\JsonResponse;
+use Symfony\Component\HttpFoundation\Response;
+
+use DHCPBundle\Entity\DHCP;
+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;
+
+/**
+ * Config controller.
+ * @RouteResource("Kea")
+ */
+class ConfigController extends Controller
+{
+
+    public function getAction(Request $request) 
+    {
+        $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();
+
+        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);
+            } elseif($action == 'save') {
+                $params = $request->get('params');
+                $this->saveConfig($dhcp, $params);
+                $config = json_encode(array("ok" => $translator->trans("form.config_created", array(), "KeaBundle")));
+            } else {
+                $config = json_encode(array("error" => $translator->trans("form.action_not_defined", array(), "KeaBundle")));
+            }
+
+            $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()
+        ));
+    }
+
+    /**
+     * @param DHCP
+     * @param json
+     */
+    private function saveConfig(DHCP $dhcp, $template)
+    {
+        $em = $this->get('doctrine')->getManager();
+        $now = date("Y-m-d H:i");
+
+        $config = new Config();
+        $config->setDhcp($dhcp);
+        $config->setTemplate($template);
+        $config->setDescription("DHCP Config {$dhcp->getName()}({$dhcp->getHost()}) - {$now}");
+
+        $em->persist($config);
+        $em->flush();
+
+        return true; 
+    }
+
+}

+ 165 - 0
src/KeaBundle/Entity/Config.php

@@ -0,0 +1,165 @@
+<?php
+
+namespace KeaBundle\Entity;
+
+use Doctrine\ORM\Mapping as ORM;
+use JMS\Serializer\Annotation as JMS;
+use Symfony\Component\Validator\Constraints as Assert;
+use Gedmo\Mapping\Annotation as Gedmo;
+
+/**
+ * Config
+ *
+ * @ORM\Table
+ * @ORM\Entity
+ */
+class Config
+{
+
+    /**
+     * @var int
+     *
+     * @ORM\Column(name="id", type="integer")
+     * @ORM\Id
+     * @ORM\GeneratedValue(strategy="AUTO")
+     */
+    private $id;
+
+    /**
+     * @var string
+     *
+     * @ORM\Column(type="string", length=255)
+     */
+    private $description;
+
+    /**
+     * @ORM\ManyToOne(targetEntity="\DHCPBundle\Entity\DHCP", inversedBy="configs", fetch="EXTRA_LAZY")
+     * @ORM\JoinColumn(onDelete="SET NULL")
+     *
+     * @JMS\MaxDepth(1)
+     */
+    private $dhcp;
+
+    /**
+     * @var text
+     *
+     * @ORM\Column(type="text", nullable=false)
+     */
+    protected $template;
+    
+    /**
+     * @Gedmo\Timestampable(on="create")
+     * @ORM\Column(type="datetime")
+     */
+    protected $created;
+
+    /**
+    * @return string
+    */
+    public function __toString()
+    {
+        return "Config KEA";
+    }
+
+    /**
+     * Get id
+     *
+     * @return int
+     */
+    public function getId()
+    {
+        return $this->id;
+    }
+
+    /**
+     * Set description
+     *
+     * @param string $description
+     *
+     * @return Config
+     */
+    public function setDescription($description)
+    {
+        $this->description = $description;
+
+        return $this;
+    }
+
+    /**
+     * Get description
+     *
+     * @return string
+     */
+    public function getDescription()
+    {
+        return $this->description;
+    }
+
+    /**
+     * Set template
+     *
+     * @param text $template
+     *
+     * @return Config
+     */
+    public function setTemplate($template)
+    {
+        $this->template = $template;
+
+        return $this;
+    }
+
+    /**
+     * Get template
+     *
+     * @return text
+     */
+    public function getTemplate()
+    {
+        return $this->template;
+    }
+
+    /**
+     * @return DHCP
+     */
+    public function getDhcp()
+    {
+        return $this->dhcp;
+    }
+
+    /**
+     * @param DHCP $dhcp
+     *
+     * @return Config
+     */
+    public function setDhcp($dhcp)
+    {
+        $this->dhcp = $dhcp;
+
+        return $this;
+    }
+
+    /**
+     * Get created
+     *
+     * @return \DateTime
+     */
+    public function getCreated()
+    {
+        return $this->created;
+    }
+
+    /**
+     * Set created
+     *
+     * @param \DateTime
+     *
+     * @return Config
+     */
+    public function setCreated($d)
+    {
+        $this->created = $d;
+        return $this;
+    }
+
+}

+ 11 - 0
src/KeaBundle/Resources/config/routing/admin.xml

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<routes xmlns="http://symfony.com/schema/routing"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">
+
+    <route id="kea_get_config" path="/admin/kea/config/get">
+        <default key="_controller">KeaBundle:Config:get</default>
+    </route>
+    
+</routes>

+ 12 - 3
src/KeaBundle/Resources/config/services.yml

@@ -1,4 +1,13 @@
 services:
-   kea.config:
-       class: KeaBundle\Services\KeaConfigService
-       arguments: ["@doctrine.orm.entity_manager"]
+    kea.config:
+        class: KeaBundle\Services\KeaConfigService
+        arguments: ["@webservice", "@doctrine.orm.entity_manager"]
+
+    sonata.admin.kea_config:
+        class: KeaBundle\Admin\ConfigAdmin
+        arguments: [~, KeaBundle\Entity\Config, BaseAdminBundle:CRUD]
+        tags:
+            - { name: sonata.admin, manager_type: orm, group: Kea, label: Config, label_catalogue: KeaBundle, label_translator_strategy: sonata.admin.label.strategy.underscore, audit: false }
+        calls:
+            - [setTranslationDomain, [KeaBundle]]
+        public: true

+ 48 - 0
src/KeaBundle/Resources/translations/KeaBundle.es.yml

@@ -0,0 +1,48 @@
+Kea: Kea
+Config: Configuración
+
+form:
+    label_description: Descripción
+    label_dhcp: DHCP
+    label_created: Creado
+    label_template: Plantilla
+    config_created: Config guardada
+    action_not_defined: Acción no definida
+
+breadcrumb:
+    link_d_h_c_p_list: Listado Configuraciones
+    link_d_h_c_p_delete: Eliminar Configuración
+    link_config_list: Listado de Configuraciones
+    link_config_delete: Eliminar Configuración
+    
+list:
+    label_description: Descripción
+    label_dhcp: DHCP
+    label_created: Creado
+    label_template: Plantilla
+    label__action: Acciones
+
+show:
+    label_description: Descripción
+    label_dhcp: DHCP
+    label_created: Creado
+    label_template: Plantilla
+
+filter:
+    label_description: Descripción
+    label_dhcp: DHCP
+    label_created: Creado
+    label_template: Plantilla
+
+msg_import_kea_config: Obtener configuración de Kea
+select_dhcp_and_get_config: Seleccionar DHCP y obtener configuración
+kea_options: Opciones de configuración
+get_config: Obtener configuración
+get_config_help: Obtiene la configuración actual del KEA perteneciente al DHCP seleccionado.
+generate_config: Generar configuración
+generate_config_help: Genera la configuración para el KEA del DHCP partiendo de los datos cargados en el sistema de Flowdat(host, dhcp, subred y pool).
+set_config: Cargar configuración
+set_config_help: Envía la configuración visible en el editor al KEA del DHCP seleccionado(recomendable guardar la configuración actual antes de cargar una nueva configuración).
+save_config: Guardar configuración
+save_config_help: Guarda la configuración visible en el sistema.
+kea_get_config: Configurar KEA

+ 6 - 0
src/KeaBundle/Resources/views/Config/config_manager_button.html.twig

@@ -0,0 +1,6 @@
+<li>
+    <a class="sonata-action-element" href="{{ path('kea_get_config') }}">
+        <i class="fa fa-cog" aria-hidden="true"></i>
+        {{ 'kea_get_config'|trans({}, 'KeaBundle') }}
+    </a>
+</li>

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

@@ -0,0 +1,163 @@
+{% 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() }}
+{% 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 />
+                                <div class="clearfix">
+                                    <div style="width:55%; float: left">
+                                        <textarea id="textarea_ace_editor"></textarea>
+                                    </div>
+                                    <div style="width:40%; float: left">
+                                        <br />
+                                        <p class="text-uppercase">{{ 'kea_options'|trans({}, 'KeaBundle') }}</p>
+                                        <br />
+                                        <code><i class="fa fa-download" aria-hidden="true"></i> {{ 'get_config'|trans({}, 'KeaBundle') }} :</code> {{ 'get_config_help'|trans({}, 'KeaBundle') }}
+                                        <br />
+                                        <code><i class="fa fa-cog" aria-hidden="true"></i> {{ 'generate_config'|trans({}, 'KeaBundle') }} :</code> {{ 'generate_config_help'|trans({}, 'KeaBundle') }}
+                                        <br />
+                                        <code><i class="fa fa-upload" aria-hidden="true"></i> {{ 'set_config'|trans({}, 'KeaBundle') }} :</code> {{ 'set_config_help'|trans({}, 'KeaBundle') }}
+                                        <br />
+                                        <code><i class="fa fa-save" aria-hidden="true"></i> {{ 'save_config'|trans({}, 'KeaBundle') }} :</code> {{ 'save_config_help'|trans({}, 'KeaBundle') }}
+                                    </div>
+                                </div>
+                                <div id="result_load" style="display:none">
+                                    <pre id="result_load_pre"></pre>
+                                </div>
+                            </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" onclick="bclick('btn_get_config','get');">
+        <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" onclick="bclick('btn_generate_config','generate');">
+        <i class="fa fa-cog" aria-hidden="true"></i>&nbsp;{{ 'generate_config'|trans({}, 'KeaBundle') }}
+    </button>
+    <button class="btn btn-success" type="submit" id="btn_set_config" onclick="bclick('btn_set_config','set');">
+        <i class="fa fa-upload" aria-hidden="true"></i>&nbsp;{{ 'set_config'|trans({}, 'KeaBundle') }}
+    </button>
+    <button class="btn btn-success" type="submit" id="btn_save_config" onclick="bclick('btn_save_config','save');">
+        <i class="fa fa-save" aria-hidden="true"></i>&nbsp;{{ 'save_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); 
+});
+
+function bclick(id, action) {
+    $("#"+id).attr('disabled','disabled');
+    
+    dhcpId = $("#form_dhcpId").val();
+    if(!dhcpId) {
+        $("#"+id).removeAttr('disabled');
+        alert("{{ 'alert_select_dhcp'|trans({}, 'KeaBundle') }}");
+        return;
+    }
+    result = getConfig(dhcpId, action);
+    $("#"+id).removeAttr('disabled');
+}
+
+function getConfig(dhcpId, action) {
+    
+    params = editor.getSession().getValue();
+    $("#result_load").hide();
+    
+    $.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 ) {
+        if(action == "set" || action == "save") {
+            $("#result_load_pre").html(result);
+            $("#result_load").show();
+        } else {
+            editor.setValue(result, -1);
+        }
+    });
+    return true;
+}
+
+</script>
+{% endblock %}

+ 49 - 11
src/KeaBundle/Services/BaseKea.php

@@ -36,12 +36,16 @@ class BaseKea implements KeaConfigInterface
         }
 
         return json_encode([
-            'Dhcp4' => [
-                'subnet4' => $this->subnet4,
-                'hooks-libraries' => $this->hooks_libraries,
-            ],
-            'Logging' => $this->loggingConfig(),
-        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
+                array(
+                'arguments' => array(
+                    'Dhcp4' => [
+                        'control-socket' => $this->controlSocketConfig(),
+                        'lease-database' =>$this->leaseDatabaseConfig(),
+                        'subnet4' => $this->subnet4,
+                        'hooks-libraries' => $this->hooks_libraries,
+                    ],
+                    'Logging' => $this->loggingConfig(),
+            ))], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
     }
 
     /**
@@ -114,18 +118,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[0]) && isset($_params[0]['arguments'])) {
+            $_params = array("command" => "config-set", "service" => array("dhcp4"), "arguments" => $_params[0]['arguments']);
+        } else {
+            return json_encode(array("error" => "Config Error. Check template DHCP"));
+        }
+        
+        $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" => "Kea Connection Error."));
+        }
+
+        return $return;
+
+    }
+
 }