872513af9647e0c4234947fdd26fabcd59b2a01f
[sim/o1-interface.git] / ntsimulator / src / ntsimulator-manager / simulator-operations.c
1 /*
2  * simulator-operations.c
3  *
4  *  Created on: Mar 9, 2019
5  *      Author: parallels
6  */
7
8 #include "simulator-operations.h"
9 #include "sysrepo.h"
10 #include "sysrepo/values.h"
11 #include <string.h>
12 #include <math.h>
13 #include <linux/limits.h>
14
15 #include "utils.h"
16
17 #define LINE_BUFSIZE 128
18
19 static  CURL *curl; //share the same curl connection for communicating with the Docker Engine API
20 static  CURL *curl_odl; //share the same curl connection for mounting servers in ODL
21
22 static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
23 {
24   size_t realsize = size * nmemb;
25   struct MemoryStruct *mem = (struct MemoryStruct *)userp;
26
27   char *ptr = realloc(mem->memory, mem->size + realsize + 1);
28   if(ptr == NULL) {
29     /* out of memory! */
30     printf("not enough memory (realloc returned NULL)\n");
31     return 0;
32   }
33
34   mem->memory = ptr;
35   memcpy(&(mem->memory[mem->size]), contents, realsize);
36   mem->size += realsize;
37   mem->memory[mem->size] = 0;
38
39   return realsize;
40 }
41
42 static void set_curl_common_info()
43 {
44         struct curl_slist *chunk = NULL;
45         chunk = curl_slist_append(chunk, "Content-Type: application/json");
46         chunk = curl_slist_append(chunk, "Accept: application/json");
47
48     curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
49
50         curl_easy_setopt(curl, CURLOPT_UNIX_SOCKET_PATH, "/var/run/docker.sock");
51
52         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
53     curl_easy_setopt(curl_odl, CURLOPT_CONNECTTIMEOUT, 2L); // seconds timeout for a connection
54     curl_easy_setopt(curl_odl, CURLOPT_TIMEOUT, 5L); //seconds timeout for an operation
55
56     curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
57 }
58
59 static void set_curl_common_info_odl()
60 {
61         struct curl_slist *chunk = NULL;
62         chunk = curl_slist_append(chunk, "Content-Type: application/xml");
63         chunk = curl_slist_append(chunk, "Accept: application/xml");
64
65     curl_easy_setopt(curl_odl, CURLOPT_HTTPHEADER, chunk);
66
67     curl_easy_setopt(curl_odl, CURLOPT_CONNECTTIMEOUT, 2L); // seconds timeout for a connection
68     curl_easy_setopt(curl_odl, CURLOPT_TIMEOUT, 5L); //seconds timeout for an operation
69
70     curl_easy_setopt(curl_odl, CURLOPT_VERBOSE, 1L);
71 }
72
73 static cJSON* get_docker_container_bindings(void)
74 {
75         struct MemoryStruct curl_response_mem;
76
77         curl_response_mem.memory = malloc(1);  /* will be grown as needed by the realloc above */
78         curl_response_mem.size = 0;    /* no data at this point */
79
80         CURLcode res;
81
82         curl_easy_reset(curl);
83         set_curl_common_info();
84
85         char url[100];
86         sprintf(url, "http:/v%s/containers/NTS_Manager/json", getenv("DOCKER_ENGINE_VERSION"));
87
88         curl_easy_setopt(curl, CURLOPT_URL, url);
89
90     curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "");
91     curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
92
93         curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&curl_response_mem);
94
95         res = curl_easy_perform(curl);
96
97         if (res != CURLE_OK)
98         {
99                 return NULL;
100         }
101         else
102         {
103                 cJSON *json_response = cJSON_Parse(curl_response_mem.memory);
104
105                 printf("%lu bytes retrieved\n", (unsigned long)curl_response_mem.size);
106
107                 if (json_response == NULL)
108                 {
109                         printf("Could not parse JSON response for url=\"%s\"\n", url);
110                         return NULL;
111                 }
112
113                 cJSON *hostConfig = cJSON_GetObjectItemCaseSensitive(json_response, "HostConfig");
114
115                 if (hostConfig == NULL)
116                 {
117                         printf("Could not get HostConfig object\n");
118                         return NULL;
119                 }
120
121                 cJSON *binds = cJSON_GetObjectItemCaseSensitive(hostConfig, "Binds");
122
123                 if (binds == NULL)
124                 {
125                         printf("Could not get Binds object\n");
126                         return NULL;
127                 }
128
129                 cJSON *bindsCopy = cJSON_Duplicate(binds, 1);
130
131             cJSON_Delete(json_response);
132
133                 return bindsCopy;
134         }
135
136         return NULL;
137 }
138
139 static char* create_docker_container_curl(int base_netconf_port, cJSON* managerBinds)
140 {
141         if (managerBinds == NULL)
142         {
143                 printf("Could not retrieve JSON object: Binds\n");
144                 return NULL;
145         }
146         cJSON *binds = cJSON_Duplicate(managerBinds, 1);
147
148         struct MemoryStruct curl_response_mem;
149
150         curl_response_mem.memory = malloc(1);  /* will be grown as needed by the realloc above */
151         curl_response_mem.size = 0;    /* no data at this point */
152
153         CURLcode res;
154
155         curl_easy_reset(curl);
156         set_curl_common_info();
157
158         char url[100];
159         sprintf(url, "http:/v%s/containers/create", getenv("DOCKER_ENGINE_VERSION"));
160
161         // the docker image name to be used is defined in the Dockerfile of the NTS Manager,
162         // under the MODELS_IMAGE env variable
163         char models_var[50];
164         sprintf(models_var, "%s", getenv("MODELS_IMAGE"));
165
166         curl_easy_setopt(curl, CURLOPT_URL, url);
167
168     cJSON *postDataJson = cJSON_CreateObject();
169
170     if (cJSON_AddStringToObject(postDataJson, "Image", models_var) == NULL)
171         {
172         printf("Could not create JSON object: Image\n");
173                 return NULL;
174         }
175
176     cJSON *hostConfig = cJSON_CreateObject();
177     if (hostConfig == NULL)
178         {
179         printf("Could not create JSON object: HostConfig\n");
180                 return NULL;
181         }
182
183     cJSON_AddItemToObject(postDataJson, "HostConfig", hostConfig);
184
185     cJSON *portBindings = cJSON_CreateObject();
186     if (portBindings == NULL)
187         {
188         printf("Could not create JSON object: PortBindings\n");
189                 return NULL;
190         }
191
192     cJSON_AddItemToObject(hostConfig, "PortBindings", portBindings);
193
194     for (int i = 0; i < NETCONF_CONNECTIONS_PER_DEVICE; ++i)
195     {
196         cJSON *port = cJSON_CreateArray();
197                 if (port == NULL)
198                 {
199                 printf("Could not create JSON object: port\n");
200                         return NULL;
201                 }
202
203                 char dockerContainerPort[20];
204                 sprintf(dockerContainerPort, "%d/tcp", 830 + i);
205
206             cJSON_AddItemToObject(portBindings, dockerContainerPort, port);
207
208             cJSON *hostPort = cJSON_CreateObject();
209             if (hostPort == NULL)
210                 {
211                 printf("Could not create JSON object: HostPort\n");
212                         return NULL;
213                 }
214
215             char dockerHostPort[10];
216             sprintf(dockerHostPort, "%d", base_netconf_port + i);
217             if (cJSON_AddStringToObject(hostPort, "HostPort", dockerHostPort) == NULL)
218             {
219                 printf("Could not create JSON object: HostPortString\n");
220                 return NULL;
221             }
222             if (cJSON_AddStringToObject(hostPort, "HostIp", getenv("NTS_IP")) == NULL)
223             {
224                 printf("Could not create JSON object: HostIpString\n");
225                 return NULL;
226             }
227
228             cJSON_AddItemToArray(port, hostPort);
229     }
230
231     cJSON *labels = cJSON_CreateObject();
232     if (labels == NULL)
233         {
234         printf("Could not create JSON object: Labels\n");
235                 return NULL;
236         }
237
238     cJSON_AddItemToObject(postDataJson, "Labels", labels);
239
240     if (cJSON_AddStringToObject(labels, "NTS", "") == NULL)
241     {
242         printf("Could not create JSON object: NTS\n");
243         return NULL;
244     }
245
246     cJSON *env_variables_array = cJSON_CreateArray();
247     if (env_variables_array == NULL)
248         {
249         printf("Could not create JSON object: Env array\n");
250                 return NULL;
251         }
252
253     cJSON_AddItemToObject(postDataJson, "Env", env_variables_array);
254
255     char environment_var[50];
256     sprintf(environment_var, "NTS_IP=%s", getenv("NTS_IP"));
257
258     cJSON *env_var_obj = cJSON_CreateString(environment_var);
259     if (env_var_obj == NULL)
260         {
261         printf("Could not create JSON object: Env array object NTS_IP\n");
262                 return NULL;
263         }
264     cJSON_AddItemToArray(env_variables_array, env_var_obj);
265
266     sprintf(environment_var, "NETCONF_BASE=%d", base_netconf_port);
267     cJSON *env_var_obj_2 = cJSON_CreateString(environment_var);
268     if (env_var_obj_2 == NULL)
269         {
270         printf("Could not create JSON object: Env array object NETCONF_BASE\n");
271                 return NULL;
272         }
273     cJSON_AddItemToArray(env_variables_array, env_var_obj_2);
274
275         char scripts_dir[200];
276         sprintf(scripts_dir, "SCRIPTS_DIR=%s", getenv("SCRIPTS_DIR"));
277         cJSON *env_var_obj_3 = cJSON_CreateString(scripts_dir);
278         if (env_var_obj_3 == NULL)
279         {
280                 printf("Could not create JSON object: Env array object SCRIPTS_DIR\n");
281                 return NULL;
282         }
283         cJSON_AddItemToArray(env_variables_array, env_var_obj_3);
284
285     cJSON_AddItemToObject(hostConfig, "Binds", binds);
286
287     char *post_data_string = NULL;
288
289     post_data_string = cJSON_PrintUnformatted(postDataJson);
290
291     printf("Post data JSON:\n%s\n", post_data_string);
292
293     if (postDataJson != NULL)
294     {
295         cJSON_Delete(postDataJson);
296     }
297
298     curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data_string);
299
300         curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&curl_response_mem);
301
302         res = curl_easy_perform(curl);
303
304         if (res != CURLE_OK)
305         {
306                 return NULL;
307         }
308         else
309         {
310                 cJSON *json_response = cJSON_Parse(curl_response_mem.memory);
311                 const cJSON *container_id = NULL;
312
313                 printf("%lu bytes retrieved\n", (unsigned long)curl_response_mem.size);
314
315                 container_id = cJSON_GetObjectItemCaseSensitive(json_response, "Id");
316
317                 if (cJSON_IsString(container_id) && (container_id->valuestring != NULL))
318                 {
319                         printf("Container id: \"%s\"\n", container_id->valuestring);
320
321                         char container_id_short[13];
322
323                         memset(container_id_short, '\0', sizeof(container_id_short));
324                         strncpy(container_id_short, container_id->valuestring, 12);
325
326                         printf("Container id short: \"%s\"\n", container_id_short);
327
328                     cJSON_Delete(json_response);
329                         return strdup(container_id_short);
330                 }
331
332             cJSON_Delete(json_response);
333         }
334
335         return NULL;
336 }
337
338 static int start_docker_container_curl(char *container_id)
339 {
340         struct MemoryStruct curl_response_mem;
341
342         curl_response_mem.memory = malloc(1);  /* will be grown as needed by the realloc above */
343         curl_response_mem.size = 0;    /* no data at this point */
344
345         CURLcode res;
346
347         curl_easy_reset(curl);
348         set_curl_common_info();
349
350         char url[100];
351         sprintf(url, "http:/v%s/containers/%s/start", getenv("DOCKER_ENGINE_VERSION"), container_id);
352
353         curl_easy_setopt(curl, CURLOPT_URL, url);
354
355     curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "");
356
357         curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&curl_response_mem);
358
359         res = curl_easy_perform(curl);
360
361         if (res != CURLE_OK)
362         {
363                 return SR_ERR_OPERATION_FAILED;
364         }
365         else
366         {
367                 printf("Container %s started successfully!\n", container_id);
368         }
369
370         return SR_ERR_OK;
371 }
372
373 static int kill_and_remove_docker_container_curl(char *container_id)
374 {
375         struct MemoryStruct curl_response_mem;
376
377         curl_response_mem.memory = malloc(1);  /* will be grown as needed by the realloc above */
378         curl_response_mem.size = 0;    /* no data at this point */
379
380         CURLcode res;
381
382         curl_easy_reset(curl);
383         set_curl_common_info();
384
385         char url[100];
386         sprintf(url, "http:/v%s/containers/%s?force=true", getenv("DOCKER_ENGINE_VERSION"), container_id);
387
388         curl_easy_setopt(curl, CURLOPT_URL, url);
389
390     curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "");
391     curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
392
393         curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&curl_response_mem);
394
395         res = curl_easy_perform(curl);
396
397         if (res != CURLE_OK)
398         {
399                 return SR_ERR_OPERATION_FAILED;
400         }
401         else
402         {
403                 printf("Container %s removed successfully!\n", container_id);
404         }
405
406         return SR_ERR_OK;
407 }
408
409 static int send_mount_device_instance_ssh(char *url, char *credentials, char *device_name, int device_port)
410 {
411         CURLcode res;
412
413         curl_easy_reset(curl_odl);
414         set_curl_common_info_odl();
415
416         char url_for_curl[200];
417         sprintf(url_for_curl, "%s%s_%d", url, device_name, device_port);
418
419         curl_easy_setopt(curl_odl, CURLOPT_URL, url_for_curl);
420
421         char post_data_xml[1000];
422
423         sprintf(post_data_xml,
424                         "<node xmlns=\"urn:TBD:params:xml:ns:yang:network-topology\">"
425                         "<node-id>%s_%d</node-id>"
426                         "<host xmlns=\"urn:opendaylight:netconf-node-topology\">%s</host>"
427                         "<port xmlns=\"urn:opendaylight:netconf-node-topology\">%d</port>"
428                         "<username xmlns=\"urn:opendaylight:netconf-node-topology\">%s</username>"
429                         "<password xmlns=\"urn:opendaylight:netconf-node-topology\">%s</password>"
430                         "<tcp-only xmlns=\"urn:opendaylight:netconf-node-topology\">false</tcp-only>"
431                         "<keepalive-delay xmlns=\"urn:opendaylight:netconf-node-topology\">120</keepalive-delay>"
432                         "</node>",
433                         device_name, device_port, getenv("NTS_IP"), device_port, "netconf", "netconf");
434
435         printf("Post data:\n%s\n", post_data_xml);
436
437         curl_easy_setopt(curl_odl, CURLOPT_POSTFIELDS, post_data_xml);
438     curl_easy_setopt(curl_odl, CURLOPT_CUSTOMREQUEST, "PUT");
439     curl_easy_setopt(curl_odl, CURLOPT_USERPWD, credentials);
440
441         res = curl_easy_perform(curl_odl);
442         if (res != CURLE_OK)
443         {
444                 printf("cURL failed to url=%s\n", url_for_curl);
445         }
446
447         long http_response_code = 0;
448         curl_easy_getinfo (curl_odl, CURLINFO_RESPONSE_CODE, &http_response_code);
449         if (http_response_code >= 200 && http_response_code <= 226 && http_response_code != CURLE_ABORTED_BY_CALLBACK)
450         {
451                 printf("cURL succeeded to url=%s\n", url_for_curl);
452         }
453         else
454         {
455             printf("cURL to url=%s failed with code=%ld\n", url_for_curl, http_response_code);
456                 return SR_ERR_OPERATION_FAILED;
457         }
458
459         return SR_ERR_OK;
460 }
461
462 static int send_mount_device_instance_tls(char *url, char *credentials, char *device_name, int device_port)
463 {
464         CURLcode res;
465
466         curl_easy_reset(curl_odl);
467         set_curl_common_info_odl();
468
469         char url_for_curl[200];
470         sprintf(url_for_curl, "%s%s_%d", url, device_name, device_port);
471
472         curl_easy_setopt(curl_odl, CURLOPT_URL, url_for_curl);
473
474         char post_data_xml[1000];
475
476         sprintf(post_data_xml,
477                         "<node xmlns=\"urn:TBD:params:xml:ns:yang:network-topology\">"
478                         "<protocol xmlns=\"urn:opendaylight:netconf-node-topology\">"
479                         "<name>TLS</name>"
480                         "</protocol>"
481                         "<node-id>%s_%d</node-id>"
482                         "<host xmlns=\"urn:opendaylight:netconf-node-topology\">%s</host>"
483                         "<key-based xmlns=\"urn:opendaylight:netconf-node-topology\">"
484                         "<username>%s</username>"
485                         "<key-id>device-key</key-id>"
486                         "</key-based>"
487                         "<port xmlns=\"urn:opendaylight:netconf-node-topology\">%d</port>"
488                         "<tcp-only xmlns=\"urn:opendaylight:netconf-node-topology\">false</tcp-only>"
489                         "<keepalive-delay xmlns=\"urn:opendaylight:netconf-node-topology\">120</keepalive-delay>"
490                         "</node>",
491                         device_name, device_port, getenv("NTS_IP"), "netconf", device_port);
492
493         printf("Post data:\n%s\n", post_data_xml);
494
495         curl_easy_setopt(curl_odl, CURLOPT_POSTFIELDS, post_data_xml);
496     curl_easy_setopt(curl_odl, CURLOPT_CUSTOMREQUEST, "PUT");
497     curl_easy_setopt(curl_odl, CURLOPT_USERPWD, credentials);
498
499         res = curl_easy_perform(curl_odl);
500         if (res != CURLE_OK)
501         {
502                 printf("cURL failed to url=%s\n", url_for_curl);
503         }
504
505         long http_response_code = 0;
506         curl_easy_getinfo (curl_odl, CURLINFO_RESPONSE_CODE, &http_response_code);
507         if (http_response_code >= 200 && http_response_code <= 226 && http_response_code != CURLE_ABORTED_BY_CALLBACK)
508         {
509                 printf("cURL succeeded to url=%s\n", url_for_curl);
510         }
511         else
512         {
513             printf("cURL to url=%s failed with code=%ld\n", url_for_curl, http_response_code);
514                 return SR_ERR_OPERATION_FAILED;
515         }
516
517         return SR_ERR_OK;
518 }
519
520 static int send_unmount_device_instance(char *url, char *credentials, char *device_name, int device_port)
521 {
522         CURLcode res;
523
524         curl_easy_reset(curl_odl);
525         set_curl_common_info_odl();
526
527         char url_for_curl[200];
528         sprintf(url_for_curl, "%s%s_%d", url, device_name, device_port);
529
530         curl_easy_setopt(curl_odl, CURLOPT_URL, url_for_curl);
531
532         curl_easy_setopt(curl_odl, CURLOPT_POSTFIELDS, "");
533         curl_easy_setopt(curl_odl, CURLOPT_CUSTOMREQUEST, "DELETE");
534         curl_easy_setopt(curl_odl, CURLOPT_USERPWD, credentials);
535
536         res = curl_easy_perform(curl_odl);
537         if (res != CURLE_OK)
538         {
539                 printf("cURL failed to url=%s\n", url_for_curl);
540         }
541
542         long http_response_code = 0;
543         curl_easy_getinfo (curl_odl, CURLINFO_RESPONSE_CODE, &http_response_code);
544         if (http_response_code == 200 && http_response_code != CURLE_ABORTED_BY_CALLBACK)
545         {
546                 printf("cURL succeeded to url=%s\n", url_for_curl);
547         }
548         else
549         {
550                 printf("cURL to url=%s failed with code=%ld\n", url_for_curl, http_response_code);
551                 return SR_ERR_OPERATION_FAILED;
552         }
553
554
555         return SR_ERR_OK;
556 }
557
558
559 static int send_mount_device(device_t *current_device, controller_t controller_details)
560 {
561         int rc = SR_ERR_OK;
562         bool is_mounted = true;
563
564         //This is where we hardcoded: 7 devices will have SSH connections and 3 devices will have TLS connections
565         for (int port = 0; port < NETCONF_CONNECTIONS_PER_DEVICE - 3; ++port)
566         {
567                 rc = send_mount_device_instance_ssh(controller_details.url, controller_details.credentials,
568                                 current_device->device_id, current_device->netconf_port + port);
569                 if (rc != SR_ERR_OK)
570                 {
571                         is_mounted = false;
572                 }
573         }
574         for (int port = NETCONF_CONNECTIONS_PER_DEVICE - 3; port < NETCONF_CONNECTIONS_PER_DEVICE; ++port)
575         {
576                 rc = send_mount_device_instance_tls(controller_details.url, controller_details.credentials,
577                                 current_device->device_id, current_device->netconf_port + port);
578                 if (rc != SR_ERR_OK)
579                 {
580                         is_mounted = false;
581                 }
582         }
583
584         current_device->is_mounted = is_mounted;
585
586         return SR_ERR_OK;
587 }
588
589 static int send_unmount_device(device_t *current_device, controller_t controller_details)
590 {
591         int rc = SR_ERR_OK;
592
593         for (int port = 0; port < NETCONF_CONNECTIONS_PER_DEVICE; ++port)
594         {
595                 rc = send_unmount_device_instance(controller_details.url, controller_details.credentials,
596                                 current_device->device_id, current_device->netconf_port + port);
597                 if (rc != SR_ERR_OK)
598                 {
599                         printf("Could not send unmount for ODL with url=\"%s\", for device=\"%s\" and port=%d\n",
600                                         controller_details.url, current_device->device_id, current_device->netconf_port);
601                 }
602         }
603         current_device->is_mounted = false;
604
605         return SR_ERR_OK;
606 }
607
608 device_stack_t *new_device_stack(void)
609 {
610         device_stack_t *stack = malloc(sizeof(*stack));
611
612         if (stack) {
613                 stack->head = NULL;
614                 stack->stack_size = 0;
615         }
616         return stack;
617 }
618
619 void push_device(device_stack_t *theStack, char *dev_id, int port)
620 {
621         device_t *new_dev = malloc(sizeof(*new_dev));
622
623         if (new_dev) {
624                 new_dev->device_id = strdup(dev_id);
625                 new_dev->netconf_port = port;
626                 new_dev->is_mounted = false;
627                 new_dev->operational_state = strdup("not-specified");
628
629                 new_dev->next = theStack->head;
630
631                 theStack->head = new_dev;
632                 theStack->stack_size++;
633         }
634 }
635
636 void pop_device(device_stack_t *theStack)
637 {
638         if (theStack && theStack->head) {
639                 device_t *temp = theStack->head;
640                 theStack->head = theStack->head->next;
641
642                 free(temp->device_id);
643                 free(temp->operational_state);
644                 free(temp);
645                 theStack->stack_size--;
646         }
647 }
648
649 int get_netconf_port_next(device_stack_t *theStack)
650 {
651         if (theStack && theStack->stack_size > 0) {
652                 return theStack->head->netconf_port + NETCONF_CONNECTIONS_PER_DEVICE;
653         }
654
655         return get_netconf_port_base();
656 }
657
658 int get_netconf_port_base()
659 {
660         int netconf_port_base = 0, rc;
661
662         char *netconf_base_string = getenv("NETCONF_BASE");
663
664         if (netconf_base_string != NULL)
665         {
666                 rc = sscanf(netconf_base_string, "%d", &netconf_port_base);
667                 if (rc != 1)
668                 {
669                         printf("Could not get the NETCONF_BASE port! Using the default 30.000...\n");
670                         netconf_port_base = 30000;
671                 }
672         }
673
674         return netconf_port_base;
675 }
676
677
678 char *get_id_last_device(device_stack_t *theStack)
679 {
680         if (theStack && theStack->head) {
681                 return theStack->head->device_id;
682         }
683         return NULL;
684 }
685
686 int get_current_number_of_mounted_devices(device_stack_t *theStack)
687 {
688         int mounted_devices = 0;
689
690         if (theStack && theStack->head)
691         {
692                 device_t *current_device = theStack->head;
693
694                 while (current_device != NULL)
695                 {
696                         if (current_device->is_mounted)
697                         {
698                                 mounted_devices++;
699                         }
700                         current_device = current_device->next;
701                 }
702         }
703
704         return mounted_devices;
705 }
706
707 int get_current_number_of_devices(device_stack_t *theStack)
708 {
709         struct MemoryStruct curl_response_mem;
710
711         curl_response_mem.memory = malloc(1);  /* will be grown as needed by the realloc above */
712         curl_response_mem.size = 0;    /* no data at this point */
713
714         CURLcode res;
715
716         curl_easy_reset(curl);
717         set_curl_common_info();
718
719         char url[100];
720         sprintf(url, "http:/v%s/containers/json?all=true&filters={\"label\":[\"NTS\"],\"status\":[\"running\"]}",
721                         getenv("DOCKER_ENGINE_VERSION"));
722
723         curl_easy_setopt(curl, CURLOPT_URL, url);
724
725         curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "");
726         curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
727
728         curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&curl_response_mem);
729
730         res = curl_easy_perform(curl);
731
732         if (res != CURLE_OK)
733         {
734                 return SR_ERR_OPERATION_FAILED;
735         }
736         else
737         {
738                 cJSON *json_response = cJSON_Parse(curl_response_mem.memory);
739
740                 printf("%lu bytes retrieved\n", (unsigned long)curl_response_mem.size);
741
742                 if (json_response == NULL || !cJSON_IsArray(json_response))
743                 {
744                         printf("Could not parse JSON response for url=\"%s\"\n", url);
745                         return SR_ERR_OPERATION_FAILED;
746                 }
747
748                 int num_of_devices = cJSON_GetArraySize(json_response);
749                 cJSON_Delete(json_response);
750
751                 return num_of_devices;
752         }
753
754         return 0;
755 }
756
757 static int set_operational_state_of_device(device_stack_t *theStack, char *device_id, char *operational_state)
758 {
759         if (theStack && theStack->head)
760         {
761                 device_t *current_device = theStack->head;
762
763                 while (current_device != NULL)
764                 {
765                         if (strcmp(current_device->device_id, device_id) == 0)
766                         {
767                                 free(current_device->operational_state);
768                                 current_device->operational_state = strdup(operational_state);
769
770                                 return SR_ERR_OK;
771                         }
772
773                         current_device = current_device->next;
774                 }
775         }
776
777         printf("Could not find device with uuid=\"%s\"\n", device_id);
778         return SR_ERR_OPERATION_FAILED;
779 }
780
781 char* get_docker_container_operational_state(device_stack_t *theStack, char *container_id)
782 {
783         if (theStack && theStack->head)
784         {
785                 device_t *current_device = theStack->head;
786
787                 while (current_device != NULL)
788                 {
789                         if (strcmp(current_device->device_id, container_id) == 0)
790                         {
791                                 return current_device->operational_state;
792                         }
793
794                         current_device = current_device->next;
795                 }
796         }
797
798         return NULL;
799 }
800
801 int start_device(device_stack_t *theStack)
802 {
803         int rc = SR_ERR_OK;
804         static cJSON* managerBindings = NULL;
805
806         if (managerBindings == NULL)
807         {
808                 managerBindings = get_docker_container_bindings();
809         }
810
811         int netconf_base = get_netconf_port_next(theStack);
812
813         char *dev_id = create_docker_container_curl(netconf_base, managerBindings);
814
815         push_device(theStack, dev_id, netconf_base);
816
817         rc = start_docker_container_curl(dev_id);
818         if (rc != SR_ERR_OK)
819         {
820                 printf("Could not start device with device_id=\"%s\"\n", dev_id);
821         }
822
823         if (dev_id) {
824                 free(dev_id);
825         }
826
827         return SR_ERR_OK;
828 }
829
830 int _init_curl()
831 {
832         curl = curl_easy_init();
833
834         if (curl == NULL) {
835                 printf("cURL initialization error! Aborting call!\n");
836                 return SR_ERR_OPERATION_FAILED;
837         }
838
839         return SR_ERR_OK;
840 }
841
842 int cleanup_curl()
843 {
844         if (curl != NULL)
845         {
846                 curl_easy_cleanup(curl);
847         }
848
849         return SR_ERR_OK;
850 }
851
852 int _init_curl_odl()
853 {
854         curl_odl = curl_easy_init();
855
856         if (curl_odl == NULL) {
857                 printf("cURL initialization error! Aborting call!\n");
858                 return SR_ERR_OPERATION_FAILED;
859         }
860
861         return SR_ERR_OK;
862 }
863
864 int cleanup_curl_odl()
865 {
866         if (curl_odl != NULL)
867         {
868                 curl_easy_cleanup(curl_odl);
869         }
870
871         return SR_ERR_OK;
872 }
873
874 int stop_device(device_stack_t *theStack)
875 {
876         int rc = SR_ERR_OK;
877         char *last_id = get_id_last_device(theStack);
878
879         rc = kill_and_remove_docker_container_curl(last_id);
880         if (rc != SR_ERR_OK)
881         {
882                 printf("Could not kill and remove docker container with uuid=\"%s\"\n", last_id);
883         }
884
885         pop_device(theStack);
886
887         return SR_ERR_OK;
888 }
889
890 int mount_device(device_stack_t *theStack, controller_t controller_details)
891 {
892         int rc;
893
894         if (theStack && theStack->head)
895         {
896                 device_t *current_device = theStack->head;
897                 while (current_device != NULL && current_device->is_mounted == true)
898                 {
899                         printf("Device \"%s\" is already mounted, skipping...\n", current_device->device_id);
900                         current_device = current_device->next;
901                 }
902
903                 if (current_device != NULL)
904                 {
905                         printf("Sending mount device for device \"%s\"...\n", current_device->device_id);
906                         rc = send_mount_device(current_device, controller_details);
907                         if (rc != SR_ERR_OK)
908                         {
909                                 return SR_ERR_OPERATION_FAILED;
910                         }
911                 }
912         }
913
914         return SR_ERR_OK;
915 }
916
917 int unmount_device(device_stack_t *theStack, controller_t controller_list)
918 {
919         int rc;
920
921         if (theStack && theStack->head)
922         {
923                 device_t *current_device = theStack->head;
924                 while (current_device != NULL && current_device->is_mounted == false)
925                 {
926                         printf("Device \"%s\" is already unmounted, skipping...\n", current_device->device_id);
927                         current_device = current_device->next;
928                 }
929
930                 if (current_device != NULL)
931                 {
932                         printf("Sending unmount device for device \"%s\"...\n", current_device->device_id);
933                         rc = send_unmount_device(current_device, controller_list);
934                         if (rc != SR_ERR_OK)
935                         {
936                                 return SR_ERR_OPERATION_FAILED;
937                         }
938                 }
939         }
940
941         return SR_ERR_OK;
942 }
943
944 int get_docker_containers_operational_state_curl(device_stack_t *theStack)
945 {
946         int rc = SR_ERR_OK;
947         struct MemoryStruct curl_response_mem;
948
949         curl_response_mem.memory = malloc(1);  /* will be grown as needed by the realloc above */
950         curl_response_mem.size = 0;    /* no data at this point */
951
952         CURLcode res;
953
954         curl_easy_reset(curl);
955         set_curl_common_info();
956
957         char url[100];
958         sprintf(url, "http:/v%s/containers/json?all=true&filters={\"label\":[\"NTS\"]}", getenv("DOCKER_ENGINE_VERSION"));
959
960         curl_easy_setopt(curl, CURLOPT_URL, url);
961
962     curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "");
963     curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
964
965         curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&curl_response_mem);
966
967         res = curl_easy_perform(curl);
968
969         if (res != CURLE_OK)
970         {
971                 return SR_ERR_OPERATION_FAILED;
972         }
973         else
974         {
975                 cJSON *json_response = cJSON_Parse(curl_response_mem.memory);
976                 const cJSON *container = NULL;
977
978                 printf("%lu bytes retrieved\n", (unsigned long)curl_response_mem.size);
979
980                 if (json_response == NULL || !cJSON_IsArray(json_response))
981                 {
982                         printf("Could not parse JSON response for url=\"%s\"\n", url);
983                         return SR_ERR_OPERATION_FAILED;
984                 }
985
986             cJSON_ArrayForEach(container, json_response)
987             {
988                 cJSON *container_id_long = cJSON_GetObjectItemCaseSensitive(container, "Id");
989                 cJSON *state = cJSON_GetObjectItemCaseSensitive(container, "State");
990
991                         if (cJSON_IsString(container_id_long) && (container_id_long->valuestring != NULL))
992                         {
993                                 char container_id_short[13];
994
995                                 memset(container_id_short, '\0', sizeof(container_id_short));
996                                 strncpy(container_id_short, container_id_long->valuestring, 12);
997
998                                 if (cJSON_IsString(state) && (state->valuestring != NULL))
999                                 {
1000                                         rc = set_operational_state_of_device(theStack, container_id_short, state->valuestring);
1001                                         if (rc != SR_ERR_OK)
1002                                         {
1003                                                 printf("Could not set the operational state for the device with uuid=\"%s\"\n", container_id_short);
1004                                         }
1005                                 }
1006                         }
1007             }
1008
1009             cJSON_Delete(json_response);
1010         }
1011
1012         return SR_ERR_OK;
1013 }
1014
1015 char* get_docker_container_resource_stats(device_stack_t *theStack)
1016 {
1017         char line[LINE_BUFSIZE];
1018         int linenr;
1019         FILE *pipe;
1020
1021         /* Get a pipe where the output from the scripts comes in */
1022         char script[200];
1023         sprintf(script, "%s/docker_stats.sh", getenv("SCRIPTS_DIR"));
1024
1025         pipe = popen(script, "r");
1026         if (pipe == NULL) {  /* check for errors */
1027                 printf("Could not open script.\n");
1028                 return NULL;        /* return with exit code indicating error */
1029         }
1030
1031         /* Read script output from the pipe line by line */
1032         linenr = 1;
1033         while (fgets(line, LINE_BUFSIZE, pipe) != NULL) {
1034                 printf("Script output line %d: %s", linenr, line);
1035                 ++linenr;
1036
1037                 pclose(pipe); /* Close the pipe */
1038                 return strdup(line);
1039         }
1040
1041         /* Once here, out of the loop, the script has ended. */
1042         pclose(pipe); /* Close the pipe */
1043         return NULL;     /* return with exit code indicating success. */
1044 }
1045
1046 int notification_delay_period_changed(int period)
1047 {
1048         char *stringConfiguration = readConfigFileInString();
1049
1050         if (stringConfiguration == NULL)
1051         {
1052                 printf("Could not read configuration file!\n");
1053                 return SR_ERR_OPERATION_FAILED;
1054         }
1055
1056         cJSON *jsonConfig = cJSON_Parse(stringConfiguration);
1057         if (jsonConfig == NULL)
1058         {
1059                 free(stringConfiguration);
1060                 const char *error_ptr = cJSON_GetErrorPtr();
1061                 if (error_ptr != NULL)
1062                 {
1063                         fprintf(stderr, "Could not parse JSON configuration! Error before: %s\n", error_ptr);
1064                 }
1065                 return SR_ERR_OPERATION_FAILED;
1066         }
1067         //we don't need the string anymore
1068         free(stringConfiguration);
1069         stringConfiguration = NULL;
1070
1071         cJSON *notifConfig = cJSON_GetObjectItemCaseSensitive(jsonConfig, "notification-config");
1072         if (!cJSON_IsObject(notifConfig))
1073         {
1074                 printf("Configuration JSON is not as expected: notification-config is not an object");
1075                 free(jsonConfig);
1076                 return SR_ERR_OPERATION_FAILED;
1077         }
1078
1079         cJSON *faultNotifDelay = cJSON_GetObjectItemCaseSensitive(notifConfig, "fault-notification-delay-period");
1080         if (!cJSON_IsNumber(faultNotifDelay))
1081         {
1082                 printf("Configuration JSON is not as expected: fault-notification-delay-period is not an object");
1083                 free(jsonConfig);
1084                 return SR_ERR_OPERATION_FAILED;
1085         }
1086
1087         //we set the value of the fault-notification-delay-period object
1088         cJSON_SetNumberValue(faultNotifDelay, period);
1089
1090         //writing the new JSON to the configuration file
1091         stringConfiguration = cJSON_Print(jsonConfig);
1092         writeConfigFile(stringConfiguration);
1093
1094         free(jsonConfig);
1095
1096         return SR_ERR_OK;
1097 }
1098
1099 int ves_heartbeat_period_changed(int period)
1100 {
1101         char *stringConfiguration = readConfigFileInString();
1102
1103         if (stringConfiguration == NULL)
1104         {
1105                 printf("Could not read configuration file!\n");
1106                 return SR_ERR_OPERATION_FAILED;
1107         }
1108
1109         cJSON *jsonConfig = cJSON_Parse(stringConfiguration);
1110         if (jsonConfig == NULL)
1111         {
1112                 free(stringConfiguration);
1113                 const char *error_ptr = cJSON_GetErrorPtr();
1114                 if (error_ptr != NULL)
1115                 {
1116                         fprintf(stderr, "Could not parse JSON configuration! Error before: %s\n", error_ptr);
1117                 }
1118                 return SR_ERR_OPERATION_FAILED;
1119         }
1120         //we don't need the string anymore
1121         free(stringConfiguration);
1122         stringConfiguration = NULL;
1123
1124         cJSON *notifConfig = cJSON_GetObjectItemCaseSensitive(jsonConfig, "notification-config");
1125         if (!cJSON_IsObject(notifConfig))
1126         {
1127                 printf("Configuration JSON is not as expected: notification-config is not an object");
1128                 free(jsonConfig);
1129                 return SR_ERR_OPERATION_FAILED;
1130         }
1131
1132         cJSON *vesHeartbeatPeriod = cJSON_GetObjectItemCaseSensitive(notifConfig, "ves-heartbeat-period");
1133         if (!cJSON_IsNumber(vesHeartbeatPeriod))
1134         {
1135                 printf("Configuration JSON is not as expected: ves-heartbeat-period is not an object");
1136                 free(jsonConfig);
1137                 return SR_ERR_OPERATION_FAILED;
1138         }
1139
1140         //we set the value of the fault-notification-delay-period object
1141         cJSON_SetNumberValue(vesHeartbeatPeriod, period);
1142
1143         //writing the new JSON to the configuration file
1144         stringConfiguration = cJSON_Print(jsonConfig);
1145         writeConfigFile(stringConfiguration);
1146
1147         free(jsonConfig);
1148
1149         return SR_ERR_OK;
1150 }
1151
1152 static int add_keystore_entry_odl(char *url, char *credentials)
1153 {
1154         CURLcode res;
1155
1156         curl_easy_reset(curl_odl);
1157         set_curl_common_info_odl();
1158
1159         char url_for_curl[200];
1160         sprintf(url_for_curl, "%s", url);
1161
1162         curl_easy_setopt(curl_odl, CURLOPT_URL, url_for_curl);
1163
1164         char post_data_xml[2000];
1165
1166         sprintf(post_data_xml,
1167                         "<input xmlns=\"urn:opendaylight:netconf:keystore\">"
1168                         "<key-credential>"
1169                         "<key-id>device-key</key-id>"
1170                         "<private-key>MIIEpAIBAAKCAQEAueCQaNQWoNmFK6LKu1p8U8ZWdWg/PvDdLsJyzfzl/Qw4UA68"
1171                         "SfFNaY06zZl8QB9W02nr5kWeeMY0VA3adrPgOlvfx3oWlFbkETnMaN4OT3WTQ0Wt"
1172                         "6jAWZDzVfopwpJPAzRPxACDftIqFGagYcF32hZlVNqqnVdbXh0S0EViweqp/dbG4"
1173                         "VDUHSNVbglc+u4UbEzNIFXMdEFsJZpkynOmSiTsIATqIhb+2srkVgLwhfkC2qkuH"
1174                         "QwAHdubuB07ObM2z01UhyEdDvEYGHwtYAGDBL2TAcsI0oGeVkRyuOkV0QY0UN7UE"
1175                         "FI1yTYw+xZ42HgFx3uGwApCImxhbj69GBYWFqwIDAQABAoIBAQCZN9kR8DGu6V7y"
1176                         "t0Ax68asL8O5B/OKaHWKQ9LqpVrXmikZJOxkbzoGldow/CIFoU+q+Zbwu9aDa65a"
1177                         "0wiP7Hoa4Py3q5XNNUrOQDyU/OYC7cI0I83WS0lJ2zOJGYj8wKae5Z81IeQFKGHK"
1178                         "4lsy1OGPAvPRGh7RjUUgRavA2MCwe07rWRuDb/OJFe4Oh56UMEjwMiNBtMNtncog"
1179                         "j1vr/qgRJdf9tf0zlJmLvUJ9+HSFFV9I/97LJyFhb95gAfHkjdVroLVgT3Cho+4P"
1180                         "WtZaKCIGD0OwfOG2nLV4leXvRUk62/LMlB8NI9+JF7Xm+HCKbaWHNWC7mvWSLV58"
1181                         "Zl4AbUWRAoGBANyJ6SFHFRHSPDY026SsdMzXR0eUxBAK7G70oSBKKhY+O1j0ocLE"
1182                         "jI2krHJBhHbLlnvJVyMUaCUOTS5m0uDw9hgSsAqeSL3hL38kxVZw+KNG9Ouno1Fl"
1183                         "KnE/xXHlPQyeGs/P8nAMzHZxQtEsQdQayJEhK2XXHTsy7Q3MxDisfVJ1AoGBANfD"
1184                         "34gB+OMx6pwj7zk3qWbYXSX8xjCZMR0ciko+h4xeMP2N8B0oyoqC+v1ABMAtJ3wG"
1185                         "sGZd0hV9gwM7OUM3SEwkn6oeg1GemWLcn4rlSmTnZc4aeVwrEWlnSNFX3s4g9l4u"
1186                         "k8Ugu4MVJYqH8HuDQ5Ggl6/QAwPzMSEdCW0O+jOfAoGAIBRbegC5+t6m7Yegz4Ja"
1187                         "dxV1g98K6f58x+MDsQu4tYWV4mmrQgaPH2dtwizvlMwmdpkh+LNWNtWuumowkJHc"
1188                         "akIFo3XExQIFg6wYnGtQb4e5xrGa2xMpKlIJaXjb+YLiCYqJDG2ALFZrTrvuU2kV"
1189                         "9a5qfqTc1qigvNolTM0iaaUCgYApmrZWhnLUdEKV2wP813PNxfioI4afxlpHD8LG"
1190                         "sCn48gymR6E+Lihn7vuwq5B+8fYEH1ISWxLwW+RQUjIneNhy/jjfV8TgjyFqg7or"
1191                         "0Sy4KjpiNI6kLBXOakELRNNMkeSPopGR2E7v5rr3bGD9oAD+aqX1G7oJH/KgPPYd"
1192                         "Vl7+ZwKBgQDcHyWYrimjyUgKaQD2GmoO9wdcJYQ59ke9K+OuGlp4ti5arsi7N1tP"
1193                         "B4f09aeELM2ASIuk8Q/Mx0jQFnm8lzRFXdewgvdPoZW/7VufM9O7dGPOc41cm2Dh"
1194                         "yrTcXx/VmUBb+/fnXVEgCv7gylp/wtdTGHQBQJHR81jFBz0lnLj+gg==</private-key>"
1195                         "<passphrase></passphrase>"
1196                         "</key-credential>"
1197                         "</input>");
1198
1199         printf("Post data:\n%s\n", post_data_xml);
1200
1201         curl_easy_setopt(curl_odl, CURLOPT_POSTFIELDS, post_data_xml);
1202         curl_easy_setopt(curl_odl, CURLOPT_CUSTOMREQUEST, "POST");
1203         curl_easy_setopt(curl_odl, CURLOPT_USERPWD, credentials);
1204
1205         res = curl_easy_perform(curl_odl);
1206         if (res != CURLE_OK)
1207         {
1208                 printf("cURL failed to url=%s\n", url_for_curl);
1209         }
1210
1211         long http_response_code = 0;
1212         curl_easy_getinfo (curl_odl, CURLINFO_RESPONSE_CODE, &http_response_code);
1213         if (http_response_code >= 200 && http_response_code <= 226 && http_response_code != CURLE_ABORTED_BY_CALLBACK)
1214         {
1215                 printf("cURL succeeded to url=%s\n", url_for_curl);
1216         }
1217         else
1218         {
1219                 printf("cURL to url=%s failed with code=%ld\n", url_for_curl, http_response_code);
1220                 return SR_ERR_OPERATION_FAILED;
1221         }
1222
1223         return SR_ERR_OK;
1224 }
1225
1226 static int add_private_key_odl(char *url, char *credentials)
1227 {
1228         CURLcode res;
1229
1230         curl_easy_reset(curl_odl);
1231         set_curl_common_info_odl();
1232
1233         char url_for_curl[200];
1234         sprintf(url_for_curl, "%s", url);
1235
1236         curl_easy_setopt(curl_odl, CURLOPT_URL, url_for_curl);
1237
1238         char post_data_xml[4000];
1239
1240         sprintf(post_data_xml,
1241                         "<input xmlns=\"urn:opendaylight:netconf:keystore\">"
1242                         "<private-key>"
1243                         "<name>device-key</name>"
1244                         "<data>MIIEpAIBAAKCAQEAueCQaNQWoNmFK6LKu1p8U8ZWdWg/PvDdLsJyzfzl/Qw4UA68SfFNaY06zZl8QB9W02nr5kWeeMY0VA3adrPgOlvfx3oWlFbkETnMaN4OT3WTQ0Wt6jAWZDzVfopwpJPAzRPxACDftIqFGagYcF32hZlVNqqnVdbXh0S0EViweqp/dbG4VDUHSNVbglc+u4UbEzNIFXMdEFsJZpkynOmSiTsIATqIhb+2srkVgLwhfkC2qkuHQwAHdubuB07ObM2z01UhyEdDvEYGHwtYAGDBL2TAcsI0oGeVkRyuOkV0QY0UN7UEFI1yTYw+xZ42HgFx3uGwApCImxhbj69GBYWFqwIDAQABAoIBAQCZN9kR8DGu6V7yt0Ax68asL8O5B/OKaHWKQ9LqpVrXmikZJOxkbzoGldow/CIFoU+q+Zbwu9aDa65a0wiP7Hoa4Py3q5XNNUrOQDyU/OYC7cI0I83WS0lJ2zOJGYj8wKae5Z81IeQFKGHK4lsy1OGPAvPRGh7RjUUgRavA2MCwe07rWRuDb/OJFe4Oh56UMEjwMiNBtMNtncogj1vr/qgRJdf9tf0zlJmLvUJ9+HSFFV9I/97LJyFhb95gAfHkjdVroLVgT3Cho+4PWtZaKCIGD0OwfOG2nLV4leXvRUk62/LMlB8NI9+JF7Xm+HCKbaWHNWC7mvWSLV58Zl4AbUWRAoGBANyJ6SFHFRHSPDY026SsdMzXR0eUxBAK7G70oSBKKhY+O1j0ocLEjI2krHJBhHbLlnvJVyMUaCUOTS5m0uDw9hgSsAqeSL3hL38kxVZw+KNG9Ouno1FlKnE/xXHlPQyeGs/P8nAMzHZxQtEsQdQayJEhK2XXHTsy7Q3MxDisfVJ1AoGBANfD34gB+OMx6pwj7zk3qWbYXSX8xjCZMR0ciko+h4xeMP2N8B0oyoqC+v1ABMAtJ3wGsGZd0hV9gwM7OUM3SEwkn6oeg1GemWLcn4rlSmTnZc4aeVwrEWlnSNFX3s4g9l4uk8Ugu4MVJYqH8HuDQ5Ggl6/QAwPzMSEdCW0O+jOfAoGAIBRbegC5+t6m7Yegz4JadxV1g98K6f58x+MDsQu4tYWV4mmrQgaPH2dtwizvlMwmdpkh+LNWNtWuumowkJHcakIFo3XExQIFg6wYnGtQb4e5xrGa2xMpKlIJaXjb+YLiCYqJDG2ALFZrTrvuU2kV9a5qfqTc1qigvNolTM0iaaUCgYApmrZWhnLUdEKV2wP813PNxfioI4afxlpHD8LGsCn48gymR6E+Lihn7vuwq5B+8fYEH1ISWxLwW+RQUjIneNhy/jjfV8TgjyFqg7or0Sy4KjpiNI6kLBXOakELRNNMkeSPopGR2E7v5rr3bGD9oAD+aqX1G7oJH/KgPPYdVl7+ZwKBgQDcHyWYrimjyUgKaQD2GmoO9wdcJYQ59ke9K+OuGlp4ti5arsi7N1tPB4f09aeELM2ASIuk8Q/Mx0jQFnm8lzRFXdewgvdPoZW/7VufM9O7dGPOc41cm2DhyrTcXx/VmUBb+/fnXVEgCv7gylp/wtdTGHQBQJHR81jFBz0lnLj+gg==</data>"
1245                         "<certificate-chain>MIIECTCCAvGgAwIBAgIBBzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UEBhMCQ1oxFjAUBgNVBAgMDVNvdXRoIE1vcmF2aWExDTALBgNVBAcMBEJybm8xDzANBgNVBAoMBkNFU05FVDEMMAoGA1UECwwDVE1DMRMwEQYDVQQDDApleGFtcGxlIENBMSIwIAYJKoZIhvcNAQkBFhNleGFtcGxlY2FAbG9jYWxob3N0MB4XDTE1MDczMDA3MjcxOFoXDTM1MDcyNTA3MjcxOFowgYUxCzAJBgNVBAYTAkNaMRYwFAYDVQQIDA1Tb3V0aCBNb3JhdmlhMQ8wDQYDVQQKDAZDRVNORVQxDDAKBgNVBAsMA1RNQzEXMBUGA1UEAwwOZXhhbXBsZSBjbGllbnQxJjAkBgkqhkiG9w0BCQEWF2V4YW1wbGVjbGllbnRAbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAueCQaNQWoNmFK6LKu1p8U8ZWdWg/PvDdLsJyzfzl/Qw4UA68SfFNaY06zZl8QB9W02nr5kWeeMY0VA3adrPgOlvfx3oWlFbkETnMaN4OT3WTQ0Wt6jAWZDzVfopwpJPAzRPxACDftIqFGagYcF32hZlVNqqnVdbXh0S0EViweqp/dbG4VDUHSNVbglc+u4UbEzNIFXMdEFsJZpkynOmSiTsIATqIhb+2srkVgLwhfkC2qkuHQwAHdubuB07ObM2z01UhyEdDvEYGHwtYAGDBL2TAcsI0oGeVkRyuOkV0QY0UN7UEFI1yTYw+xZ42HgFx3uGwApCImxhbj69GBYWFqwIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUXGpLeLnh2cSDARAVA7KrBxGYpo8wHwYDVR0jBBgwFoAUc1YQIqjZsHVwlea0AB4N+ilNI2gwDQYJKoZIhvcNAQELBQADggEBAJPV3RTXFRtNyOU4rjPpYeBAIAFp2aqGc4t2J1c7oPp/1n+lZvjnwtlJpZHxMM783e2ryDQ6dkvXDf8kpwKlg3U3mkJ3xKkDdWrM4QwghXdCN519aa9qmu0zdFL+jUAaWlQ5tsceOrvbusCcbMqiFGk/QfpHqPv52SVWbYyUx7IX7DE+UjgsLHycfV/tlcx4ZE6soTzl9VdgSL/zmzG3rjsr58J80rXckLgBhvijgBlIAJvWfC7D0vaouvBInSFXymdPVoUDZ30cdGLf+hI/i/TfsEMOinLrXVdkSGNo6FXAHKSvXeB9oFKSzhQ7OPyRyqvEPycUSw/qD6FVr80oDDc=</certificate-chain>"
1246                         "</private-key>"
1247                         "</input>");
1248
1249         printf("Post data:\n%s\n", post_data_xml);
1250
1251         curl_easy_setopt(curl_odl, CURLOPT_POSTFIELDS, post_data_xml);
1252         curl_easy_setopt(curl_odl, CURLOPT_CUSTOMREQUEST, "POST");
1253         curl_easy_setopt(curl_odl, CURLOPT_USERPWD, credentials);
1254
1255         res = curl_easy_perform(curl_odl);
1256         if (res != CURLE_OK)
1257         {
1258                 printf("cURL failed to url=%s\n", url_for_curl);
1259         }
1260
1261         long http_response_code = 0;
1262         curl_easy_getinfo (curl_odl, CURLINFO_RESPONSE_CODE, &http_response_code);
1263         if (http_response_code >= 200 && http_response_code <= 226 && http_response_code != CURLE_ABORTED_BY_CALLBACK)
1264         {
1265                 printf("cURL succeeded to url=%s\n", url_for_curl);
1266         }
1267         else
1268         {
1269                 printf("cURL to url=%s failed with code=%ld\n", url_for_curl, http_response_code);
1270                 return SR_ERR_OPERATION_FAILED;
1271         }
1272
1273         return SR_ERR_OK;
1274 }
1275
1276 static int add_trusted_ca_odl(char *url, char *credentials)
1277 {
1278         CURLcode res;
1279
1280         curl_easy_reset(curl_odl);
1281         set_curl_common_info_odl();
1282
1283         char url_for_curl[200];
1284         sprintf(url_for_curl, "%s", url);
1285
1286         curl_easy_setopt(curl_odl, CURLOPT_URL, url_for_curl);
1287
1288         char post_data_xml[2000];
1289
1290         sprintf(post_data_xml,
1291                         "<input xmlns=\"urn:opendaylight:netconf:keystore\">"
1292                         "<trusted-certificate>"
1293                         "<name>test_trusted_cert</name>"
1294                         "<certificate>MIID7TCCAtWgAwIBAgIJAMtE1NGAR5KoMA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJDWjEWMBQGA1UECAwNU291dGggTW9yYXZpYTENMAsGA1UEBwwEQnJubzEPMA0GA1UECgwGQ0VTTkVUMQwwCgYDVQQLDANUTUMxEzARBgNVBAMMCmV4YW1wbGUgQ0ExIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVjYUBsb2NhbGhvc3QwHhcNMTQwNzI0MTQxOTAyWhcNMjQwNzIxMTQxOTAyWjCBjDELMAkGA1UEBhMCQ1oxFjAUBgNVBAgMDVNvdXRoIE1vcmF2aWExDTALBgNVBAcMBEJybm8xDzANBgNVBAoMBkNFU05FVDEMMAoGA1UECwwDVE1DMRMwEQYDVQQDDApleGFtcGxlIENBMSIwIAYJKoZIhvcNAQkBFhNleGFtcGxlY2FAbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArD3TDHPAMT2Z84orK4lMlarbgooIUCcRZyLe+QM+8KY8Hn+mGaxPEOTSL3ywszqefB/Utm2hPKLHX684iRC14ID9WDGHxPjvoPArhgFhfV+qnPfxKTgxZC12uOj4u1V9y+SkTCocFbRfXVBGpojrBuDHXkDMDEWNvr8/52YCv7bGaiBwUHolcLCUbmtKILCG0RNJyTaJpXQdAeq5Z1SJotpbfYFFtAXB32hVoLug1dzl2tjG9sb1wq3QaDExcbC5w6P65qOkNoyym9ne6QlQagCqVDyFn3vcqkRaTjvZmxauCeUxXgJoXkyWcm0lM1KMHdoTArmchw2Dz0yHHSyDAQIDAQABo1AwTjAdBgNVHQ4EFgQUc1YQIqjZsHVwlea0AB4N+ilNI2gwHwYDVR0jBBgwFoAUc1YQIqjZsHVwlea0AB4N+ilNI2gwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAI/1KH60qnw9Xs2RGfi0/IKf5EynXt4bQX8EIyVKwSkYKe04zZxYfLIl/Q2HOPYoFmm3daj5ddr0ZS1i4p4fTUhstjsYWvXs3W/HhVmFUslakkn3PrswhP77fCk6eEJLxdfyJ1C7Uudq2m1isZbKih+XF0mG1LxJaDMocSz4eAya7M5brwjy8DoOmA1TnLQFCVcpn+sCr7VC4wE/JqxyVhBCk/MuGqqM3B1j90bGFZ112ZOecyE0EDSr6IbiRBtmeNbEwOFjKXhNLYdxpBZ9D8A/368OckZkCrVLGuJNxK9UwCVTe8IhotHUqU9EqFDmxdV8oIdU/OzUwwNPA/Bd/9g==</certificate>"
1295                         "</trusted-certificate>"
1296                         "</input>");
1297
1298         printf("Post data:\n%s\n", post_data_xml);
1299
1300         curl_easy_setopt(curl_odl, CURLOPT_POSTFIELDS, post_data_xml);
1301         curl_easy_setopt(curl_odl, CURLOPT_CUSTOMREQUEST, "POST");
1302         curl_easy_setopt(curl_odl, CURLOPT_USERPWD, credentials);
1303
1304         res = curl_easy_perform(curl_odl);
1305         if (res != CURLE_OK)
1306         {
1307                 printf("cURL failed to url=%s\n", url_for_curl);
1308         }
1309
1310         long http_response_code = 0;
1311         curl_easy_getinfo (curl_odl, CURLINFO_RESPONSE_CODE, &http_response_code);
1312         if (http_response_code >= 200 && http_response_code <= 226 && http_response_code != CURLE_ABORTED_BY_CALLBACK)
1313         {
1314                 printf("cURL succeeded to url=%s\n", url_for_curl);
1315         }
1316         else
1317         {
1318                 printf("cURL to url=%s failed with code=%ld\n", url_for_curl, http_response_code);
1319                 return SR_ERR_OPERATION_FAILED;
1320         }
1321
1322         return SR_ERR_OK;
1323 }
1324
1325 int add_key_pair_to_odl(controller_t *controller_list, int controller_list_size)
1326 {
1327         int rc = SR_ERR_OK;
1328
1329         rc = add_keystore_entry_odl(controller_list[0].url_for_keystore_add, controller_list[0].credentials);
1330         if (rc != SR_ERR_OK)
1331         {
1332                 printf("Failed to add keystore entry to ODL.\n");
1333         }
1334
1335         rc = add_private_key_odl(controller_list[0].url_for_private_key_add, controller_list[0].credentials);
1336         if (rc != SR_ERR_OK)
1337         {
1338                 printf("Failed to add private key entry to ODL.\n");
1339         }
1340
1341         rc = add_trusted_ca_odl(controller_list[0].url_for_trusted_ca_add, controller_list[0].credentials);
1342         if (rc != SR_ERR_OK)
1343         {
1344                 printf("Failed to add trusted CA entry to ODL.\n");
1345         }
1346
1347         return SR_ERR_OK;
1348 }
1349
1350 int ves_ip_changed(char *new_ip)
1351 {
1352         char *stringConfiguration = readConfigFileInString();
1353
1354         if (stringConfiguration == NULL)
1355         {
1356                 printf("Could not read configuration file!\n");
1357                 return SR_ERR_OPERATION_FAILED;
1358         }
1359
1360         cJSON *jsonConfig = cJSON_Parse(stringConfiguration);
1361         if (jsonConfig == NULL)
1362         {
1363                 free(stringConfiguration);
1364                 const char *error_ptr = cJSON_GetErrorPtr();
1365                 if (error_ptr != NULL)
1366                 {
1367                         fprintf(stderr, "Could not parse JSON configuration! Error before: %s\n", error_ptr);
1368                 }
1369                 return SR_ERR_OPERATION_FAILED;
1370         }
1371         //we don't need the string anymore
1372         free(stringConfiguration);
1373         stringConfiguration = NULL;
1374
1375         cJSON *vesDetails = cJSON_GetObjectItemCaseSensitive(jsonConfig, "ves-endpoint-details");
1376         if (!cJSON_IsObject(vesDetails))
1377         {
1378                 printf("Configuration JSON is not as expected: ves-endpoint-details is not an object");
1379                 free(jsonConfig);
1380                 return SR_ERR_OPERATION_FAILED;
1381         }
1382
1383         cJSON *vesIp = cJSON_GetObjectItemCaseSensitive(vesDetails, "ves-endpoint-ip");
1384         if (!cJSON_IsString(vesIp))
1385         {
1386                 printf("Configuration JSON is not as expected: ves-endpoint-ip is not a string");
1387                 free(jsonConfig);
1388                 return SR_ERR_OPERATION_FAILED;
1389         }
1390
1391         //we set the value of the fault-notification-delay-period object
1392         cJSON_ReplaceItemInObject(vesDetails, "ves-endpoint-ip", cJSON_CreateString(new_ip));
1393
1394         //writing the new JSON to the configuration file
1395         stringConfiguration = cJSON_Print(jsonConfig);
1396         writeConfigFile(stringConfiguration);
1397
1398         free(jsonConfig);
1399
1400         return SR_ERR_OK;
1401 }
1402
1403 int ves_port_changed(int new_port)
1404 {
1405         char *stringConfiguration = readConfigFileInString();
1406
1407         if (stringConfiguration == NULL)
1408         {
1409                 printf("Could not read configuration file!\n");
1410                 return SR_ERR_OPERATION_FAILED;
1411         }
1412
1413         cJSON *jsonConfig = cJSON_Parse(stringConfiguration);
1414         if (jsonConfig == NULL)
1415         {
1416                 free(stringConfiguration);
1417                 const char *error_ptr = cJSON_GetErrorPtr();
1418                 if (error_ptr != NULL)
1419                 {
1420                         fprintf(stderr, "Could not parse JSON configuration! Error before: %s\n", error_ptr);
1421                 }
1422                 return SR_ERR_OPERATION_FAILED;
1423         }
1424         //we don't need the string anymore
1425         free(stringConfiguration);
1426         stringConfiguration = NULL;
1427
1428         cJSON *vesDetails = cJSON_GetObjectItemCaseSensitive(jsonConfig, "ves-endpoint-details");
1429         if (!cJSON_IsObject(vesDetails))
1430         {
1431                 printf("Configuration JSON is not as expected: ves-endpoint-details is not an object");
1432                 free(jsonConfig);
1433                 return SR_ERR_OPERATION_FAILED;
1434         }
1435
1436         cJSON *vesPort = cJSON_GetObjectItemCaseSensitive(vesDetails, "ves-endpoint-port");
1437         if (!cJSON_IsNumber(vesPort))
1438         {
1439                 printf("Configuration JSON is not as expected: ves-endpoint-port is not a number.");
1440                 free(jsonConfig);
1441                 return SR_ERR_OPERATION_FAILED;
1442         }
1443
1444         //we set the value of the fault-notification-delay-period object
1445         cJSON_SetNumberValue(vesPort, new_port);
1446
1447         //writing the new JSON to the configuration file
1448         stringConfiguration = cJSON_Print(jsonConfig);
1449         writeConfigFile(stringConfiguration);
1450
1451         free(jsonConfig);
1452
1453         return SR_ERR_OK;
1454 }
1455
1456 int ves_registration_changed(cJSON_bool new_bool)
1457 {
1458         char *stringConfiguration = readConfigFileInString();
1459
1460         if (stringConfiguration == NULL)
1461         {
1462                 printf("Could not read configuration file!\n");
1463                 return SR_ERR_OPERATION_FAILED;
1464         }
1465
1466         cJSON *jsonConfig = cJSON_Parse(stringConfiguration);
1467         if (jsonConfig == NULL)
1468         {
1469                 free(stringConfiguration);
1470                 const char *error_ptr = cJSON_GetErrorPtr();
1471                 if (error_ptr != NULL)
1472                 {
1473                         fprintf(stderr, "Could not parse JSON configuration! Error before: %s\n", error_ptr);
1474                 }
1475                 return SR_ERR_OPERATION_FAILED;
1476         }
1477         //we don't need the string anymore
1478         free(stringConfiguration);
1479         stringConfiguration = NULL;
1480
1481         cJSON *vesDetails = cJSON_GetObjectItemCaseSensitive(jsonConfig, "ves-endpoint-details");
1482         if (!cJSON_IsObject(vesDetails))
1483         {
1484                 printf("Configuration JSON is not as expected: ves-endpoint-details is not an object");
1485                 free(jsonConfig);
1486                 return SR_ERR_OPERATION_FAILED;
1487         }
1488
1489         cJSON *vesRegistration = cJSON_GetObjectItemCaseSensitive(vesDetails, "ves-registration");
1490         if (!cJSON_IsBool(vesRegistration))
1491         {
1492                 printf("Configuration JSON is not as expected: ves-registration is not a bool.");
1493                 free(jsonConfig);
1494                 return SR_ERR_OPERATION_FAILED;
1495         }
1496
1497         //we set the value of the ves-registration object
1498         cJSON_ReplaceItemInObject(vesDetails, "ves-registration", cJSON_CreateBool(new_bool));
1499
1500         //writing the new JSON to the configuration file
1501         stringConfiguration = cJSON_Print(jsonConfig);
1502         writeConfigFile(stringConfiguration);
1503
1504         free(jsonConfig);
1505
1506         return SR_ERR_OK;
1507 }
1508
1509 int is_netconf_available_changed(cJSON_bool new_bool)
1510 {
1511         char *stringConfiguration = readConfigFileInString();
1512
1513         if (stringConfiguration == NULL)
1514         {
1515                 printf("Could not read configuration file!\n");
1516                 return SR_ERR_OPERATION_FAILED;
1517         }
1518
1519         cJSON *jsonConfig = cJSON_Parse(stringConfiguration);
1520         if (jsonConfig == NULL)
1521         {
1522                 free(stringConfiguration);
1523                 const char *error_ptr = cJSON_GetErrorPtr();
1524                 if (error_ptr != NULL)
1525                 {
1526                         fprintf(stderr, "Could not parse JSON configuration! Error before: %s\n", error_ptr);
1527                 }
1528                 return SR_ERR_OPERATION_FAILED;
1529         }
1530         //we don't need the string anymore
1531         free(stringConfiguration);
1532         stringConfiguration = NULL;
1533
1534         cJSON *notifConfig = cJSON_GetObjectItemCaseSensitive(jsonConfig, "notification-config");
1535         if (!cJSON_IsObject(notifConfig))
1536         {
1537                 printf("Configuration JSON is not as expected: notification-config is not an object");
1538                 free(jsonConfig);
1539                 return SR_ERR_OPERATION_FAILED;
1540         }
1541
1542         cJSON *isNetconfAvailable = cJSON_GetObjectItemCaseSensitive(notifConfig, "is-netconf-available");
1543         if (!cJSON_IsBool(isNetconfAvailable))
1544         {
1545                 printf("Configuration JSON is not as expected: is-netconf-available is not a bool.");
1546                 free(jsonConfig);
1547                 return SR_ERR_OPERATION_FAILED;
1548         }
1549
1550         //we set the value of the ves-registration object
1551         cJSON_ReplaceItemInObject(notifConfig, "is-netconf-available", cJSON_CreateBool(new_bool));
1552
1553         //writing the new JSON to the configuration file
1554         stringConfiguration = cJSON_Print(jsonConfig);
1555         writeConfigFile(stringConfiguration);
1556
1557         free(jsonConfig);
1558
1559         return SR_ERR_OK;
1560 }
1561
1562 int is_ves_available_changed(cJSON_bool new_bool)
1563 {
1564         char *stringConfiguration = readConfigFileInString();
1565
1566         if (stringConfiguration == NULL)
1567         {
1568                 printf("Could not read configuration file!\n");
1569                 return SR_ERR_OPERATION_FAILED;
1570         }
1571
1572         cJSON *jsonConfig = cJSON_Parse(stringConfiguration);
1573         if (jsonConfig == NULL)
1574         {
1575                 free(stringConfiguration);
1576                 const char *error_ptr = cJSON_GetErrorPtr();
1577                 if (error_ptr != NULL)
1578                 {
1579                         fprintf(stderr, "Could not parse JSON configuration! Error before: %s\n", error_ptr);
1580                 }
1581                 return SR_ERR_OPERATION_FAILED;
1582         }
1583         //we don't need the string anymore
1584         free(stringConfiguration);
1585         stringConfiguration = NULL;
1586
1587         cJSON *notifConfig = cJSON_GetObjectItemCaseSensitive(jsonConfig, "notification-config");
1588         if (!cJSON_IsObject(notifConfig))
1589         {
1590                 printf("Configuration JSON is not as expected: notification-config is not an object");
1591                 free(jsonConfig);
1592                 return SR_ERR_OPERATION_FAILED;
1593         }
1594
1595         cJSON *isVesAvailable = cJSON_GetObjectItemCaseSensitive(notifConfig, "is-ves-available");
1596         if (!cJSON_IsBool(isVesAvailable))
1597         {
1598                 printf("Configuration JSON is not as expected: is-ves-available is not a bool.");
1599                 free(jsonConfig);
1600                 return SR_ERR_OPERATION_FAILED;
1601         }
1602
1603         //we set the value of the ves-registration object
1604         cJSON_ReplaceItemInObject(notifConfig, "is-ves-available", cJSON_CreateBool(new_bool));
1605
1606         //writing the new JSON to the configuration file
1607         stringConfiguration = cJSON_Print(jsonConfig);
1608         writeConfigFile(stringConfiguration);
1609
1610         free(jsonConfig);
1611
1612         return SR_ERR_OK;
1613 }