1

I have a strange problem and was hoping to find a solution here. I am using push_to_gateway module to allow Prometheus to scape some data. There are 2 steps to the process:

1) declare a variable as like so:

g = Gauge(ctr, '', ['host', 'ip'], registry=registry)

host and ip are labels used in the Prometheus DB. registry isn't relevant to my problem.

2) Populate the data:

g.labels(hostname, ipaddr).set(val)

hostname and ipaddr are the variables containing values

When you look at the data in Prometheus, you'll see something like:

ctr{hostname="node1",ip="1.1.1.1"} -1 

Since I have thousands of counters to import into Prometheus, and all of them have different sets of labels, I want to create an ordereddict containing the labels and their values while parsing the data and using that to generate 1) and 2). Filling part 1) is easy. I just type:

g = Gauge(ctr, '', list(labels.keys()), registry=registry)

The line is expecting a list, and it gets a list.

But how can I fill in part 2) since the g.labels is expecting the hostname and ipaddr seperated by a ',' (ie not a list). If I do list(labels.values()), then it shows up as a list inside the parenthesis and that doesn't work. I need the list(labels.values()) to expand to exactly 'node1','1.1.1.1' inside the parenthesis for this to work, and I have no clue how to do it (if at all possible) so that 2) looks like:

g.labels('node1', '1.1.1.1').set(val)

Thx

musca999
  • 341
  • 2
  • 12

2 Answers2

2

This is exactly where the * comes in handy. It unpacks the values of a list.

Try:

list_of_labels = list(labels.values())
g.labels(*list_of_labels).set(val)

Here's an example of how * works in python

def f(a, b):
    print a, b

tup = ("Hello", "there")

f(*tup)
# prints "Hello there"
killian95
  • 803
  • 6
  • 11
  • I tried this and it didn't work. Are you talking C or C++? I created a simple list (['a','b','c']) and when I try print *list, it comes back with invalid syntax. I'm out of hot water since I found another solution, but would still be nice to know how to do it for future reference. Thx. – musca999 Nov 02 '18 at 16:32
  • 1
    Nope this is python! The `*` operator unpacks a list or tuple but works only when passed as a function argument. See here for more details: https://stackoverflow.com/questions/2921847/what-does-the-star-operator-mean I also updated my answer with a small example. – killian95 Nov 02 '18 at 17:44
0

another solution is just to unpack on the fly:

hostname, ipaddr = labels.values()
g.labels(hostname, ipaddr).set(val)
Sam Mason
  • 15,216
  • 1
  • 41
  • 60
  • Thx for your input. This won't work as the label list can vary in size. Sometimes it might be 2 parameters, sometimes more. That's why I was looking for a more flexible approach. – musca999 Nov 02 '18 at 16:36