DHCPHostCRUDCommand.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. namespace CablemodemBundle\Command;
  3. use Buzz\Message\RequestInterface as HttpRequestInterface;
  4. use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
  5. use Symfony\Component\Console\Input\InputArgument;
  6. use Symfony\Component\Console\Input\InputOption;
  7. use Symfony\Component\Console\Input\InputInterface;
  8. use Symfony\Component\Console\Output\OutputInterface;
  9. use Symfony\Component\Console\Style\SymfonyStyle;
  10. class DHCPHostCRUDCommand extends ContainerAwareCommand
  11. {
  12. /**
  13. * @see Command
  14. */
  15. protected function configure()
  16. {
  17. $params = [
  18. 'CMD_USERNAME' => getenv("CMD_USERNAME") ? getenv("CMD_USERNAME") : 'admin',
  19. 'CMD_PASSWORD' => getenv("CMD_PASSWORD") ? getenv("CMD_PASSWORD") : 'admin'
  20. ];
  21. $dhcpUrl = getenv("HOST_DHCP");
  22. $this
  23. ->setName('dhcp:host:crud')
  24. ->setDescription('DHCP Host CRUD')
  25. ->setDefinition(array(
  26. new InputArgument('mac', InputArgument::REQUIRED, "Cablemodem mac address"),
  27. new InputOption('delete', 'd'),
  28. new InputOption('url-get', null, InputOption::VALUE_OPTIONAL, 'API URL GET hosts', "https://{$dhcpUrl}/api/hosts.json"),
  29. new InputOption('url-post', null, InputOption::VALUE_OPTIONAL, 'API URL POST hosts', "https://{$dhcpUrl}/api/hosts.json"),
  30. new InputOption('url-put', null, InputOption::VALUE_OPTIONAL, 'API URL PUT hosts', "https://{$dhcpUrl}/api/hosts/{id}.json"),
  31. new InputOption('url-delete', null, InputOption::VALUE_OPTIONAL, 'API URL DELETE hosts', "https://{$dhcpUrl}/api/hosts/{id}.json"),
  32. new InputOption('url-get-hosttype', null, InputOption::VALUE_OPTIONAL, 'API URL GET hosts types', "https://{$dhcpUrl}/api/hosttypes.json"),
  33. new InputOption('api-username', null, InputOption::VALUE_OPTIONAL, 'API username', $params["CMD_USERNAME"]),
  34. new InputOption('api-password', null, InputOption::VALUE_OPTIONAL, 'API password', $params["CMD_PASSWORD"]),
  35. ))
  36. ->setHelp(<<<EOT
  37. The <info>dhcp:host:crud</info> command create or delete a DHCP Host from Cablemodem HostType and mac parameter
  38. EOT
  39. );
  40. }
  41. /**
  42. * @param InputInterface $input
  43. * @param OutputInterface $output
  44. */
  45. protected function execute(InputInterface $input, OutputInterface $output)
  46. {
  47. $this->input = $input;
  48. $this->io = new SymfonyStyle($input, $output);
  49. $this->mac = $input->getArgument('mac');
  50. $this->webservice = $this->getContainer()->get('webservice');
  51. $this->credentials = [
  52. 'username' => $input->getOption('api-username'),
  53. 'password' => $input->getOption('api-password'),
  54. ];
  55. // deshabilito filtros, entre ellos soft_delete
  56. $em = $this->getContainer()->get('doctrine.orm.entity_manager');
  57. $filters = $em->getFilters();
  58. $enabledFilters = $filters->getEnabledFilters();
  59. foreach ($enabledFilters as $filter_name => $filter) {
  60. $filters->disable($filter_name);
  61. }
  62. $this->cablemodem = $em->getRepository('CablemodemBundle:Cablemodem')->findOneByMac($this->mac);
  63. if ($this->cablemodem) {
  64. // Crea el Host
  65. if ($this->input->getOption('delete') != true) {
  66. $this->io->section('Creating or updating DHCP Host');
  67. } else {
  68. $this->io->section('Deleting DHCP Host if exists');
  69. }
  70. $this->io->success('RESULT: ' . $this->createHost());
  71. // Crea o elimina si existe el Host CPE
  72. $cpeFixedIP = $this->cablemodem->getCpeFixedIP();
  73. if ($cpeFixedIP) {
  74. $this->io->section('Creating or updating DHCP CPE Host');
  75. $this->io->success('RESULT: ' . $this->createHost('cpe'));
  76. } else {
  77. $this->io->section('Deleting DHCP CPE Host if exists');
  78. $this->io->success('RESULT: ' . $this->deleteHost('cpe'));
  79. }
  80. // Crea o elimina si existe el Host MTA
  81. $mtaFixedIP = $this->cablemodem->getMtaFixedIP();
  82. if ($mtaFixedIP) {
  83. $this->io->section('Creating or updating DHCP MTA Host');
  84. $this->io->success('RESULT: ' . $this->createHost('mta'));
  85. } else {
  86. $this->io->section('Deleting DHCP MTA Host if exists');
  87. $this->io->success('RESULT: ' . $this->deleteHost('mta'));
  88. }
  89. } else {
  90. $output->writeln("<error>Cablemodem mac {$this->mac} not found</error>");
  91. }
  92. foreach ($enabledFilters as $filter_name => $filter) {
  93. $filters->enable($filter_name);
  94. }
  95. }
  96. /**
  97. * @param string $type HostType name Cablemodem | MTA | CPE
  98. *
  99. * @return string
  100. */
  101. private function createHost($type = 'cablemodem')
  102. {
  103. $ws = $this->webservice;
  104. $urlGET = $this->input->getOption('url-get');
  105. // Consulto en DHCP por Host
  106. $host = null;
  107. $url = $ws->buildUrl($urlGET, [
  108. 'mac' => $this->mac,
  109. ]);
  110. if ($hostJSON = $ws->makeGetRequest($url)) {
  111. $hostDecode = json_decode($hostJSON, true);
  112. if (json_last_error() == JSON_ERROR_NONE && is_array($hostDecode)) {
  113. $host = current($hostDecode);
  114. }
  115. }
  116. // Consulto por Host con HostType MTA o CPE relacionado
  117. if ($host && ($type == 'mta' || $type == 'cpe')) {
  118. $hostId = $host['id'];
  119. $url = $ws->buildUrl($urlGET, [
  120. 'host' => $hostId,
  121. 'hostType' => $this->getIdHostType($type),
  122. ]);
  123. if ($hostJSON = $ws->makeGetRequest($url)) {
  124. $hostDecode = json_decode($hostJSON, true);
  125. if (json_last_error() == JSON_ERROR_NONE && is_array($hostDecode)) {
  126. $host = current($hostDecode);
  127. }
  128. }
  129. if (!isset($hostId)) {
  130. $this->io->error("No existe el hostType {$type} en DHCP");
  131. return;
  132. }
  133. }
  134. // Creo, edito o elimino dependiendo los parámetros
  135. $method = HttpRequestInterface::METHOD_POST;
  136. if ($this->input->getOption('delete') == true) {
  137. $method = HttpRequestInterface::METHOD_DELETE;
  138. } elseif ($host) {
  139. $this->io->section('Updating');
  140. $method = HttpRequestInterface::METHOD_PUT;
  141. }
  142. $fixedIP = $this->cablemodem->getFixedIP();
  143. $mtaFixedIP = $this->cablemodem->getMtaFixedIP();
  144. $cpeFixedIP = $this->cablemodem->getCpeFixedIP();
  145. $options = isset($host['options']) ? $host['options'] : [];
  146. $data = [
  147. 'mac' => $this->mac,
  148. 'hostType' => $this->getIdHostType($type),
  149. 'state' => 'active',
  150. 'fixed_address' => $fixedIP ?: null,
  151. 'fixedIP' => $fixedIP ? true : false,
  152. ];
  153. if (isset($hostId) && ($type == 'mta' || $type == 'cpe')) {
  154. unset($data['mac']);
  155. $data['host'] = $hostId;
  156. if ($type == 'mta') {
  157. $data['fixed_address'] = $mtaFixedIP ?: null;
  158. $data['fixedIP'] = $mtaFixedIP ? true : false;
  159. }
  160. if ($type == 'cpe') {
  161. $data['fixed_address'] = $cpeFixedIP ?: null;
  162. $data['fixedIP'] = $cpeFixedIP ? true : false;
  163. }
  164. }
  165. $dhcpOptions = $this->cablemodem->getDHCPOptions();
  166. $data = array_merge($data, $dhcpOptions);
  167. $this->io->text('DATA: ' . json_encode($data));
  168. return $ws->makeGetRequest($this->getUrlParameter($method, $host), $method, $data);
  169. }
  170. /**
  171. * @param string $type HostType name Cablemodem | MTA | CPE
  172. *
  173. * @return string
  174. */
  175. private function deleteHost($type = 'cablemodem')
  176. {
  177. $ws = $this->webservice;
  178. $urlGET = $this->input->getOption('url-get');
  179. // Consulto en DHCP por Host
  180. $host = null;
  181. $url = $ws->buildUrl($urlGET, [
  182. 'mac' => $this->mac,
  183. ]);
  184. if ($hostJSON = $ws->makeGetRequest($url)) {
  185. $hostDecode = json_decode($hostJSON, true);
  186. if (json_last_error() == JSON_ERROR_NONE && is_array($hostDecode)) {
  187. $host = current($hostDecode);
  188. }
  189. }
  190. // Consulto por Host con HostType MTA o CPE relacionado
  191. $deleteHost = null;
  192. if ($host && ($type == 'mta' || $type == 'cpe')) {
  193. $hostId = $host['id'];
  194. $url = $ws->buildUrl($urlGET, [
  195. 'host' => $hostId,
  196. 'hostType' => $this->getIdHostType($type),
  197. ]);
  198. if ($hostJSON = $ws->makeGetRequest($url)) {
  199. $hostDecode = json_decode($hostJSON, true);
  200. if (json_last_error() == JSON_ERROR_NONE && is_array($hostDecode)) {
  201. $deleteHost = current($hostDecode);
  202. }
  203. }
  204. }
  205. if (!$deleteHost) {
  206. return null;
  207. }
  208. $method = HttpRequestInterface::METHOD_DELETE;
  209. $data = [
  210. 'hostType' => isset($deleteHost['hostType']) ? $deleteHost['hostType']['id'] : $this->getIdHostType($type),
  211. 'host' => $hostId,
  212. ];
  213. $this->io->text('DATA: ' . json_encode($data));
  214. return $ws->makeGetRequest($this->getUrlParameter($method, $deleteHost), $method, $data);
  215. }
  216. /**
  217. * Retorna una url de DHCP seteada como parámetro según el método http (GET|PUT|DELETE)
  218. *
  219. * @param string $method GET | PUT | DELETE
  220. * @param array $host Host
  221. *
  222. * @return string
  223. */
  224. private function getUrlParameter($method = HttpRequestInterface::METHOD_POST, $host = [])
  225. {
  226. $container = $this->getContainer();
  227. $parameter = 'dhcp_host_post_url';
  228. $url = $this->input->getOption('url-post');
  229. $id = '';
  230. if (isset($host['id'])) {
  231. $id = $host['id'];
  232. }
  233. if ($method == HttpRequestInterface::METHOD_PUT && $id) {
  234. $parameter = 'dhcp_host_put_url';
  235. $url = $this->input->getOption('url-put');
  236. } elseif ($method == HttpRequestInterface::METHOD_DELETE && $id) {
  237. $parameter = 'dhcp_host_del_url';
  238. $url = $this->input->getOption('url-delete');
  239. }
  240. return $container->hasParameter($parameter) ? str_replace('{id}', $id, $container->getParameter($parameter)) : $url;
  241. }
  242. /**
  243. * @param string $name HostType name Cablemodem | MTA | CPE
  244. *
  245. * @return int
  246. */
  247. private function getIdHostType($name = 'cablemodem')
  248. {
  249. $hostType = null;
  250. $container = $this->getContainer();
  251. $parameter = 'dhcp_host_type_get_url';
  252. $url = $container->hasParameter($parameter) ?
  253. $container->getParameter($parameter) :
  254. $this->input->getOption('url-get-hosttype');
  255. $url = $this->webservice->buildUrl($url, [
  256. 'shortname' => $name,
  257. ]);
  258. $hostTypeJSON = $this->webservice->makeGetRequest($url);
  259. if ($hostTypeJSON != '' && !is_null($hostTypeJSON)) {
  260. $hostDecode = json_decode($hostTypeJSON, true);
  261. if (json_last_error() == JSON_ERROR_NONE && is_array($hostDecode)) {
  262. $hostType = current($hostDecode)['id'];
  263. }
  264. }
  265. return $hostType;
  266. }
  267. }