Catalog alignment
[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(pycurl.SSL_VERIFYPEER, 0)
60                         c.setopt(pycurl.SSL_VERIFYHOST, 0)
61
62                 res = c.perform()
63         
64                 #print("Before get response code")      
65                 httpRes = c.getinfo(c.RESPONSE_CODE)
66                 if (httpRes != None):
67                         debug("http response=", httpRes)
68                 #print('Status: ' + str(responseCode))
69                 debug(buffer.getvalue())
70                 c.close()
71
72                 return (ELEMENT_NAME, httpRes, buffer.getvalue())
73
74         except Exception as inst:
75                 print("ERROR=" + str(inst))
76                 return (ELEMENT_NAME, None, None)                               
77
78
79 def usage():
80         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>]'
81         print "----------------- Example -------------------"
82         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"
83
84 def main(argv):
85         print 'Number of arguments:', len(sys.argv), 'arguments.'
86
87         beHost = 'localhost' 
88         bePort = '8080'
89         adminUser = 'jh0003'
90         debugf = None
91         location = None
92         element = None
93         scheme = 'http'
94
95         try:
96                 opts, args = getopt.getopt(argv,"i:p:u:d:l:e:h:s:",["ip=","port=","user=","location=","element=", "debug=","scheme="])
97         except getopt.GetoptError:
98                 usage()
99                 error_and_exit(2, 'Invalid input')
100                  
101         for opt, arg in opts:
102         #print opt, arg
103                 if opt == '-h':
104                         usage()                        
105                         sys.exit(3)
106                 elif opt in ("-i", "--ip"):
107                         beHost = arg
108                 elif opt in ("-p", "--port"):
109                         bePort = arg
110                 elif opt in ("-u", "--user"):
111                         adminUser = arg
112                 elif opt in ("-l", "--location"):
113                         location = arg
114                 elif opt in ("-e", "--element"):
115                         element = arg
116                 elif opt in ("-s", "--scheme"):
117                         scheme = arg
118                 elif opt in ("-d", "--debug"):
119                         print arg
120                         debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
121
122         print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
123         
124         if ( beHost == None ):
125                 usage()
126                 sys.exit(3)
127
128         if (debugf != None):
129                 print 'set debug mode to ' + str(debugf)
130                 importCommon.debugFlag = debugf
131
132         if (location == None):
133                 print 'Missing file location'
134                 usage()
135                 sys.exit(3)
136                 
137         if (element == None):
138                 print 'Missing element name. E.g. root, compute, ...'
139                 usage()
140                 sys.exit(3)
141
142         #pathdir = os.path.dirname(os.path.realpath(sys.argv[0]))
143
144         #baseFileLocation = pathdir + "/../../../import/tosca/"
145         #fileDir = baseFileLocation + "user-normative-types/"
146         
147         #normativeType = "root1"        
148
149         result = createUserNormativeType(scheme, beHost, bePort, adminUser, location, element)
150         #result = createUserNormativeType(beHost, bePort, adminUser, fileDir, normativeType)
151         print "---------------------------------------"
152         print "{0:30} | {1:6}".format(result[0], result[1])
153         print "---------------------------------------"
154
155         if ( result[1] == None or result[1] not in [200, 201] ) :
156                 print "Failed creating normative type " + element + ". " + str(result[1])                               
157                 error_and_exit(1, None)
158
159         error_and_exit(0, None)
160
161 if __name__ == "__main__":
162         main(sys.argv[1:])
163