functions.docker.inc.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. curl_setopt($curl, CURLOPT_TIMEOUT, 4);
  11. $response = curl_exec($curl);
  12. if ($response === false) {
  13. $err = curl_error($curl);
  14. curl_close($curl);
  15. return $err;
  16. }
  17. else {
  18. curl_close($curl);
  19. $containers = json_decode($response, true);
  20. if (!empty($containers)) {
  21. foreach ($containers as $container) {
  22. if ($container['Config']['Labels']['com.docker.compose.service'] == $service_name) {
  23. return trim($container['Id']);
  24. }
  25. }
  26. }
  27. }
  28. return false;
  29. break;
  30. case 'info':
  31. $container_id = docker($service_name, 'get_id');
  32. if (ctype_xdigit($container_id)) {
  33. curl_setopt($curl, CURLOPT_URL, 'http://dockerapi:8080/containers/' . $container_id . '/json');
  34. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  35. curl_setopt($curl, CURLOPT_POST, 0);
  36. curl_setopt($curl, CURLOPT_TIMEOUT, 4);
  37. $response = curl_exec($curl);
  38. if ($response === false) {
  39. $err = curl_error($curl);
  40. curl_close($curl);
  41. return $err;
  42. }
  43. else {
  44. curl_close($curl);
  45. if (empty($response)) {
  46. return true;
  47. }
  48. else {
  49. return json_decode($response, true);
  50. }
  51. }
  52. }
  53. else {
  54. return false;
  55. }
  56. break;
  57. case 'post':
  58. if (!empty($attr1)) {
  59. $container_id = docker($service_name, 'get_id');
  60. if (ctype_xdigit($container_id) && ctype_alnum($attr1)) {
  61. curl_setopt($curl, CURLOPT_URL, 'http://dockerapi:8080/containers/' . $container_id . '/' . $attr1);
  62. curl_setopt($curl, CURLOPT_POST, 1);
  63. curl_setopt($curl, CURLOPT_TIMEOUT, 4);
  64. if (!empty($attr2)) {
  65. curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($attr2));
  66. }
  67. if (!empty($extra_headers) && is_array($extra_headers)) {
  68. curl_setopt($curl, CURLOPT_HTTPHEADER, $extra_headers);
  69. }
  70. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  71. $response = curl_exec($curl);
  72. if ($response === false) {
  73. $err = curl_error($curl);
  74. curl_close($curl);
  75. return $err;
  76. }
  77. else {
  78. curl_close($curl);
  79. if (empty($response)) {
  80. return true;
  81. }
  82. else {
  83. return $response;
  84. }
  85. }
  86. }
  87. }
  88. break;
  89. }
  90. }