1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 
3 /*  CMetrics
4  *  ========
5  *  Copyright 2021 Eduardo Silva <eduardo@calyptia.com>
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 #include <cmetrics/cmetrics.h>
21 #include <cmetrics/cmt_sds.h>
22 #include <cmetrics/cmt_label.h>
23 
24 /*
25  * This interface file provide helper functions to compose a dynamic list
26  * of custom labels with specific keys and values. Note that this is not
27  * about labels defined by metrics upon creation, but label lists to be
28  * used by the encoders when formatting the data.
29  */
cmt_labels_create()30 struct cmt_labels *cmt_labels_create()
31 {
32     struct cmt_labels *l;
33 
34     l = malloc(sizeof(struct cmt_labels));
35     if (!l) {
36         cmt_errno();
37         return NULL;
38     }
39     mk_list_init(&l->list);
40     return l;
41 }
42 
cmt_labels_destroy(struct cmt_labels * labels)43 void cmt_labels_destroy(struct cmt_labels *labels)
44 {
45     struct mk_list *tmp;
46     struct mk_list *head;
47     struct cmt_label *l;
48 
49     mk_list_foreach_safe(head, tmp, &labels->list) {
50         l = mk_list_entry(head, struct cmt_label, _head);
51         if (l->key) {
52             cmt_sds_destroy(l->key);
53         }
54         if (l->val) {
55             cmt_sds_destroy(l->val);
56         }
57         mk_list_del(&l->_head);
58         free(l);
59     }
60 
61     free(labels);
62 }
63 
cmt_labels_add_kv(struct cmt_labels * labels,char * key,char * val)64 int cmt_labels_add_kv(struct cmt_labels *labels, char *key, char *val)
65 {
66     struct cmt_label *l;
67 
68     l = malloc(sizeof(struct cmt_label));
69     if (!l) {
70         cmt_errno();
71         return -1;
72     }
73 
74     l->key = cmt_sds_create(key);
75     if (!l->key) {
76         free(l);
77         return -1;
78     }
79 
80     l->val = cmt_sds_create(val);
81     if (!l->val) {
82         cmt_sds_destroy(l->key);
83         free(l);
84         return -1;
85     }
86 
87     mk_list_add(&l->_head, &labels->list);
88     return 0;
89 }
90 
cmt_labels_count(struct cmt_labels * labels)91 int cmt_labels_count(struct cmt_labels *labels)
92 {
93     int c = 0;
94     struct mk_list *head;
95 
96     mk_list_foreach(head, &labels->list) {
97         c++;
98     }
99 
100     return c;
101 }
102