2424TYPE_VALUES = 0x0006
2525TYPE_INTERVAL = 0x0007
2626
27+ header = struct .Struct ("!2H" )
28+ number = struct .Struct ("!Q" )
29+ short = struct .Struct ("!H" )
30+ double = struct .Struct ("<d" )
31+ char = struct .Struct ("B" )
32+ long_ = struct .Struct ("!q" )
33+
2734_value_formats = {
28- VALUE_COUNTER : "!Q" ,
29- VALUE_GAUGE : "<d" ,
30- VALUE_DERIVE : "!q" ,
31- VALUE_ABSOLUTE : "!Q"
35+ VALUE_COUNTER : number ,
36+ VALUE_GAUGE : double ,
37+ VALUE_DERIVE : long_ ,
38+ VALUE_ABSOLUTE : number
3239}
3340
3441
@@ -73,18 +80,19 @@ def __init__(self, name, *db_template):
7380 self ._value_types = [value_type for dsname , value_type in db_template ]
7481 self ._value_formats = [
7582 _value_formats [value_type ] for value_type in self ._value_types ]
76- self ._message_template = struct .pack (
77- "!HHH" , TYPE_VALUES , 6 + (9 * len (db_template )),
78- len (db_template ))
83+
84+ self ._message_template = header .pack (
85+ TYPE_VALUES , 6 + (9 * len (db_template ))
86+ ) + short .pack (len (db_template ))
7987 for value_type in self ._value_types :
80- self ._message_template += struct .pack ("B" , value_type )
88+ self ._message_template += char .pack (value_type )
8189
8290 def encode_values (self , * values ):
8391 """Encode a series of values according to the type template."""
8492
8593 msg = self ._message_template
8694 for format_ , dsvalue in zip (self ._value_formats , values ):
87- msg += struct .pack (format_ , dsvalue )
95+ msg += format_ .pack (dsvalue )
8896
8997 return msg
9098
@@ -118,22 +126,23 @@ def __init__(
118126 )
119127
120128 def _pack_string (self , typecode , value ):
121- return struct .pack (
122- "!HH" , typecode , 5 + len (value )) + value .encode ('ascii' ) + b"\0 "
129+ return header .pack (
130+ typecode , 5 + len (value )) + value .encode ('ascii' ) + b"\0 "
123131
124132 def send (self , connection , timestamp , * values ):
125133 """Send a message on a connection."""
126134
127- header = self ._host_message_part + \
128- struct .pack ("!HHq" , TYPE_TIME , 12 , int (timestamp )) + \
135+ header_ = self ._host_message_part + \
136+ header .pack (TYPE_TIME , 12 ) + \
137+ long_ .pack (int (timestamp )) + \
129138 self ._remainder_message_parts
130139
131140 payload = self .type .encode_values (* values )
132141
133- connection .send (header + payload )
142+ connection .send (header_ + payload )
134143
135144
136- class Connection (object ):
145+ class ClientConnection (object ):
137146 connections = {}
138147 create_mutex = threading .Lock ()
139148
@@ -155,7 +164,8 @@ def for_host_port(cls, host, port):
155164 try :
156165 key = (host , port )
157166 if key not in cls .connections :
158- cls .connections [key ] = connection = Connection (host , port )
167+ cls .connections [key ] = connection = \
168+ ClientConnection (host , port )
159169 return connection
160170 else :
161171 return cls .connections [key ]
0 commit comments