tdmsws.py 27.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
#!/usr/bin/env python3
#
# tdmsws WS - prototype
#
# (c) 2020 Javier Quinteros, GEOFON team
# <javier@gfz-potsdam.de>
#
# ----------------------------------------------------------------------

"""tdmsws WS - prototype

   :Platform:
       Linux
   :Copyright:
       GEOFON, GFZ Potsdam <geofon@gfz-potsdam.de>
   :License:
       GNU General Public License v3

.. moduleauthor:: Javier Quinteros <javier@gfz-potsdam.de>, GEOFON, GFZ Potsdam
"""

##################################################################
#
# First all the imports
#
##################################################################


import cherrypy
import argparse
from cherrypy.process import plugins
import os
from datetime import datetime
import configparser
from .tdms import TDMS
from obspy import Trace
from io import BytesIO


def str2date(dateiso):
    """Transform a string to a datetime.

    :param dateiso: A datetime in ISO format.
    :type dateiso: string
    :return: A datetime represented the converted input.
    :rtype: datetime
    """
    # In case of empty string
    if not len(dateiso):
        return None

    try:
        dateparts = dateiso.replace('-', ' ').replace('T', ' ')
        dateparts = dateparts.replace(':', ' ').replace('.', ' ')
        dateparts = dateparts.replace('Z', '').split()
        result = datetime(*map(int, dateparts))
    except Exception:
        raise ValueError('{} could not be parsed as datetime.'.format(dateiso))

    return result


def errormessage(code, text):
    template = """Error {0}: {1}

{1}

Usage details are available from <SERVICE DOCUMENTATION URI>

Request:
<SUBMITTED URL>

Request Submitted:
<UTC DATE TIME>

Service version:
<3-LEVEL VERSION>
"""
    return template.format(code, text)


class TdmswsAPI(object):
83
    """Main class including the dispatcher."""
84

85
    def __init__(self, experiment, directory='.'):
86
        """Constructor of the TdmswsAPI object."""
87 88 89 90 91 92 93 94 95 96
        # Save parameters
        self.__experiment = experiment
        self.__directory = directory

        # Get extra fields from the cfg file
        cfgfile = configparser.RawConfigParser()
        cfgfile.read(os.path.join(directory, 'tdsmws.cfg'))
        self.__net = cfgfile.get('NSLC', 'network', fallback='XX')
        self.__cha = cfgfile.get('NSLC', 'channel', fallback='FH1')

97 98
        # Special case for the empty location. Change '' for '--'
        self.__loc = cfgfile.get('NSLC', 'location', fallback='--')
99 100
        if self.__loc == '':
            self.__loc = '--'
101

102 103 104
        self.dataselect = DataselectAPI(experiment, directory)
        self.station = StationAPI(experiment, directory)

105 106 107 108 109 110 111 112 113 114
    @cherrypy.expose
    def index(self):
        cherrypy.response.headers['Content-Type'] = 'text/html'

        # TODO Create an HTML page with a minimum documentation for a user
        try:
            with open('help.html') as fin:
                texthelp = fin.read()
        except FileNotFoundError:
            texthelp = """<html>
115 116 117 118 119 120 121 122 123 124 125 126 127 128
                            <head>tdmsws</head>
                            <body>
                              Default help for the tdmsws service (GEOFON).
                            </body>
                          </html>"""

        return texthelp.encode('utf-8')


@cherrypy.expose
@cherrypy.popargs('wsversion')
class StationAPI(object):
    """Object dispatching methods related to access to streams."""

129
    def __init__(self, experiment, directory='.'):
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
        """Constructor of the StationAPI class."""
        # Save parameters
        self.__experiment = experiment
        self.__directory = directory

        # Get extra fields from the cfg file
        cfgfile = configparser.RawConfigParser()
        cfgfile.read(os.path.join(directory, 'tdsmws.cfg'))
        self.__net = cfgfile.get('NSLC', 'network', fallback='XX')
        self.__cha = cfgfile.get('NSLC', 'channel', fallback='FH1')

        # Special case for the empty location. Change '' for '--'
        self.__loc = cfgfile.get('NSLC', 'location', fallback='--')
        if self.__loc == '':
            self.__loc = '--'

    @cherrypy.expose
    def index(self, wsversion='1'):
        if wsversion != '1':
            # Send Error 400
            message = 'Only Station-WS version 1 is supported'
151
            # self.__log.error(message)
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

        cherrypy.response.headers['Content-Type'] = 'text/html'
        # TODO Create an HTML page with a minimum documentation for a user
        try:
            with open('help.html') as fin:
                texthelp = fin.read()
        except FileNotFoundError:
            texthelp = """<html>
                            <head>tdsmws - Station</head>
                            <body>
                              Default help for the Station web service (GEOFON).
                            </body>
                          </html>"""

        return texthelp.encode('utf-8')

    @cherrypy.expose
171 172 173 174
    def default(self, *args, **kwargs):
        """Use default method to process application.wadl because the dot is not supported in method names"""
        cherrypy.log('default method: %s %s' % (args, kwargs))
        if args[0] != '1':
175 176
            # Send Error 400
            message = 'Only Station-WS version 1 is supported'
177
            # self.__log.error(message)
178 179 180
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

181 182 183 184 185 186 187
        if args[1] != 'application.wadl':
            # Send Error 400
            message = 'Unknown method "%s"' % args[1]
            # self.__log.error(message)
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

188 189 190 191 192 193 194 195 196 197 198 199
        project_dir = os.path.dirname(__file__)

        try:
            with open(os.path.join(project_dir, 'data/station.wadl')) as fin:
                text = fin.read()
                cherrypy.response.headers['Content-Type'] = 'application/xml'
                return text.encode('utf-8')
        except FileNotFoundError:
            pass

        # Send Error 400
        message = 'application.wadl not found!'
200
        # self.__log.error(message)
201 202 203 204 205 206 207 208 209 210 211 212 213
        cherrypy.response.headers['Content-Type'] = 'text/plain'
        raise cherrypy.HTTPError(400,  errormessage(400, message))

    @cherrypy.expose
    def version(self, wsversion='1'):
        """Return the version of this implementation.

        :returns: Version of the system
        :rtype: string
        """
        if wsversion != '1':
            # Send Error 400
            message = 'Only Station-WS version 1 is supported'
214
            # self.__log.error(message)
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

        stationwsversion = '1.1.0'
        cherrypy.response.headers['Content-Type'] = 'text/plain'
        return stationwsversion.encode('utf-8')

    @cherrypy.expose
    def query(self, network='*', net='*', station='*', sta='*', location='*', loc='*', channel='*', cha='*',
              starttime=None, start=None, endtime=None, end=None, minlatitude=-90.0, minlat=-90.0, maxlatitude=90.0,
              maxlat=90.0, minlongitude=-180.0, minlon=-180.0, maxlongitude=180.0, maxlon=180.0, format='xml',
              level='station', wsversion='1', **kwargs):
        """Get data in miniSEED format.

        :param network: Usually the network code configured in the cfg file. It is included just to satisfy the standard
        :type network: str
        :param net: Alias of network
        :type net: str
        :param station: Comma-separated integers identifying of streams to retrieve
        :type station: str
        :param sta: Alias of station
        :type sta: str
        :param location: Usually the location code configured in the cfg file. Included just to satisfy the standard
        :type location: str
        :param loc: Alias of location
        :type loc: str
        :param channel: Usually the channel code configured in the cfg file. It is included just to satisfy the standard
        :type channel: str
        :param cha: Alias of channel
        :type cha: str
        :param starttime: Start time of the time window to access
        :type starttime: str
        :param start: Alias of starttime
        :type start: str
        :param endtime: End time of the time window to access
        :type endtime: str
        :param end: Alias of endtime
        :type end: str
253
        :param format: Format of result, either xml or text. Default value is xml (StationXML)
254 255 256 257 258 259 260 261 262 263 264 265
        :type format: str
        :returns: miniSEED data
        :rtype: bytearray
        :raises: cherrypy.HTTPError
        """

        """Constructor of the StationAPI class."""
        # Check parameters
        # WS version
        if wsversion != '1':
            # Send Error 400
            message = 'Only Station-WS version 1 is supported'
266
            # self.__log.error(message)
267 268 269 270 271 272 273 274
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

        # Format
        # Only text format is currently implemented
        if format != 'text':
            # Send Error 400
            message = 'Only format=text is currently supported'
275
            # self.__log.error(message)
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400,  errormessage(400, message))

        # Network
        if network not in ('*', self.__net) or net not in ('*', self.__net):
            cherrypy.response.status = 204
            return

        # Location
        if location not in ('*', self.__loc) or loc not in ('*', self.__loc):
            cherrypy.response.status = 204
            return

        # Channel
        if channel not in ('*', self.__cha) or cha not in ('*', self.__cha):
            cherrypy.response.status = 204
            return

        # Station and sta
        # Discard the most comprehensive case of '*' and keep the most restricted one
        auxsta = station if sta == '*' else sta

        # Starttime and start
        # Discard the most comprehensive case of None and keep the most restricted one
        starttime = starttime if start is None else start

        # Endtime and end
        # Discard the most comprehensive case of None and keep the most restricted one
        endtime = endtime if end is None else end

        # Station(s)
        try:
            liststa = [] if auxsta == '*' else [int(x) for x in auxsta.split(',')]
        except Exception:
            # Send Error 400
            message = 'Wrong formatted list of stations (%s).' % sta
312
            # self.__log.error(message)
313 314 315 316 317 318 319 320 321
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400,  errormessage(400, message))

        if starttime is not None:
            try:
                startdt = str2date(starttime)
            except Exception:
                # Send Error 400
                message = 'Error converting the "starttime" parameter (%s).' % starttime
322
                # self.__log.error(message)
323 324 325 326 327 328 329 330 331 332 333
                cherrypy.response.headers['Content-Type'] = 'text/plain'
                raise cherrypy.HTTPError(400, errormessage(400, message))
        else:
            startdt = None

        if endtime is not None:
            try:
                enddt = str2date(endtime)
            except Exception:
                # Send Error 400
                message = 'Error converting the "endtime" parameter (%s).' % endtime
334
                # self.__log.error(message)
335 336 337 338 339
                cherrypy.response.headers['Content-Type'] = 'text/plain'
                raise cherrypy.HTTPError(400, errormessage(400, message))
        else:
            enddt = None

340 341 342
        if level == 'response':
            # Send Error 400
            message = 'Response level not valid in text format'
343
            # self.__log.error(message)
344 345 346
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

347
        cherrypy.response.headers['Content-Type'] = 'text/plain'
348
        return self.__generatemetadata(liststa, startdt, enddt, level)
349

350
    def __generatemetadata(self, streams, starttime=None, endtime=None, level='station'):
351 352 353 354 355 356 357 358
        """Generator to extract metadata based on the selection

        :param streams: List of streams (integers) to be extracted
        :type streams: list
        :param starttime: Start time of the time window to access
        :type starttime: datetime
        :param endtime: End time of the time window to access
        :type endtime: datetime
359 360
        :param level: Level of metadata ('network', 'station', 'channel', 'response')
        :type level: str
361 362 363
        :returns: miniSEED data
        :rtype: bytearray
        """
364

365 366 367 368
        # Check parameters
        if level not in ('network', 'station', 'channel', 'response'):
            raise Exception('Level parameter invalid (%s)' % level)

369 370 371 372 373 374
        # TODO Misspelling which could possibly be fixed in the future
        latkey = 'SystemInfomation.GPS.Latitude'
        lonkey = 'SystemInfomation.GPS.Longitude'
        elevkey = 'SystemInfomation.GPS.Altitude'
        srkey = 'SamplingFrequency[Hz]'

375 376 377
        if level == 'network':
            t = TDMS(self.__experiment, directory=self.__directory, starttime=starttime, endtime=endtime, iterate='M')
            with t:
378
                # t.readMetadata()
379 380
                yield '# Network|Description|StartTime|EndTime|TotalStations\n'
                text = '%s|Description|%s|%s|%s\n' % (self.__net, t.starttime.isoformat(), t.endtime.isoformat(),
381
                                                      t.numchannels)
382 383 384 385 386 387 388 389 390 391 392 393 394
                yield text
            return

        if level == 'response':
            raise Exception('Response level not implemented!')

        # Level station and channel
        if level == 'station':
            yield '# Network|Station|Latitude|Longitude|Elevation|SiteName|StartTime|EndTime\n'
        else:
            yield '# Network|Station|Location|Channel|Latitude|Longitude|Elevation|Depth|Azimuth|Dip|Sensor ' \
                'Description|Scale|ScaleFrequency|ScaleUnits|SampleRate|StartTime|EndTime\n'

395 396
        channels = streams if len(streams) else None

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
        # It is not optimal to cycle through channels instead of reading them all at once
        # However it is the best to merge time windows from files int one epoch
        # This allows to construct the generator returning one line at each iteration
        for ch in channels:
            t = TDMS(self.__experiment, directory=self.__directory, starttime=starttime, endtime=endtime, iterate='M',
                     channels=[ch])
            result = dict()
            with t:
                lat = None
                lon = None
                elev = None
                samprate = None
                # stt = t.starttime
                # ent = t.endtime
                for data in t:
                    if lat is None:
                        lat = data[latkey]
                    if lon is None:
                        lon = data[lonkey]
                    if elev is None:
                        elev = data[elevkey]
                    if samprate is None:
                        samprate = data[srkey]

                    # if not data['data']:
                    #     yield json.dumps(data, default=datetime.isoformat)

                    if data['data']:

                        stt = data['starttime']
                        ent = data['endtime']
                        if level == 'station':
                            key = 'XX|%s||FH1|%s|%s|%s|SiteName' % (data['id'], lat, lon, elev)
                        else:
                            key = 'XX|%s||FH1|%s|%s|%s|depth|azimuth|dip|DAS|Scale|ScaleFrequency|ScaleUnits|%s' % \
                                  (data['id'], lat, lon, elev, samprate)

                        if key in result:
                            # Get the minimum starttime
                            stt = stt if stt < result[key][0] else result[key][0]
                            # Get the maximum endtime
                            ent = ent if ent > result[key][1] else result[key][1]

                        result[key] = (stt, ent)

            # Send the epoch(s)
            for key in result:
                # Key is in the proper format for station or channel level. We only need to add the start and end time
                text = '%s|%s|%s\n' % (key, stt.isoformat(), ent.isoformat())

                yield text
448
        return
449 450 451 452 453 454 455


@cherrypy.expose
@cherrypy.popargs('wsversion')
class DataselectAPI(object):
    """Object dispatching methods related to access to streams."""

456
    def __init__(self, experiment, directory='.'):
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        """Constructor of the DataselectAPI class."""
        # Save parameters
        self.__experiment = experiment
        self.__directory = directory

        # Get extra fields from the cfg file
        cfgfile = configparser.RawConfigParser()
        cfgfile.read(os.path.join(directory, 'tdsmws.cfg'))
        self.__net = cfgfile.get('NSLC', 'network', fallback='XX')
        self.__cha = cfgfile.get('NSLC', 'channel', fallback='FH1')

        # Special case for the empty location. Change '' for '--'
        self.__loc = cfgfile.get('NSLC', 'location', fallback='--')
        if self.__loc == '':
            self.__loc = '--'

    @cherrypy.expose
    def index(self, wsversion='1'):
        if wsversion != '1':
            # Send Error 400
            message = 'Only Station-WS version 1 is supported'
478
            # self.__log.error(message)
479 480 481 482 483 484 485 486 487 488 489
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

        cherrypy.response.headers['Content-Type'] = 'text/html'
        # TODO Create an HTML page with a minimum documentation for a user
        try:
            with open('help.html') as fin:
                texthelp = fin.read()
        except FileNotFoundError:
            texthelp = """<html>
                            <head>tdsmws - Dataselect</head>
490
                            <body>
491
                              Default help for the Dataselect service (GEOFON).
492 493 494 495 496
                            </body>
                          </html>"""

        return texthelp.encode('utf-8')

497
    @cherrypy.expose
498 499 500 501
    def default(self, *args, **kwargs):
        """Use default method to process application.wadl because the dot is not supported in method names"""
        cherrypy.log('default method: %s %s' % (args, kwargs))
        if args[0] != '1':
502
            # Send Error 400
503 504 505 506 507 508 509 510
            message = 'Only Dataselect-WS version 1 is supported'
            # self.__log.error(message)
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

        if args[1] != 'application.wadl':
            # Send Error 400
            message = 'Unknown method "%s"' % args[1]
511
            # self.__log.error(message)
512 513 514
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

515 516 517
        project_dir = os.path.dirname(__file__)

        try:
518
            with open(os.path.join(project_dir, 'data/dataselect.wadl')) as fin:
519 520 521 522 523 524 525 526
                text = fin.read()
                cherrypy.response.headers['Content-Type'] = 'application/xml'
                return text.encode('utf-8')
        except FileNotFoundError:
            pass

        # Send Error 400
        message = 'application.wadl not found!'
527
        # self.__log.error(message)
528 529 530
        cherrypy.response.headers['Content-Type'] = 'text/plain'
        raise cherrypy.HTTPError(400,  errormessage(400, message))

531
    @cherrypy.expose
532
    def version(self, wsversion='1'):
533 534 535 536 537
        """Return the version of this implementation.

        :returns: Version of the system
        :rtype: string
        """
538 539 540
        if wsversion != '1':
            # Send Error 400
            message = 'Only Station-WS version 1 is supported'
541
            # self.__log.error(message)
542 543 544 545
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

        dataselectversion = '1.1.0'
546
        cherrypy.response.headers['Content-Type'] = 'text/plain'
547
        return dataselectversion.encode('utf-8')
548 549

    @cherrypy.expose
550
    def query(self, network='*', net='*', station='*', sta='*', location='*', loc='*', channel='*', cha='*',
551
              starttime=None, start=None, endtime=None, end=None, wsversion='1', **kwargs):
552 553
        """Get data in miniSEED format.

554 555 556
        :param network: Usually the network code configured in the cfg file. It is included just to satisfy the standard
        :type network: str
        :param net: Alias of network
557
        :type net: str
558 559 560
        :param station: Comma-separated integers identifying of streams to retrieve
        :type station: str
        :param sta: Alias of station
561
        :type sta: str
Javier Quinteros's avatar
Javier Quinteros committed
562
        :param location: Usually the location code configured in the cfg file. Included just to satisfy the standard
563 564
        :type location: str
        :param loc: Alias of location
565
        :type loc: str
566 567 568
        :param channel: Usually the channel code configured in the cfg file. It is included just to satisfy the standard
        :type channel: str
        :param cha: Alias of channel
569 570 571
        :type cha: str
        :param starttime: Start time of the time window to access
        :type starttime: str
572 573
        :param start: Alias of starttime
        :type start: str
574 575
        :param endtime: End time of the time window to access
        :type endtime: str
576 577
        :param end: Alias of endtime
        :type end: str
578 579
        :param wsversion: Major version of the Dataselect web service
        :type wsversion: str
580 581 582 583 584 585
        :returns: miniSEED data
        :rtype: bytearray
        :raises: cherrypy.HTTPError
        """

        # Check parameters
586 587
        if wsversion != '1':
            # Send Error 400
588
            message = 'Only Dataselect-WS version 1 is supported'
589
            # self.__log.error(message)
590 591 592
            cherrypy.response.headers['Content-Type'] = 'text/plain'
            raise cherrypy.HTTPError(400, errormessage(400, message))

593
        # Network
594 595 596
        if network not in ('*', self.__net) or net not in ('*', self.__net):
            cherrypy.response.status = 204
            return
597 598

        # Location
599 600 601
        if location not in ('*', self.__loc) or loc not in ('*', self.__loc):
            cherrypy.response.status = 204
            return
602 603

        # Channel
604 605 606
        if channel not in ('*', self.__cha) or cha not in ('*', self.__cha):
            cherrypy.response.status = 204
            return
607 608 609 610 611 612 613 614 615 616 617 618 619 620

        # Station and sta
        # Discard the most comprehensive case of '*' and keep the most restricted one
        auxsta = station if sta == '*' else sta

        # Starttime and start
        # Discard the most comprehensive case of None and keep the most restricted one
        starttime = starttime if start is None else start

        # Endtime and end
        # Discard the most comprehensive case of None and keep the most restricted one
        endtime = endtime if end is None else end

        # Station(s)
621
        try:
622
            liststa = [] if auxsta == '*' else [int(x) for x in auxsta.split(',')]
623 624 625 626
        except Exception:
            # Send Error 400
            message = 'Wrong formatted list of stations (%s).' % sta
            cherrypy.response.headers['Content-Type'] = 'text/plain'
627
            raise cherrypy.HTTPError(400,  errormessage(400, message))
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651

        if starttime is not None:
            try:
                startdt = str2date(starttime)
            except Exception:
                # Send Error 400
                message = 'Error converting the "starttime" parameter (%s).' % starttime
                cherrypy.response.headers['Content-Type'] = 'text/plain'
                raise cherrypy.HTTPError(400, errormessage(400, message))
        else:
            startdt = None

        if endtime is not None:
            try:
                enddt = str2date(endtime)
            except Exception:
                # Send Error 400
                message = 'Error converting the "endtime" parameter (%s).' % endtime
                cherrypy.response.headers['Content-Type'] = 'text/plain'
                raise cherrypy.HTTPError(400, errormessage(400, message))
        else:
            enddt = None

        cherrypy.response.headers['Content-Type'] = 'application/vnd.fdsn.mseed'
652
        return self.__generatemseed(liststa, startdt, enddt)
653

654
    def __generatemseed(self, streams, starttime=None, endtime=None):
655 656 657 658 659 660 661 662 663 664 665
        """Generator to extract miniSEED data based on the selection

        :param streams: List of streams (integers) to be extracted
        :type streams: list
        :param starttime: Start time of the time window to access
        :type starttime: datetime
        :param endtime: End time of the time window to access
        :type endtime: datetime
        :returns: miniSEED data
        :rtype: bytearray
        """
666

667
        channels = streams if len(streams) else None
668

669 670 671 672 673 674 675 676 677 678
        t = TDMS(self.__experiment, directory=self.__directory, starttime=starttime, endtime=endtime,
                 channels=channels)
        with t:
            for data in t:
                # Create the Trace
                tr0 = Trace(data=data[0], header=data[1])
                auxout = BytesIO()
                tr0.write(auxout, format='MSEED', reclen=512)
                yield auxout.getvalue()
                auxout.close()
679

680
        return
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717


def main():
    """Run the tdmsws service implementing a Dataselect-WS on top of TDMS files"""

    desc = 'tdmsws is an FDSN Dataselect implementation to read TDMS files'
    parser = argparse.ArgumentParser(description=desc)

    parser.add_argument('-mc', '--minimalconfig', action='store_true', default=False,
                        help='Generate a minimal configuration file.')
    parser.add_argument('-l', '--log', default='WARNING', choices=['DEBUG', 'WARNING', 'INFO', 'DEBUG'],
                        help='Increase the verbosity level.')
    args = parser.parse_args()

    # Read configuration
    config = configparser.RawConfigParser()

    if args.minimalconfig:
        # Create default sections and options for the configfile
        config['General'] = {'experiment': 'filename', 'loglevel': 'INFO'}
        config['NSLC'] = {'network': 'XX', 'location': '', 'channel': 'FH1'}
        # Write to tdmsws.cfg
        with open('tdmsws.cfg', 'w') as configfile:
            config.write(configfile)
        return

    # Open the configuration file in the current directory
    config.read('tdmsws.cfg')
    
    # Read general parameters
    experiment = config.get('General', 'experiment')

    server_config = {
        'global': {
            'tools.proxy.on': True,
            'server.socket_host': 'localhost',
            'server.socket_port': 7000,
718 719 720
            'engine.autoreload_on': False,
            'log.access_file': 'access.log',
            'log.error_file': 'error.log'
721 722 723 724
        }
    }
    # Update the global CherryPy configuration
    cherrypy.config.update(server_config)
725
    cherrypy.tree.mount(TdmswsAPI(experiment), '/fdsnws')
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

    plugins.Daemonizer(cherrypy.engine).subscribe()
    if hasattr(cherrypy.engine, 'signal_handler'):
        cherrypy.engine.signal_handler.subscribe()
    if hasattr(cherrypy.engine, 'console_control_handler'):
        cherrypy.engine.console_control_handler.subscribe()

    # Always start the engine; this will start all other services
    try:
        cherrypy.engine.start()
    except Exception:
        # Assume the error has been logged already via bus.log.
        raise
    else:
        cherrypy.engine.block()


if __name__ == "__main__":
    main()