functions.docker.inc.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. function docker($service_name, $action, $attr1 = null, $attr2 = null, $extra_headers = 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($attr1)) {
  57. $container_id = docker($service_name, 'get_id');
  58. if (ctype_xdigit($container_id) && ctype_alnum($attr1)) {
  59. curl_setopt($curl, CURLOPT_URL, 'http://dockerapi:8080/containers/' . $container_id . '/' . $attr1);
  60. curl_setopt($curl, CURLOPT_POST, 1);
  61. if (!empty($attr2)) {
  62. curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($attr2));
  63. }
  64. if (!empty($extra_headers) && is_array($extra_headers)) {
  65. curl_setopt($curl, CURLOPT_HTTPHEADER, $extra_headers);
  66. }
  67. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  68. $response = curl_exec($curl);
  69. if ($response === false) {
  70. $err = curl_error($curl);
  71. curl_close($curl);
  72. return $err;
  73. }
  74. else {
  75. curl_close($curl);
  76. if (empty($response)) {
  77. return true;
  78. }
  79. else {
  80. return $response;
  81. }
  82. }
  83. }
  84. }
  85. break;
  86. }
  87. }