Add supoprt for D release use-case.
[sim/o1-interface.git] / ntsimulator / ntsim-ng / core / faults / faults.c
1 /*************************************************************************
2 *
3 * Copyright 2020 highstreet technologies GmbH and others
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 ***************************************************************************/
17
18 #define _GNU_SOURCE
19
20 #include "faults.h"
21 #include "utils/log_utils.h"
22 #include "utils/rand_utils.h"
23 #include "utils/nts_utils.h"
24 #include "utils/sys_utils.h"
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <assert.h>
28
29 static fault_settings_t *faults = 0;
30 static int fault_iterator = -1;
31
32 int faults_init(void) {
33     int rc = 0;
34
35     rc = faults_ves_init();
36     if(rc != NTS_ERR_OK) {
37         log_error("faults_ves_init failed\n");
38         return NTS_ERR_FAILED; 
39     }
40
41     faults_counters_clear();
42
43     char *config_contents = file_read_content("config/config.json");
44     rc = faults_change_settings(config_contents);
45     free(config_contents);
46
47     return rc;
48 }
49
50 void faults_free(void) {
51     faults_ves_free();
52     faults_settings_free(faults);
53 }
54
55 int faults_change_settings(const char *json) {
56     assert(json);
57
58     fault_settings_t *local_faults = faults_settings_read(json);
59     if(faults) {
60         faults_settings_free(faults);
61     }
62     faults = local_faults;
63
64     return NTS_ERR_OK;
65 }
66
67 bool faults_get_present(void) {
68     return (faults != 0);
69 }
70
71 fault_details_t *faults_generate_fault(void) {
72     if(faults == 0) {
73         return 0;
74     }
75
76     switch(faults->choosing_method[0]) {
77         case 'l':
78             fault_iterator++;
79             if(fault_iterator >= faults->fault_count) {
80                 fault_iterator = 0;
81             }
82
83             break;
84
85         case 'r':
86             fault_iterator = rand_uint32() % faults->fault_count;
87             break;
88
89         default:
90             log_error("invalid fault choosing method\n");
91             return 0;
92             break;
93     }
94
95     int rc = faults_settings_process(faults, fault_iterator);
96     if(rc != NTS_ERR_OK) {
97         log_error("faults_settings_process failed\n");
98         faults_settings_free(faults);
99         return 0;
100     }
101
102     return &faults->fault[fault_iterator];
103 }