Sync Integ to Master
[sdc.git] / catalog-be / src / main / resources / scripts / import / tosca / importNodeType.py
1 import pycurl
2 import sys, getopt, os
3 from StringIO import StringIO
4 import json
5 import copy
6 from importCommon import *
7 import importCommon
8 import zipfile
9 ################################################################################################################################################
10 #                                                                                                                                                                                                                                                                                      #        
11 ################################################################################################################################################
12
13 def createZipFromYml(ymlFile, zipFile):
14         zip = zipfile.ZipFile(zipFile, 'w', zipfile.ZIP_DEFLATED)
15         
16         zip.write(ymlFile, os.path.basename(ymlFile)) 
17         zip.close()
18
19 def createUserNormativeType(scheme, beHost, bePort, adminUser, fileDir, ELEMENT_NAME):
20         
21         try:
22                 log("in create normative type ", ELEMENT_NAME)
23                 debug("userId", adminUser)
24                 debug("fileDir", fileDir)
25                 
26                 buffer = StringIO()
27                 c = pycurl.Curl()
28
29                 url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart'
30                 c.setopt(c.URL, url)
31                 c.setopt(c.POST, 1)             
32
33                 adminHeader = 'USER_ID: ' + adminUser
34                 #c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader])
35                 c.setopt(pycurl.HTTPHEADER, [adminHeader])
36
37                 ymlFile = fileDir + ELEMENT_NAME + "/normative-types-new-" + ELEMENT_NAME + ".yml"
38                 zipFile = fileDir + ELEMENT_NAME + "/normative-types-new-" + ELEMENT_NAME + ".zip"
39                 debug(ymlFile)
40                 debug(zipFile)
41                 path = zipFile 
42                 debug("path=" + path)
43                 CURRENT_JSON_FILE=fileDir + ELEMENT_NAME + "/" + ELEMENT_NAME + ".json"
44                 debug(CURRENT_JSON_FILE)
45                 jsonFile = open(CURRENT_JSON_FILE)
46                 
47                 debug("before load json")
48                 json_data = json.load(jsonFile, strict=False)
49                 debug(json_data)
50         
51                 jsonAsStr = json.dumps(json_data)
52                 debug(path)
53                 send = [('resourceMetadata', jsonAsStr), ('resourceZip', (pycurl.FORM_FILE, path))]
54                 debug(send)
55                 c.setopt(pycurl.HTTPPOST, send)         
56
57                 c.setopt(c.WRITEFUNCTION, buffer.write)
58                 if scheme == 'https':
59                         c.setopt(c.SSL_VERIFYPEER, 0)
60
61                 res = c.perform()
62         
63                 #print("Before get response code")      
64                 httpRes = c.getinfo(c.RESPONSE_CODE)
65                 if (httpRes != None):
66                         debug("http response=", httpRes)
67                 #print('Status: ' + str(responseCode))
68                 debug(buffer.getvalue())
69                 c.close()
70
71                 return (ELEMENT_NAME, httpRes, buffer.getvalue())
72
73         except Exception as inst:
74                 print("ERROR=" + str(inst))
75                 return (ELEMENT_NAME, None, None)                               
76
77
78 def usage():
79         print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-l <directory base location> | --location=<directory base location>] [-e <element name> | --element=<element name>]'
80         print "----------------- Example -------------------"
81         print "python importNodeType.py -d false -l  /home/vagrant/catalog-be-1604.0.2.15.6-SNAPSHOT/scripts/import/tosca/../../../import/tosca/user-normative-types/ -e root1"
82
83 def main(argv):
84         print 'Number of arguments:', len(sys.argv), 'arguments.'
85
86         beHost = 'localhost' 
87         bePort = '8080'
88         adminUser = 'jh0003'
89         debugf = None
90         location = None
91         element = None
92         scheme = 'http'
93
94         try:
95                 opts, args = getopt.getopt(argv,"i:p:u:d:l:e:h:s:",["ip=","port=","user=","location=","element=", "debug=","scheme="])
96         except getopt.GetoptError:
97                 usage()
98                 errorAndExit(2, 'Invalid input')
99                  
100         for opt, arg in opts:
101         #print opt, arg
102                 if opt == '-h':
103                         usage()                        
104                         sys.exit(3)
105                 elif opt in ("-i", "--ip"):
106                         beHost = arg
107                 elif opt in ("-p", "--port"):
108                         bePort = arg
109                 elif opt in ("-u", "--user"):
110                         adminUser = arg
111                 elif opt in ("-l", "--location"):
112                         location = arg
113                 elif opt in ("-e", "--element"):
114                         element = arg
115                 elif opt in ("-s", "--scheme"):
116                         scheme = arg
117                 elif opt in ("-d", "--debug"):
118                         print arg
119                         debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
120
121         print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
122         
123         if ( beHost == None ):
124                 usage()
125                 sys.exit(3)
126
127         if (debugf != None):
128                 print 'set debug mode to ' + str(debugf)
129                 importCommon.debugFlag = debugf
130
131         if (location == None):
132                 print 'Missing file location'
133                 usage()
134                 sys.exit(3)
135                 
136         if (element == None):
137                 print 'Missing element name. E.g. root, compute, ...'
138                 usage()
139                 sys.exit(3)
140
141         #pathdir = os.path.dirname(os.path.realpath(sys.argv[0]))
142
143         #baseFileLocation = pathdir + "/../../../import/tosca/"
144         #fileDir = baseFileLocation + "user-normative-types/"
145         
146         #normativeType = "root1"        
147
148         result = createUserNormativeType(scheme, beHost, bePort, adminUser, location, element)
149         #result = createUserNormativeType(beHost, bePort, adminUser, fileDir, normativeType)
150         print "---------------------------------------"
151         print "{0:30} | {1:6}".format(result[0], result[1])
152         print "---------------------------------------"
153
154         if ( result[1] == None or result[1] not in [200, 201] ) :
155                 print "Failed creating normative type " + element + ". " + str(result[1])                               
156                 errorAndExit(1, None)
157
158         errorAndExit(0, None)
159
160 if __name__ == "__main__":
161         main(sys.argv[1:])
162