aggregates.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <malloc.h>
  4. #include <curl/curl.h>
  5. #include "cJSON.h"
  6. #include "curl.h"
  7. #include "compute.h"
  8. #include "keystone.h"
  9. #include "utils.h"
  10. int get_compute_aggregates(struct string *s) {
  11. char ept[2048] = { 0 };
  12. get_interface_endpoint(ept, "compute");
  13. return submit_api_request(s, ept, "/os-aggregates");
  14. }
  15. static int list(int argc, char **argv) {
  16. struct string s;
  17. int err = get_compute_aggregates(&s);
  18. cJSON *response = cJSON_Parse(s.ptr);
  19. cJSON *aggregates = cJSON_GetObjectItem(response, "aggregates");
  20. int n_aggs = cJSON_GetArraySize(aggregates);
  21. enum field {
  22. id, name, az, n_fields
  23. };
  24. char aggregate_info[n_aggs][n_fields][MAX_BUF_SZ];
  25. char *field_name[n_fields] = { "id", "name", "availability_zone" };
  26. enum field this_width[n_fields] = { 0, 0, 0 };
  27. enum field max_width[n_fields] = { 0, 0, 0 };
  28. int agg_ctr = 0;
  29. cJSON *a;
  30. cJSON_ArrayForEach(a, aggregates) {
  31. cJSON *obj[n_fields];
  32. for(enum field fld = 0; fld < n_fields; ++fld) {
  33. obj[fld] = cJSON_GetObjectItem(a, field_name[fld]);
  34. switch(obj[fld]->type) {
  35. case cJSON_Number:
  36. this_width[fld]= strnlen(cJSON_Print(obj[fld]), MAX_BUF_SZ);
  37. sprintf(aggregate_info[agg_ctr][fld], "%d", obj[fld]->valueint);
  38. case cJSON_String:
  39. if(obj[fld]->valuestring != NULL) {
  40. strncpy(aggregate_info[agg_ctr][fld], cJSON_GetStringValue(obj[fld]), MAX_BUF_SZ);
  41. this_width[fld]= strnlen(aggregate_info[agg_ctr][fld], MAX_BUF_SZ);
  42. }
  43. }
  44. if(this_width[fld] > max_width[fld]) {
  45. max_width[fld] = this_width[fld];
  46. }
  47. }
  48. // We need to free the objects in a separate loop or else get a segfault :shrug:
  49. for(enum field fld = 0; fld < n_fields; ++fld) {
  50. if(obj[fld] != NULL) {
  51. cJSON_free(obj[fld]);
  52. }
  53. }
  54. ++agg_ctr;
  55. }
  56. for(agg_ctr = 0; agg_ctr < n_aggs; ++agg_ctr) {
  57. for(enum field fld = 0; fld < n_fields; ++fld) {
  58. printf("%s%*s", fld == 0 ? "" : " ", max_width[fld], aggregate_info[agg_ctr][fld]);
  59. }
  60. printf("\n");
  61. }
  62. if(a != NULL) {
  63. free(a);
  64. }
  65. if(aggregates != NULL) {
  66. free(aggregates);
  67. }
  68. if(response != NULL) {
  69. free(response);
  70. }
  71. if(s.ptr != NULL) {
  72. free(s.ptr);
  73. }
  74. return err;
  75. }
  76. static struct command subcommands[] = {
  77. CMD_DEF(list),
  78. { NULL, NULL }
  79. };
  80. int aggregate(int argc, char **argv) {
  81. common_main(argc, argv, subcommands);
  82. return 0;
  83. }