3 #Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
15 import sys, os, glob, threading
19 #sys.path.append('gen-py')
20 #sys.path.insert(0, glob.glob('./lib/py/build/lib.*')[0])
21 sys.path.insert(0, glob.glob('./lib')[0])
23 from dominoRPC import Communication
24 from dominoRPC.ttypes import *
25 from dominoRPC.constants import *
27 from dominoCLI import DominoClientCLI
28 from dominoCLI.ttypes import *
29 from dominoCLI.constants import *
31 from thrift import Thrift
32 from thrift.transport import TSocket
33 from thrift.transport import TTransport
34 from thrift.protocol import TBinaryProtocol
35 from thrift.server import TServer
39 #Load configuration parameters
40 from domino_conf import *
42 class CommunicationHandler:
46 def __init__(self, dominoclient):
48 self.dominoClient = dominoclient
51 transport = TSocket.TSocket(DOMINO_SERVER_IP, DOMINO_SERVER_PORT)
52 transport.setTimeout(THRIFT_RPC_TIMEOUT_MS)
53 # Add buffering to compensate for slow raw sockets
54 self.transport = TTransport.TBufferedTransport(transport)
56 self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
57 # Create a client to use the protocol encoder
58 self.sender = Communication.Client(self.protocol)
59 except Thrift.TException, tx:
60 logging.error('%s' , tx.message)
62 # Template Push from Domino Server is received
64 # - Depending on Controller Domain, call API
65 # - Respond Back with Push Response
66 def d_push(self, push_msg):
67 logging.info('%d Received Template File', self.dominoClient.UDID)
68 # Retrieve the template file
70 os.makedirs(TOSCA_RX_DIR+str(self.dominoClient.UDID))
71 except OSError as exception:
72 if exception.errno == errno.EEXIST:
73 logging.debug('IGNORING error: ERRNO %d; %s exists.', exception.errno, TOSCA_RX_DIR+str(self.dominoClient.UDID))
75 logging.error('IGNORING error in creating %s. Err no: %d', exception.errno)
78 miscutil.write_templatefile(TOSCA_RX_DIR+str(self.dominoClient.UDID)+'/'+str(push_msg.seq_no)+'.yaml' , push_msg.template)
80 logging.error('FAILED to write the pushed file: %s', sys.exc_info()[0])
81 push_r = PushResponseMessage()
82 # Fill response message fields
83 push_r.domino_udid = self.dominoClient.UDID
84 push_r.seq_no = self.dominoClient.seqno
85 push_r.responseCode = FAILED
86 self.dominoClient.seqno = self.dominoClient.seqno + 1
87 return push_r# Any inspection code goes here
92 # If heat client, call heat command
94 # If ONOS client, run as shell script
99 # Marshall the response message for the Domino Server Fill
100 push_r = PushResponseMessage()
101 # Fill response message fields
102 push_r.domino_udid = self.dominoClient.UDID
103 push_r.seq_no = self.dominoClient.seqno
104 push_r.responseCode = SUCCESS
107 self.dominoClient.seqno = self.dominoClient.seqno + 1
112 def openconnection(self):
113 self.transport.open()
115 def closeconnection():
116 self.transport.close()
122 def __init__(self, dominoclient, CLIservice):
124 self.dominoClient = dominoclient
125 self.CLIservice = CLIservice
127 def d_CLI(self, msg):
128 logging.info('Received CLI %s', msg.CLI_input)
130 self.CLIservice.process_input(msg.CLI_input)
132 CLIrespmsg = CLIResponse()
133 CLIrespmsg.CLI_response = "Testing..."
137 class DominoClientCLIService(threading.Thread):
138 def __init__(self, dominoclient, communicationhandler, interactive):
139 threading.Thread.__init__(self)
140 self.dominoclient = dominoclient
141 self.communicationhandler = communicationhandler
142 self.interactive = interactive
144 def process_input(self, args):
146 print 'Empty API body'
150 if args[0] == 'heartbeat':
151 self.dominoclient.heartbeat()
153 elif args[0] == 'publish':
154 opts, args = getopt.getopt(args[1:],"t:",["tosca-file="])
156 print '\nUsage: publish -t <toscafile>'
159 for opt, arg in opts:
160 if opt in ('-t', '--tosca-file'):
163 self.dominoclient.publish(toscafile)
165 elif args[0] == 'subscribe':
170 opts, args = getopt.getopt(args[1:],"l:t:",["labels=","ttype=","lop=","top="])
171 for opt, arg in opts:
172 if opt in ('-l', '--labels'):
173 labels = labels + arg.split(',')
174 elif opt in ('-t', '--ttype'):
175 templateTypes = templateTypes + arg.split(',')
176 elif opt in ('--lop'):
178 labelop = str2enum[arg.upper()]
179 except KeyError as ex:
180 print '\nInvalid label option, pick one of: APPEND, OVERWRITE, DELETE'
182 elif opt in ('--top'):
184 templateop = str2enum[arg.upper()]
185 except KeyError as ex:
186 print '\nInvalid label option, pick one of: APPEND, OVERWRITE, DELETE'
189 #check if labels or supported templates are nonempty
190 if labels != [] or templateTypes != []:
191 self.dominoclient.subscribe(labels, templateTypes, labelop, templateop)
193 elif args[0] == 'register':
194 self.dominoclient.start()
196 except getopt.GetoptError:
197 print 'Command is misentered or not supported!'
201 global DEFAULT_TOSCA_PUBFILE
202 if self.interactive == "TRUE":
207 if flag: #interactive CLI, loop in while until killed
209 sys.stdout.write('>>')
210 input_string = raw_input()
211 args = input_string.split()
215 sys.stdout.write('>>')
216 #process input arguments
217 self.process_input(args)
218 else: #domino cli-client is used, listen for the CLI rpc calls
219 cliHandler = CLIHandler(self.dominoclient, self)
220 processor = DominoClientCLI.Processor(cliHandler)
221 transport = TSocket.TServerSocket(port=self.dominoclient.CLIport)
222 tfactory = TTransport.TBufferedTransportFactory()
223 pfactory = TBinaryProtocol.TBinaryProtocolFactory()
224 #Use TThreadedServer or TThreadPoolServer for a multithreaded server
225 CLIServer = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
226 logging.debug('RPC service for CLI is starting...')
231 self.communicationHandler = CommunicationHandler(self)
232 self.processor = None
233 self.transport = None
236 self.communicationServer = None
238 self.CLIservice = None
240 self.serviceport = 9091
241 self.dominoserver_IP = 'localhost'
243 self.CLIport = DOMINO_CLI_PORT
245 #Start from UNREGISTERED STATE
246 #TO BE DONE: initialize from a saved state
247 self.state = 'UNREGISTERED'
251 def start_communicationService(self):
252 self.processor = Communication.Processor(self.communicationHandler)
253 self.transport = TSocket.TServerSocket(port=int(self.serviceport))
254 self.tfactory = TTransport.TBufferedTransportFactory()
255 self.pfactory = TBinaryProtocol.TBinaryProtocolFactory()
256 #Use TThreadedServer or TThreadPoolServer for a multithreaded server
257 #self.communicationServer = TServer.TThreadedServer(self.processor, self.transport, self.tfactory, self.pfactory)
258 self.communicationServer = TServer.TThreadPoolServer(self.processor, self.transport, self.tfactory, self.pfactory)
260 self.communicationServer.serve()
264 self.communicationHandler.openconnection()
266 except Thrift.TException, tx:
267 print '%s' % (tx.message)
270 if self.state == 'UNREGISTERED':
271 logging.info('%d Sending Registration', self.UDID)
272 #prepare registration message
273 reg_msg = RegisterMessage()
274 reg_msg.domino_udid_desired = UDID_DESIRED
275 reg_msg.seq_no = self.seqno
276 reg_msg.ipaddr = netutil.get_ip()
277 reg_msg.tcpport = self.serviceport
278 reg_msg.supported_templates = LIST_SUPPORTED_TEMPLATES
281 reg_msg_r = self.sender().d_register(reg_msg)
282 logging.info('Registration Response: Response Code: %d' , reg_msg_r.responseCode)
283 if reg_msg_r.comments:
284 logging.debug('Response Comments: %s' , reg_msg_r.comments)
286 if reg_msg_r.responseCode == SUCCESS:
287 self.state = 'REGISTERED'
288 self.UDID = reg_msg_r.domino_udid_assigned
290 #Handle registration failure here (possibly based on reponse comments)
292 except (Thrift.TException, TSocket.TTransportException) as tx:
293 logging.error('%s' , tx.message)
294 except (socket.timeout) as tx:
295 self.dominoclient.handle_RPC_timeout(pub_msg)
296 except (socket.error) as tx:
297 logging.error('%s' , tx.message)
298 self.seqno = self.seqno + 1
301 if self.state == 'UNREGISTERED':
304 logging.info('%d Sending heartbeat', self.UDID)
305 hbm = HeartBeatMessage()
306 hbm.domino_udid = self.UDID
307 hbm.seq_no = self.seqno
310 hbm_r = self.sender().d_heartbeat(hbm)
311 logging.info('heart beat received from: %d ,sequence number: %d' , hbm_r.domino_udid, hbm_r.seq_no)
312 except (Thrift.TException, TSocket.TTransportException) as tx:
313 logging.error('%s' , tx.message)
314 except (socket.timeout) as tx:
315 self.handle_RPC_timeout(hbm)
317 logging.error('Unexpected error: %s', sys.exc_info()[0])
319 self.seqno = self.seqno + 1
321 def publish(self, toscafile):
322 if self.state == 'UNREGISTERED':
325 logging.info('Publishing the template file: ' + toscafile)
326 pub_msg = PublishMessage()
327 pub_msg.domino_udid = self.UDID
328 pub_msg.seq_no = self.seqno
329 pub_msg.template_type = 'tosca-nfv-v1.0'
332 pub_msg.template = miscutil.read_templatefile(toscafile)
334 logging.error('I/O error(%d): %s' , e.errno, e.strerror)
337 pub_msg_r = self.sender().d_publish(pub_msg)
338 logging.info('Publish Response is received from: %d ,sequence number: %d Op. Status: %d', pub_msg_r.domino_udid, pub_msg_r.seq_no, pub_msg_r.responseCode)
339 except (Thrift.TException, TSocket.TTransportException) as tx:
340 print '%s' % (tx.message)
341 except (socket.timeout) as tx:
342 self.handle_RPC_timeout(pub_msg)
344 self.seqno = self.seqno + 1
346 def subscribe(self, labels, templateTypes, label_op, template_op):
347 if self.state == 'UNREGISTERED':
350 logging.info('subscribing labels %s and templates %s', labels, templateTypes)
351 #send subscription message
352 sub_msg = SubscribeMessage()
353 sub_msg.domino_udid = self.UDID
354 sub_msg.seq_no = self.seqno
355 sub_msg.template_op = template_op
356 sub_msg.supported_template_types = templateTypes
357 sub_msg.label_op = label_op
358 sub_msg.labels = labels
360 sub_msg_r = self.sender().d_subscribe(sub_msg)
361 logging.info('Subscribe Response is received from: %d ,sequence number: %d', sub_msg_r.domino_udid,sub_msg_r.seq_no)
362 except (Thrift.TException, TSocket.TTransportException) as tx:
363 logging.error('%s' , tx.message)
364 except (socket.timeout) as tx:
365 self.handle_RPC_timeout(sub_msg)
367 self.seqno = self.seqno + 1
371 self.communicationHandler.closeconnection()
372 except Thrift.TException, tx:
373 logging.error('%s' , tx.message)
376 return self.communicationHandler.sender
378 def startCLI(self, interactive):
379 self.CLIservice = DominoClientCLIService(self, self.communicationHandler, interactive)
380 logging.info('CLI Service is starting')
381 self.CLIservice.start()
382 #to wait until CLI service is finished
383 #self.CLIservice.join()
385 def set_serviceport(self, port):
386 self.serviceport = port
388 def set_CLIport(self, cliport):
389 self.CLIport = cliport
391 def set_dominoserver_ipaddr(self, ipaddr):
392 self.dominoserver_IP = ipaddr
394 def handle_RPC_timeout(self, RPCmessage):
395 # TBD: handle each RPC timeout separately
396 if RPCmessage.messageType == HEART_BEAT:
397 logging.debug('RPC Timeout for message type: HEART_BEAT')
398 elif RPCmessage.messageType == PUBLISH:
399 logging.debug('RPC Timeout for message type: PUBLISH')
400 elif RPCmessage.messageType == SUBSCRIBE:
401 logging.debug('RPC Timeout for message type: SUBSCRIBE')
402 elif RPCmessage.messageType == REGISTER:
403 logging.debug('RPC Timeout for message type: REGISTER')
404 elif RPCmessage.messageType == QUERY:
405 logging.debug('RPC Timeout for message type: QUERY')
408 client = DominoClient()
410 interactive = INTERACTIVE
411 #process input arguments
413 opts, args = getopt.getopt(argv,"hc:p:i:l:",["conf=","port=","ipaddr=","log=","iac=","cliport="])
414 except getopt.GetoptError:
415 print 'DominoClient.py -c/--conf <configfile> -p/--port <socketport> -i/--ipaddr <IPaddr> -l/--log <loglevel> --iac=true/false --cliport <cliport>'
417 for opt, arg in opts:
419 print 'DominoClient.py -c/--conf <configfile> -p/--port <socketport> -i/--ipaddr <IPaddr> -l/--log <loglevel> --iac=true/false --cliport <cliport>'
421 elif opt in ("-c", "--conf"):
423 elif opt in ("-p", "--port"):
424 client.set_serviceport(int(arg))
425 elif opt in ("-i", "--ipaddr"):
426 client.set_dominoserver_ipaddr(arg)
427 elif opt in ("-l", "--log"):
429 elif opt in ("--iac"):
430 interactive = arg.upper()
431 elif opt in ("--cliport"):
432 client.set_CLIport(int(arg))
435 numeric_level = getattr(logging, loglevel.upper(), None)
437 if not isinstance(numeric_level, int):
438 raise ValueError('Invalid log level: %s' % loglevel)
439 logging.basicConfig(filename=logfile,level=numeric_level, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
440 except ValueError, ex:
444 #The client is starting
445 logging.debug('Domino Client Starting...')
447 client.startCLI(interactive)
448 client.start_communicationService()
450 if __name__ == "__main__":