using miscutil.read_templatefile(temp_filename) function in domino client
[domino.git] / DominoClient.py
1 #!/usr/bin/env python
2
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.
13
14
15 import sys, glob, threading
16 import getopt, socket
17 import logging
18
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])
22
23 from dominoRPC import Communication
24 from dominoRPC.ttypes import *
25 from dominoRPC.constants import *
26
27 from dominoCLI import DominoClientCLI
28 from dominoCLI.ttypes import *
29 from dominoCLI.constants import *
30
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
36
37 from util import *
38
39 #Load configuration parameters
40 from domino_conf import *
41
42 class CommunicationHandler:
43   def __init__(self):
44     self.log = {}
45
46   def __init__(self, dominoclient):
47     self.log = {}
48     self.dominoClient = dominoclient
49     try:
50       # Make socket
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)
55       # Wrap in a protocol
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)
61
62   # Template Push from Domino Server is received
63   # Actions:
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
69
70     ## End of retrieval
71  
72     # Any inspection code goes here
73
74     ## End of inspection
75
76     # Call NB API
77     # If heat client, call heat command
78     
79     # If ONOS client, run as shell script
80
81
82     ## End of NB API call
83
84     # Marshall the response message for the Domino Server Fill
85     push_r = PushResponseMessage()
86     # Fill response message fields
87     push_r.domino_udid = self.dominoClient.UDID    
88     push_r.seq_no = self.dominoClient.seqno
89     push_r.responseCode = SUCCESS    
90     ## End of filling
91
92     self.dominoClient.seqno = self.dominoClient.seqno + 1
93
94     return push_r
95
96   
97   def openconnection(self):
98     self.transport.open()
99
100   def closeconnection():
101     self.transport.close()
102
103 class CLIHandler:
104   def __init__(self):
105     self.log = {}
106
107   def __init__(self, dominoclient, CLIservice):
108     self.log = {}
109     self.dominoClient = dominoclient
110     self.CLIservice = CLIservice
111
112   def d_CLI(self, msg):
113     logging.info('Received CLI %s', msg.CLI_input)
114
115     self.CLIservice.process_input(msg.CLI_input)
116     
117     CLIrespmsg = CLIResponse()
118     CLIrespmsg.CLI_response = "Testing..."
119     return CLIrespmsg
120  
121
122 class DominoClientCLIService(threading.Thread):
123   def __init__(self, dominoclient, communicationhandler, interactive):
124     threading.Thread.__init__(self)
125     self.dominoclient = dominoclient
126     self.communicationhandler = communicationhandler
127     self.interactive = interactive
128
129   def process_input(self, args):
130     try:
131       if args[0] == 'heartbeat':
132         self.dominoclient.heartbeat()
133
134       elif args[0] == 'publish':
135         opts, args = getopt.getopt(args[1:],"t:",["tosca-file="])
136         if len(opts) == 0:
137           print '\nUsage: publish -t <toscafile>'
138           return
139
140         for opt, arg in opts:
141           if opt in ('-t', '--tosca-file'):
142             toscafile = arg
143        
144         self.dominoclient.publish(toscafile)
145
146       elif args[0] == 'subscribe':
147         labels = []    
148         templateTypes = []
149         labelop = APPEND
150         templateop = APPEND
151         opts, args = getopt.getopt(args[1:],"l:t:",["labels=","ttype=","lop=","top="])
152         for opt, arg in opts:
153           if opt in ('-l', '--labels'):
154             labels = labels + arg.split(',')
155           elif opt in ('-t', '--ttype'):
156             templateTypes = templateTypes + arg.split(',')
157           elif opt in ('--lop'):
158             try:
159               labelop = str2enum[arg.upper()]
160             except KeyError as ex:
161               print '\nInvalid label option, pick one of: APPEND, OVERWRITE, DELETE'
162               return 
163           elif opt in ('--top'):
164             try:
165               templateop = str2enum[arg.upper()]
166             except KeyError as ex:
167               print '\nInvalid label option, pick one of: APPEND, OVERWRITE, DELETE'
168               return
169         
170         #check if labels or supported templates are nonempty
171         if labels != [] or templateTypes != []:
172           self.dominoclient.subscribe(labels, templateTypes, labelop, templateop)
173
174       elif args[0] == 'register':
175         self.dominoclient.start()
176
177     except getopt.GetoptError:
178       print 'Command is misentered or not supported!'
179
180
181   def run(self):
182     global DEFAULT_TOSCA_PUBFILE
183     if self.interactive == "TRUE":
184       flag = True
185     else:
186       flag = False
187
188     if flag: #interactive CLI, loop in while until killed
189       while True:
190          sys.stdout.write('>>')
191          input_string = raw_input()
192          args = input_string.split()
193          if len(args) == 0:
194            continue
195
196          sys.stdout.write('>>')
197          #process input arguments
198          self.process_input(args)
199     else: #domino cli-client is used, listen for the CLI rpc calls
200       cliHandler = CLIHandler(self.dominoclient, self)
201       processor = DominoClientCLI.Processor(cliHandler)
202       transport = TSocket.TServerSocket(port=self.dominoclient.CLIport)
203       tfactory = TTransport.TBufferedTransportFactory()
204       pfactory = TBinaryProtocol.TBinaryProtocolFactory()
205       #Use TThreadedServer or TThreadPoolServer for a multithreaded server
206       CLIServer = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
207       logging.debug('RPC service for CLI is starting...')
208       CLIServer.serve()       
209
210 class DominoClient:
211   def __init__(self):
212     self.communicationHandler = CommunicationHandler(self)
213     self.processor = None
214     self.transport = None
215     self.tfactory = None
216     self.pfactory = None
217     self.communicationServer = None
218
219     self.CLIservice = None
220
221     self.serviceport = 9091
222     self.dominoserver_IP = 'localhost'
223
224     self.CLIport = DOMINO_CLI_PORT 
225
226     #Start from UNREGISTERED STATE
227     #TO BE DONE: initialize from a saved state
228     self.state = 'UNREGISTERED'
229     self.seqno = 0
230     self.UDID = 1
231
232   def start_communicationService(self):
233     self.processor = Communication.Processor(self.communicationHandler)
234     self.transport = TSocket.TServerSocket(port=int(self.serviceport))
235     self.tfactory = TTransport.TBufferedTransportFactory()
236     self.pfactory = TBinaryProtocol.TBinaryProtocolFactory()
237     #Use TThreadedServer or TThreadPoolServer for a multithreaded server
238     #self.communicationServer = TServer.TThreadedServer(self.processor, self.transport, self.tfactory, self.pfactory)
239     self.communicationServer = TServer.TThreadPoolServer(self.processor, self.transport, self.tfactory, self.pfactory)
240
241     self.communicationServer.serve()
242  
243   def start(self):
244     try:
245       self.communicationHandler.openconnection()
246       self.register()
247     except Thrift.TException, tx:
248       print '%s' % (tx.message)
249    
250   def register(self):  
251     if self.state == 'UNREGISTERED':
252       logging.info('%d Sending Registration', self.UDID)
253       #prepare registration message
254       reg_msg = RegisterMessage()
255       reg_msg.domino_udid_desired = UDID_DESIRED
256       reg_msg.seq_no = self.seqno
257       reg_msg.ipaddr = netutil.get_ip()
258       reg_msg.tcpport = self.serviceport
259       reg_msg.supported_templates = LIST_SUPPORTED_TEMPLATES
260
261       try:
262         reg_msg_r = self.sender().d_register(reg_msg)
263         logging.info('Registration Response: Response Code: %d'  , reg_msg_r.responseCode)
264         if reg_msg_r.comments:
265           logging.debug('Response Comments: %s' ,  reg_msg_r.comments)
266
267         if reg_msg_r.responseCode == SUCCESS:
268           self.state = 'REGISTERED'
269           self.UDID = reg_msg_r.domino_udid_assigned
270         else:
271           #Handle registration failure here (possibly based on reponse comments)
272           pass
273       except (Thrift.TException, TSocket.TTransportException) as tx:
274         logging.error('%s' , tx.message)
275       except (socket.timeout) as tx:
276         self.dominoclient.handle_RPC_timeout(pub_msg)
277       except (socket.error) as tx:
278         logging.error('%s' , tx.message)
279       self.seqno = self.seqno + 1
280
281   def heartbeat(self):
282     if self.state == 'UNREGISTERED':
283       self.start()
284           
285     logging.info('%d Sending heartbeat', self.UDID)
286     hbm = HeartBeatMessage()         
287     hbm.domino_udid = self.UDID        
288     hbm.seq_no = self.seqno         
289
290     try:
291       hbm_r = self.sender().d_heartbeat(hbm)
292       logging.info('heart beat received from: %d ,sequence number: %d' , hbm_r.domino_udid, hbm_r.seq_no)
293     except (Thrift.TException, TSocket.TTransportException) as tx:
294       logging.error('%s' , tx.message)
295     except (socket.timeout) as tx:
296       self.handle_RPC_timeout(hbm)
297     except:
298       logging.error('Unexpected error: %s', sys.exc_info()[0])
299     
300     self.seqno = self.seqno + 1    
301
302   def publish(self, toscafile):
303     if self.state == 'UNREGISTERED':
304       self.start()
305
306     logging.info('Publishing the template file: ' + toscafile)
307     pub_msg = PublishMessage()
308     pub_msg.domino_udid = self.UDID
309     pub_msg.seq_no = self.seqno
310     pub_msg.template_type = 'tosca-nfv-v1.0'
311
312     try:
313       pub_msg.template = miscutil.read_templatefile(toscafile)
314     except IOError as e:
315       logging.error('I/O error(%d): %s' , e.errno, e.strerror)
316       return
317     try:
318       pub_msg_r = self.sender().d_publish(pub_msg)
319       logging.info('Publish Response is received from: %d ,sequence number: %d', pub_msg_r.domino_udid, pub_msg_r.seq_no)
320     except (Thrift.TException, TSocket.TTransportException) as tx:
321       print '%s' % (tx.message)
322     except (socket.timeout) as tx:
323       self.handle_RPC_timeout(pub_msg)
324
325     self.seqno = self.seqno + 1
326
327   def subscribe(self, labels, templateTypes, label_op, template_op):
328      if self.state == 'UNREGISTERED':
329        self.start()
330
331      logging.info('subscribing labels %s and templates %s', labels, templateTypes)
332      #send subscription message
333      sub_msg = SubscribeMessage()
334      sub_msg.domino_udid = self.UDID
335      sub_msg.seq_no = self.seqno
336      sub_msg.template_op = template_op
337      sub_msg.supported_template_types = templateTypes
338      sub_msg.label_op = label_op
339      sub_msg.labels = labels
340      try:
341        sub_msg_r = self.sender().d_subscribe(sub_msg)
342        logging.info('Subscribe Response is received from: %d ,sequence number: %d', sub_msg_r.domino_udid,sub_msg_r.seq_no)
343      except (Thrift.TException, TSocket.TTransportException) as tx: 
344        logging.error('%s' , tx.message)
345      except (socket.timeout) as tx: 
346        self.handle_RPC_timeout(sub_msg)
347
348      self.seqno = self.seqno + 1 
349
350   def stop(self):
351     try:
352       self.communicationHandler.closeconnection()
353     except Thrift.TException, tx:
354       logging.error('%s' , tx.message)
355     
356   def sender(self):
357     return self.communicationHandler.sender
358
359   def startCLI(self, interactive):
360     self.CLIservice = DominoClientCLIService(self, self.communicationHandler, interactive)
361     logging.info('CLI Service is starting')
362     self.CLIservice.start()
363     #to wait until CLI service is finished
364     #self.CLIservice.join()
365
366   def set_serviceport(self, port):
367     self.serviceport = port
368
369   def set_CLIport(self, cliport):
370     self.CLIport = cliport
371
372   def set_dominoserver_ipaddr(self, ipaddr):
373     self.dominoserver_IP = ipaddr
374
375   def handle_RPC_timeout(self, RPCmessage):
376     # TBD: handle each RPC timeout separately
377     if RPCmessage.messageType == HEART_BEAT:
378       logging.debug('RPC Timeout for message type: HEART_BEAT') 
379     elif RPCmessage.messageType == PUBLISH:
380       logging.debug('RPC Timeout for message type: PUBLISH')
381     elif RPCmessage.messageType == SUBSCRIBE:
382       logging.debug('RPC Timeout for message type: SUBSCRIBE')
383     elif RPCmessage.messageType == REGISTER:
384       logging.debug('RPC Timeout for message type: REGISTER')
385     elif RPCmessage.messageType == QUERY:
386       logging.debug('RPC Timeout for message type: QUERY') 
387
388 def main(argv):
389   client = DominoClient()
390   loglevel = LOGLEVEL
391   interactive = INTERACTIVE
392   #process input arguments
393   try:
394       opts, args = getopt.getopt(argv,"hc:p:i:l:",["conf=","port=","ipaddr=","log=","iac=","cliport="])
395   except getopt.GetoptError:
396       print 'DominoClient.py -c/--conf <configfile> -p/--port <socketport> -i/--ipaddr <IPaddr> -l/--log <loglevel> --iac=true/false'
397       sys.exit(2)
398   for opt, arg in opts:
399       if opt == '-h':
400          print 'DominoClient.py -c/--conf <configfile> -p/--port <socketport> -i/--ipaddr <IPaddr> -l/--log <loglevel> --iac=true/false'
401          sys.exit()
402       elif opt in ("-c", "--conf"):
403          configfile = arg
404       elif opt in ("-p", "--port"):
405          client.set_serviceport(int(arg))
406       elif opt in ("-i", "--ipaddr"):
407          client.set_dominoserver_ipaddr(arg)
408       elif opt in ("-l", "--log"):
409          loglevel = arg
410       elif opt in ("--iac"):
411          interactive = arg.upper()
412       elif opt in ("--cliport"):
413          client.set_CLIport(int(arg))
414
415   #Set logging level
416   numeric_level = getattr(logging, loglevel.upper(), None)
417   try:
418     if not isinstance(numeric_level, int):
419       raise ValueError('Invalid log level: %s' % loglevel)
420     logging.basicConfig(filename=logfile,level=numeric_level, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
421   except ValueError, ex:
422     print ex.message
423     exit()
424  
425   #The client is starting
426   logging.debug('Domino Client Starting...')
427   client.start()
428   client.startCLI(interactive)
429   client.start_communicationService()
430
431 if __name__ == "__main__":
432    main(sys.argv[1:])
433