Auto Generated INFO.yaml file
[domino.git] / DominoClient.py
index 19aaa65..b417186 100755 (executable)
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 
-#Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+#Copyright 2016 Open Platform for NFV Project, Inc. and its contributors
 #   Licensed under the Apache License, Version 2.0 (the "License");
 #   you may not use this file except in compliance with the License.
 #   You may obtain a copy of the License at
@@ -15,9 +15,8 @@
 import sys, os, glob, threading
 import getopt, socket
 import logging, errno
+import uuid
 
-#sys.path.append('gen-py')
-#sys.path.insert(0, glob.glob('./lib/py/build/lib.*')[0])
 sys.path.insert(0, glob.glob('./lib')[0])
 
 from dominoRPC import Communication
@@ -46,25 +45,16 @@ class CommunicationHandler:
   def __init__(self, dominoclient):
     self.log = {}
     self.dominoClient = dominoclient
-    try:
-      # Make socket
-      transport = TSocket.TSocket(DOMINO_SERVER_IP, DOMINO_SERVER_PORT)
-      transport.setTimeout(THRIFT_RPC_TIMEOUT_MS)
-      # Add buffering to compensate for slow raw sockets
-      self.transport = TTransport.TBufferedTransport(transport)
-      # Wrap in a protocol
-      self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
-      # Create a client to use the protocol encoder
-      self.sender = Communication.Client(self.protocol)
-    except Thrift.TException, tx: 
-      logging.error('%s' , tx.message)
+    self.transport = None
+    self.protocol = None
+    self.sender = None
 
   # Template Push from Domino Server is received
   # Actions:
   #       - Depending on Controller Domain, call API
   #       - Respond Back with Push Response
   def d_push(self, push_msg):
-    logging.info('%d Received Template File', self.dominoClient.UDID)
+    logging.info('%s Received Template File', self.dominoClient.UDID)
     # Retrieve the template file
     try:
       os.makedirs(TOSCA_RX_DIR+str(self.dominoClient.UDID))
@@ -75,7 +65,7 @@ class CommunicationHandler:
         logging.error('IGNORING error in creating %s. Err no: %d', exception.errno)
 
     try:  
-      miscutil.write_templatefile(TOSCA_RX_DIR+str(self.dominoClient.UDID)+'/'+str(push_msg.seq_no)+'.yaml' , push_msg.template)
+      miscutil.write_templatefile(TOSCA_RX_DIR+str(self.dominoClient.UDID)+'/'+str(push_msg.template_UUID)+'.yaml' , push_msg.template)
     except:    
       logging.error('FAILED to write the pushed file: %s', sys.exc_info()[0])
       push_r = PushResponseMessage()
@@ -110,7 +100,19 @@ class CommunicationHandler:
 
   
   def openconnection(self):
-    self.transport.open()
+    try:
+      # Make socket
+      transport = TSocket.TSocket(self.dominoClient.dominoserver_IP, DOMINO_SERVER_PORT)
+      transport.setTimeout(THRIFT_RPC_TIMEOUT_MS)
+      # Add buffering to compensate for slow raw sockets
+      self.transport = TTransport.TBufferedTransport(transport)
+      # Wrap in a protocol
+      self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
+      # Create a client to use the protocol encoder
+      self.sender = Communication.Client(self.protocol)
+      self.transport.open()
+    except Thrift.TException, tx:
+      logging.error('%s' , tx.message)
 
   def closeconnection():
     self.transport.close()
@@ -125,12 +127,10 @@ class CLIHandler:
     self.CLIservice = CLIservice
 
   def d_CLI(self, msg):
-    logging.info('Received CLI %s', msg.CLI_input)
+    #logging.info('Received CLI %s', msg.CLI_input) #breaks testing due to random TUIDs
 
-    self.CLIservice.process_input(msg.CLI_input)
-    
     CLIrespmsg = CLIResponse()
-    CLIrespmsg.CLI_response = "Testing..."
+    CLIrespmsg.CLI_response = self.CLIservice.process_input(msg.CLI_input)
     return CLIrespmsg
  
 
@@ -143,24 +143,29 @@ class DominoClientCLIService(threading.Thread):
 
   def process_input(self, args):
     if len(args) == 0:
-      print 'Empty API body'
-      return
+      return 'Empty API body'
 
     try:
       if args[0] == 'heartbeat':
         self.dominoclient.heartbeat()
 
       elif args[0] == 'publish':
-        opts, args = getopt.getopt(args[1:],"t:",["tosca-file="])
+        opts, args = getopt.getopt(args[1:],"t:k:",["tosca-file=","tuid"])
         if len(opts) == 0:
-         print '\nUsage: publish -t <toscafile>'
+         print '\nUsage: publish -t <toscafile> -k <TUID>'
          return
-
+        
+        template_UUID = None
+        toscafile = None
         for opt, arg in opts:
          if opt in ('-t', '--tosca-file'):
            toscafile = arg
-       
-        self.dominoclient.publish(toscafile)
+          elif opt in ('-k', '--tuid'):
+            template_UUID = arg
+        if toscafile is not None:
+          self.dominoclient.publish(toscafile,template_UUID)
+        else:
+          print '\nUsage: publish -t <toscafile> -k <TUID>'
 
       elif args[0] == 'subscribe':
         labels = []    
@@ -193,6 +198,12 @@ class DominoClientCLIService(threading.Thread):
       elif args[0] == 'register':
         self.dominoclient.start()
 
+      elif args[0] == 'list-tuids':
+        return self.dominoclient.query(['list-tuids'])
+
+      else:
+        return 'Command is misentered or not supported!'
+
     except getopt.GetoptError:
       print 'Command is misentered or not supported!'
 
@@ -214,7 +225,9 @@ class DominoClientCLIService(threading.Thread):
 
          sys.stdout.write('>>')
         #process input arguments
-         self.process_input(args)
+         resp_msg = self.process_input(args)
+         if resp_msg is not None:
+           print resp_msg
     else: #domino cli-client is used, listen for the CLI rpc calls
       cliHandler = CLIHandler(self.dominoclient, self)
       processor = DominoClientCLI.Processor(cliHandler)
@@ -228,6 +241,8 @@ class DominoClientCLIService(threading.Thread):
 
 class DominoClient:
   def __init__(self):
+
+
     self.communicationHandler = CommunicationHandler(self)
     self.processor = None
     self.transport = None
@@ -237,9 +252,8 @@ class DominoClient:
 
     self.CLIservice = None
 
-    self.serviceport = 9091
-    self.dominoserver_IP = 'localhost'
-
+    self.serviceport = DOMINO_CLIENT_PORT
+    self.dominoserver_IP = DOMINO_SERVER_IP
     self.CLIport = DOMINO_CLI_PORT 
 
     #Start from UNREGISTERED STATE
@@ -292,7 +306,7 @@ class DominoClient:
       except (Thrift.TException, TSocket.TTransportException) as tx:
         logging.error('%s' , tx.message)
       except (socket.timeout) as tx:
-        self.dominoclient.handle_RPC_timeout(pub_msg)
+        self.handle_RPC_timeout(reg_msg)
       except (socket.error) as tx:
         logging.error('%s' , tx.message)
       self.seqno = self.seqno + 1
@@ -301,14 +315,14 @@ class DominoClient:
     if self.state == 'UNREGISTERED':
       self.start()
           
-    logging.info('%d Sending heartbeat', self.UDID)
+    logging.info('%s Sending heartbeat', self.UDID)
     hbm = HeartBeatMessage()         
     hbm.domino_udid = self.UDID        
     hbm.seq_no = self.seqno         
 
     try:
       hbm_r = self.sender().d_heartbeat(hbm)
-      logging.info('heart beat received from: %d ,sequence number: %d' , hbm_r.domino_udid, hbm_r.seq_no)
+      logging.info('heart beat received from: %s ,sequence number: %d' , hbm_r.domino_udid, hbm_r.seq_no)
     except (Thrift.TException, TSocket.TTransportException) as tx:
       logging.error('%s' , tx.message)
     except (socket.timeout) as tx:
@@ -318,7 +332,7 @@ class DominoClient:
     
     self.seqno = self.seqno + 1    
 
-  def publish(self, toscafile):
+  def publish(self, toscafile, template_UUID=None):
     if self.state == 'UNREGISTERED':
       self.start()
 
@@ -327,6 +341,8 @@ class DominoClient:
     pub_msg.domino_udid = self.UDID
     pub_msg.seq_no = self.seqno
     pub_msg.template_type = 'tosca-nfv-v1.0'
+    if template_UUID is not None:
+      pub_msg.template_UUID = template_UUID
 
     try:
       pub_msg.template = miscutil.read_templatefile(toscafile)
@@ -335,7 +351,7 @@ class DominoClient:
       return
     try:
       pub_msg_r = self.sender().d_publish(pub_msg)
-      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)
+      logging.info('Publish Response is received from: %s ,sequence number: %d Status: %d', pub_msg_r.domino_udid, pub_msg_r.seq_no, pub_msg_r.responseCode)
     except (Thrift.TException, TSocket.TTransportException) as tx:
       print '%s' % (tx.message)
     except (socket.timeout) as tx:
@@ -358,7 +374,7 @@ class DominoClient:
      sub_msg.labels = labels
      try:
        sub_msg_r = self.sender().d_subscribe(sub_msg)
-       logging.info('Subscribe Response is received from: %d ,sequence number: %d', sub_msg_r.domino_udid,sub_msg_r.seq_no)
+       logging.info('Subscribe Response is received from: %s ,sequence number: %d', sub_msg_r.domino_udid,sub_msg_r.seq_no)
      except (Thrift.TException, TSocket.TTransportException) as tx: 
        logging.error('%s' , tx.message)
      except (socket.timeout) as tx: 
@@ -366,6 +382,24 @@ class DominoClient:
 
      self.seqno = self.seqno + 1 
 
+  def query(self, queryString, template_UUID=None):
+    logging.info('querying Domino Server: %s', queryString)
+    query_msg = QueryMessage()
+    query_msg.domino_udid = self.UDID
+    query_msg.seq_no = self.seqno
+    query_msg.queryString = queryString
+    query_msg.template_UUID = template_UUID 
+    self.seqno = self.seqno + 1
+    try:
+      query_msg_r = self.sender().d_query(query_msg)
+      logging.info('Query Response is received from: %s ,sequence number: %d', query_msg_r.domino_udid,query_msg_r.seq_no)
+      if (query_msg_r.queryResponse is not None) and (len(query_msg_r.queryResponse)>0):
+        return query_msg_r.queryResponse
+    except (Thrift.TException, TSocket.TTransportException) as tx:
+      logging.error('%s' , tx.message)
+    except (socket.timeout) as tx:
+      self.handle_RPC_timeout(query_msg)
+
   def stop(self):
     try:
       self.communicationHandler.closeconnection()
@@ -404,13 +438,13 @@ class DominoClient:
     elif RPCmessage.messageType == QUERY:
       logging.debug('RPC Timeout for message type: QUERY') 
 
-def main(argv):
+def main():
   client = DominoClient()
   loglevel = LOGLEVEL
   interactive = INTERACTIVE
   #process input arguments
   try:
-      opts, args = getopt.getopt(argv,"hc:p:i:l:",["conf=","port=","ipaddr=","log=","iac=","cliport="])
+      opts, args = getopt.getopt(sys.argv[1:],"hc:p:i:l:",["conf=","port=","ipaddr=","log=","iac=","cliport=","uuid=","regmod="])
   except getopt.GetoptError:
       print 'DominoClient.py -c/--conf <configfile> -p/--port <socketport> -i/--ipaddr <IPaddr> -l/--log <loglevel> --iac=true/false --cliport <cliport>'
       sys.exit(2)
@@ -430,7 +464,11 @@ def main(argv):
          interactive = arg.upper()
       elif opt in ("--cliport"):
          client.set_CLIport(int(arg))
-
+      elif opt in ("--uuid"):
+         client.UDID = arg
+      elif opt in ("--regmod"):
+         if arg.upper() == 'REGISTERED': 
+           client.state = 'REGISTERED'
   #Set logging level
   numeric_level = getattr(logging, loglevel.upper(), None)
   try:
@@ -448,5 +486,4 @@ def main(argv):
   client.start_communicationService()
 
 if __name__ == "__main__":
-   main(sys.argv[1:])
-
+  sys.exit(main())