functions.docker.inc.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. function docker($service_name, $action, $post_action = null, $post_fields = null) {
  3. $curl = curl_init();
  4. curl_setopt($curl, CURLOPT_HTTPHEADER,array( 'Content-Type: application/json' ));
  5. switch($action) {
  6. case 'get_id':
  7. curl_setopt($curl, CURLOPT_URL, 'http://dockerapi:8080/containers/json');
  8. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  9. curl_setopt($curl, CURLOPT_POST, 0);
  10. $response = curl_exec($curl);
  11. if ($response === false) {
  12. $err = curl_error($curl);
  13. curl_close($curl);
  14. return $err;
  15. }
  16. else {
  17. curl_close($curl);
  18. $containers = json_decode($response, true);
  19. if (!empty($containers)) {
  20. foreach ($containers as $container) {
  21. if ($container['Config']['Labels']['com.docker.compose.service'] == $service_name) {
  22. return trim($container['Id']);
  23. }
  24. }
  25. }
  26. }
  27. return false;
  28. break;
  29. case 'info':
  30. $container_id = docker($service_name, 'get_id');
  31. if (ctype_xdigit($container_id)) {
  32. curl_setopt($curl, CURLOPT_URL, 'http://dockerapi:8080/containers/' . $container_id . '/json');
  33. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  34. curl_setopt($curl, CURLOPT_POST, 0);
  35. $response = curl_exec($curl);
  36. if ($response === false) {
  37. $err = curl_error($curl);
  38. curl_close($curl);
  39. return $err;
  40. }
  41. else {
  42. curl_close($curl);
  43. if (empty($response)) {
  44. return true;
  45. }
  46. else {
  47. return json_decode($response, true);
  48. }
  49. }
  50. }
  51. else {
  52. return false;
  53. }
  54. break;
  55. case 'post':
  56. if (!empty($post_action)) {
  57. $container_id = docker($service_name, 'get_id');
  58. if (ctype_xdigit($container_id) && ctype_alnum($post_action)) {
  59. curl_setopt($curl, CURLOPT_URL, 'http://dockerapi:8080/containers/' . $container_id . '/' . $post_action);
  60. curl_setopt($curl, CURLOPT_POST, 1);
  61. if (!empty($post_fields)) {
  62. curl_setopt( $curl, CURLOPT_POSTFIELDS, json_encode($post_fields));
  63. }
  64. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  65. $response = curl_exec($curl);
  66. if ($response === false) {
  67. $err = curl_error($curl);
  68. curl_close($curl);
  69. return $err;
  70. }
  71. else {
  72. curl_close($curl);
  73. if (empty($response)) {
  74. return true;
  75. }
  76. else {
  77. return $response;
  78. }
  79. }
  80. }
  81. }
  82. break;
  83. }
  84. }