Ignore:
Timestamp:
Apr 11, 2020, 4:46:15 PM (7 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, master
Children:
3db3d13
Parents:
da2be70
Message:
  • Added yapf style config (src/python-style.yapf)
    • Updated all files to the yapf formatted version
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/common/bin/gnuboat-log-uploader

    rda2be70 r7be94aa  
    2424import argparse
    2525
     26
    2627class Log:
    27         """
     28    """
    2829                Workaround for @dataclass, until python 3.7 is available in main distros
    2930        """
    30         def __init__(self, water_id, device_id, gauge_id, gauge_height, comment, logfile):
    31                 self.water_id = water_id
    32                 self.device_id = device_id
    33                 self.gauge_id = gauge_id
    34                 self.gauge_height = gauge_height
    35                 self.comment = comment
    36                 self.logfile = logfile
    37                
    38         def log_creation(self):
    39                 return {
    40                         'water': self.water_id,
    41                         'device': self.device_id,
    42                         'gauge': self.gauge_id,
    43                         'gaugeHeight': self.gauge_height,
    44                         'comment': self.comment
    45                 }
     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
    4650
    4751def to_int(value_string):
    48         try:
    49                 return int(value_string)
    50         except:
    51                 return None
     52    try:
     53        return int(value_string)
     54    except:
     55        return None
     56
    5257
    5358def to_float(value_string):
    54         try:
    55                 return float(value_string)
    56         except:
    57                 return None
     59    try:
     60        return float(value_string)
     61    except:
     62        return None
     63
    5864
    5965def header(api_key):
    60         return {
    61                 'X-API-KEY': api_key
    62         #       'Content-type': 'multipart/form-data'
    63         }
     66    return {
     67        'X-API-KEY': api_key
     68        #       'Content-type': 'multipart/form-data'
     69    }
     70
    6471
    6572def create_log(log, url, api_key):
    66         response = requests.post(url,
    67                 json = log.log_creation(),
    68                 headers = header(api_key)
    69         )
    70        
    71         if response.status_code != 200:
    72                 print('ERROR: Could not create LogMetaData for logfile {}'.format(log.logfile))
    73                 print('  Response status code: {}'.format(response.status_code))
    74                 print('  Response:             \n{}'.format(response.text))
    75                 print('  Request headers:      {}'.format(response.request.headers))
    76                 print('  Request body:         {}'.format(response.request.body))
    77                 sys.exit(5)
    78                
    79         data = response.json()
    80         if not 'logId' in data:
    81                 print('ERROR: No log id returned')
    82                 sys.exit(6)
    83         return data["logId"]
     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
    8495
    8596def upload_log(log_id, log, url, api_key):
    86         fileContent = open(log.logfile, 'rb')
    87         headers = header(api_key)
    88         headers["Accept"] = "application/json"
    89         response = requests.post(
    90                 "{}/{}".format(url, log_id),
    91                 data = fileContent,
    92                 headers = headers
    93         )
    94         if response.status_code != 200:
    95                 print('ERROR: Could not upload log for logfile {}'.format(log.logfile))
    96                 print("Response status code: {}".format(response.status_code))
    97                 print("Response:             \n{}".format(response.text))
    98                 sys.exit(7)
     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
    99109
    100110def main(argv):
    101         input_file_path = None
    102         url = None
    103         api_key = None
    104        
    105         parser = argparse.ArgumentParser(description='Uploads logfiles to GNUBoat server')
    106         parser.add_argument('input_file', metavar='input_file_path', type=str,
    107                                                 help='JSON file with water, gauge, device, logfiles and correction data to be processed')
    108         parser.add_argument('-s', '--server', dest='server', type=str,
    109                         help='Server host and port to upload the logsfiles to')
    110         parser.add_argument('-k', '--api-key', dest='api_key', type=str,
    111                         help='API Key for authorisation')
    112         arguments = parser.parse_args(argv)
    113        
    114         if arguments.input_file is None:
    115                 print('ERROR: No input file specified')
    116                 sys.exit(2)
    117         elif not os.path.exists(arguments.input_file):
    118                 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
    119                 sys.exit(3)
    120         else:
    121                 input_file_path = arguments.input_file
    122        
    123         if arguments.server is None:
    124                 print('ERROR: No server specified')
    125                 sys.exit(2)
    126         else:
    127                 url = 'http://{}/mapservice/v1/logs'.format(arguments.server)
    128                
    129         if arguments.api_key is None:
    130                 print('ERROR: No API key specified')
    131                 sys.exit(2)
    132         else:
    133                 api_key = arguments.api_key
    134                
    135         logs_checked = []
    136         print('Checking input from {}'.format(input_file_path))
    137         with open(input_file_path, 'r') as input_file:
    138                 logs = json.load(input_file)
    139                 for log in logs:
    140                         if not 'water' in log:
    141                                 print('ERROR: No water in log {}'.format(json.dumps(log)))
    142                                 sys.exit(4)
    143                         water_id = to_int(log['water'])
    144                         if not water_id:
    145                                 print('ERROR: Could not convert water to int {}'.format(log['water']))
    146                                 sys.exit(4)
    147                        
    148                         if not 'gauge' in log:
    149                                 print('ERROR: No gauge in log {}'.format(json.dumps(log)))
    150                                 sys.exit(4)
    151                         gauge_id = to_int(log['gauge'])
    152                         if not gauge_id:
    153                                 print('ERROR: Could not convert gauge to int {}'.format(log['gauge']))
    154                                 sys.exit(4)
    155                                
    156                         if not 'device' in log:
    157                                 print('ERROR: No device in log {}'.format(json.dumps(log)))
    158                                 sys.exit(4)
    159                         device_id = to_int(log['device'])
    160                         if not device_id:
    161                                 print('ERROR: Could not convert device to int {}'.format(log['device']))
    162                                 sys.exit(4)
    163                                
    164                         if not 'gaugeHeight' in log:
    165                                 print('ERROR: No gaugeHeight in log {}'.format(json.dumps(log)))
    166                                 sys.exit(4)
    167                         gauge_height = to_float(log['gaugeHeight'])
    168                         if not gauge_height:
    169                                 print('ERROR: Could not convert gaugeHeight to float {}'.format(log['gaugeHeight']))
    170                                 sys.exit(4)
    171                                
    172                         if not 'file' in log:
    173                                 print('ERROR: No file in log {}'.format(json.dumps(log)))
    174                                 sys.exit(4)
    175                                
    176                         comment = ''
    177                         if 'comment' in log:
    178                                 comment = log['comment']
    179                        
    180                         logfile = os.path.join(os.path.dirname(__file__), log['file'])
    181                         if not os.path.exists(logfile):
    182                                 logfile_rel = os.path.join(os.path.dirname(input_file_path), log['file'])
    183                                 if not os.path.exists(logfile_rel):
    184                                         print('ERROR: Logfile not found at {} or {}'.format(logfile, logfile_rel))
    185                                         sys.exit(4)
    186                                 else:
    187                                         logfile = logfile_rel
    188                         logs_checked.append(Log(water_id, device_id, gauge_id, gauge_height, comment, logfile))
    189        
    190         print('Uploading {} logs'.format(len(logs_checked)))
    191         for log in logs_checked:
    192                 log_id = create_log(log, url, api_key)
    193                 upload_log(log_id, log, url, api_key)
    194                 print(' Finished {}'.format(log.logfile))
     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
    195256
    196257if __name__ == "__main__":
    197         main(sys.argv[1:])
     258    main(sys.argv[1:])
Note: See TracChangeset for help on using the changeset viewer.