source: src/common/bin/gnuboat-log-uploader@ 8818b65

debian/bullseye
Last change on this file since 8818b65 was 7be94aa, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago
  • Added yapf style config (src/python-style.yapf)
    • Updated all files to the yapf formatted version
  • Property mode set to 100644
File size: 7.7 KB
Line 
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3'''
4 Copyright (C) 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
5
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
18'''
19
20import os
21import sys
22import json
23import requests
24import argparse
25
26
27class Log:
28 """
29 Workaround for @dataclass, until python 3.7 is available in main distros
30 """
31 def __init__(
32 self, water_id, device_id, gauge_id, gauge_height, comment, logfile
33 ):
34 self.water_id = water_id
35 self.device_id = device_id
36 self.gauge_id = gauge_id
37 self.gauge_height = gauge_height
38 self.comment = comment
39 self.logfile = logfile
40
41 def log_creation(self):
42 return {
43 'water': self.water_id,
44 'device': self.device_id,
45 'gauge': self.gauge_id,
46 'gaugeHeight': self.gauge_height,
47 'comment': self.comment
48 }
49
50
51def to_int(value_string):
52 try:
53 return int(value_string)
54 except:
55 return None
56
57
58def to_float(value_string):
59 try:
60 return float(value_string)
61 except:
62 return None
63
64
65def header(api_key):
66 return {
67 'X-API-KEY': api_key
68 # 'Content-type': 'multipart/form-data'
69 }
70
71
72def create_log(log, url, api_key):
73 response = requests.post(
74 url, json=log.log_creation(), headers=header(api_key)
75 )
76
77 if response.status_code != 200:
78 print(
79 'ERROR: Could not create LogMetaData for logfile {}'.format(
80 log.logfile
81 )
82 )
83 print(' Response status code: {}'.format(response.status_code))
84 print(' Response: \n{}'.format(response.text))
85 print(' Request headers: {}'.format(response.request.headers))
86 print(' Request body: {}'.format(response.request.body))
87 sys.exit(5)
88
89 data = response.json()
90 if not 'logId' in data:
91 print('ERROR: No log id returned')
92 sys.exit(6)
93 return data["logId"]
94
95
96def upload_log(log_id, log, url, api_key):
97 fileContent = open(log.logfile, 'rb')
98 headers = header(api_key)
99 headers["Accept"] = "application/json"
100 response = requests.post(
101 "{}/{}".format(url, log_id), data=fileContent, headers=headers
102 )
103 if response.status_code != 200:
104 print('ERROR: Could not upload log for logfile {}'.format(log.logfile))
105 print("Response status code: {}".format(response.status_code))
106 print("Response: \n{}".format(response.text))
107 sys.exit(7)
108
109
110def main(argv):
111 input_file_path = None
112 url = None
113 api_key = None
114
115 parser = argparse.ArgumentParser(
116 description='Uploads logfiles to GNUBoat server'
117 )
118 parser.add_argument(
119 'input_file',
120 metavar='input_file_path',
121 type=str,
122 help=
123 'JSON file with water, gauge, device, logfiles and correction data to be processed'
124 )
125 parser.add_argument(
126 '-s',
127 '--server',
128 dest='server',
129 type=str,
130 help='Server host and port to upload the logsfiles to'
131 )
132 parser.add_argument(
133 '-k',
134 '--api-key',
135 dest='api_key',
136 type=str,
137 help='API Key for authorisation'
138 )
139 arguments = parser.parse_args(argv)
140
141 if arguments.input_file is None:
142 print('ERROR: No input file specified')
143 sys.exit(2)
144 elif not os.path.exists(arguments.input_file):
145 print(
146 'ERROR: Specified input file does not exists: {}'.format(
147 arguments.input_file
148 )
149 )
150 sys.exit(3)
151 else:
152 input_file_path = arguments.input_file
153
154 if arguments.server is None:
155 print('ERROR: No server specified')
156 sys.exit(2)
157 else:
158 url = 'http://{}/mapservice/v1/logs'.format(arguments.server)
159
160 if arguments.api_key is None:
161 print('ERROR: No API key specified')
162 sys.exit(2)
163 else:
164 api_key = arguments.api_key
165
166 logs_checked = []
167 print('Checking input from {}'.format(input_file_path))
168 with open(input_file_path, 'r') as input_file:
169 logs = json.load(input_file)
170 for log in logs:
171 if not 'water' in log:
172 print('ERROR: No water in log {}'.format(json.dumps(log)))
173 sys.exit(4)
174 water_id = to_int(log['water'])
175 if not water_id:
176 print(
177 'ERROR: Could not convert water to int {}'.format(
178 log['water']
179 )
180 )
181 sys.exit(4)
182
183 if not 'gauge' in log:
184 print('ERROR: No gauge in log {}'.format(json.dumps(log)))
185 sys.exit(4)
186 gauge_id = to_int(log['gauge'])
187 if not gauge_id:
188 print(
189 'ERROR: Could not convert gauge to int {}'.format(
190 log['gauge']
191 )
192 )
193 sys.exit(4)
194
195 if not 'device' in log:
196 print('ERROR: No device in log {}'.format(json.dumps(log)))
197 sys.exit(4)
198 device_id = to_int(log['device'])
199 if not device_id:
200 print(
201 'ERROR: Could not convert device to int {}'.format(
202 log['device']
203 )
204 )
205 sys.exit(4)
206
207 if not 'gaugeHeight' in log:
208 print(
209 'ERROR: No gaugeHeight in log {}'.format(json.dumps(log))
210 )
211 sys.exit(4)
212 gauge_height = to_float(log['gaugeHeight'])
213 if not gauge_height:
214 print(
215 'ERROR: Could not convert gaugeHeight to float {}'.format(
216 log['gaugeHeight']
217 )
218 )
219 sys.exit(4)
220
221 if not 'file' in log:
222 print('ERROR: No file in log {}'.format(json.dumps(log)))
223 sys.exit(4)
224
225 comment = ''
226 if 'comment' in log:
227 comment = log['comment']
228
229 logfile = os.path.join(os.path.dirname(__file__), log['file'])
230 if not os.path.exists(logfile):
231 logfile_rel = os.path.join(
232 os.path.dirname(input_file_path), log['file']
233 )
234 if not os.path.exists(logfile_rel):
235 print(
236 'ERROR: Logfile not found at {} or {}'.format(
237 logfile, logfile_rel
238 )
239 )
240 sys.exit(4)
241 else:
242 logfile = logfile_rel
243 logs_checked.append(
244 Log(
245 water_id, device_id, gauge_id, gauge_height, comment,
246 logfile
247 )
248 )
249
250 print('Uploading {} logs'.format(len(logs_checked)))
251 for log in logs_checked:
252 log_id = create_log(log, url, api_key)
253 upload_log(log_id, log, url, api_key)
254 print(' Finished {}'.format(log.logfile))
255
256
257if __name__ == "__main__":
258 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.