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