Source

saturnalia / setup.py

Full commit
  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
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#!/usr/bin/env python

import os
import errno
import subprocess
import shutil
import webbrowser

from setuptools        import setup, Command
from distutils.command import clean
from glob              import glob


from distutils.extension import Extension
from Cython.Distutils import build_ext



rootDir = "."


CYTHON_MODULES = [
    ( "task.fieldtypes"          , "src/python/task/fieldtypes.pyx"           ),
    ( "task.messagedata"         , "src/python/task/messagedata.pyx"          ),
    ( "task.messagebuilder"      , "src/python/task/messagebuilder.pyx"       ),
    ( "saturnalia.messagebuilder", "src/python/saturnalia/messagebuilder.pyx" ),
    ]


def main():
    setup(
        name="saturnalia", 
        version="0.5.0",
        description="Distributed time series database.",
        author="saturnaliadb.org",
        author_email="saturnaliadb.org",
        url="http://saturnaliadb.org/",
        license="MIT",
        package_dir = {
            'saturnalia'                      : 'src/python/saturnalia'                      ,
            'saturnalia.tile'                 : 'src/python/saturnalia/tile'                 ,
            'saturnalia.tools'                : 'src/python/saturnalia/tools'                ,
            'saturnalia.tests'                : 'src/python/saturnalia/tests'                ,
            'task'                            : 'src/python/task'                            ,
            'saturnalia.web'                  : 'src/python/saturnalia/web'                  ,
            'saturnalia.web.tasks'            : 'src/python/saturnalia/web/tasks'            ,
            'saturnalia.web.resources'        : 'src/python/saturnalia/web/resources'        ,
            },
        packages=[
            'saturnalia'                      ,
            'saturnalia.tile'                 ,
            'saturnalia.tools'                ,
            'saturnalia.tests'                ,
            'saturnalia.web'                  ,
            'saturnalia.web.tasks'            ,
            'saturnalia.web.resources'        ,
            'task'                            ,
            ],
        scripts = glob('sbin/*'),
        ext_modules = [
            Extension( name, [ source ] ) for ( name, source ) in CYTHON_MODULES
            ],
        data_files = [
            ( '/usr/share/saturnalia/configs/system'       , [ 'config/system/common.conf'                                    ] ),
            ( '/usr/share/saturnalia/configs/metricd'      , [ 'config/metricd/metricd.conf'                                  ] ),
            ( '/usr/share/saturnalia/configs/routedb'      , [ 'config/routedb/routedb.conf'                                  ] ),
            ( '/usr/share/saturnalia/configs/componentdb'  , [ 'config/componentdb/componentdb.conf'                          ] ),
            ( '/usr/share/saturnalia/configs/sclientd'     , [ 'config/sclientd/sclientd.conf'                                ] ),
            ( '/usr/share/saturnalia/configs/client'       , [ 'config/client/client.conf'                                    ] ),
            ( '/usr/share/saturnalia/configs/sweb'         , [ 'config/sweb/sweb.conf'                                        ] ),
            ( '/usr/share/saturnalia/configs/managementd'  , [ 'config/managementd/managementd.conf'                          ] ),
            ( '/usr/share/saturnalia/configs'              , [ 'config/basecomponents.json'                                   ] ),
            ],
        include_package_data = True,
        package_data = {
            },
        cmdclass = {
            'build_ext'       : build_ext        ,
            'test'            : RunTrial         ,
            'build_js'        : BuildJavaScript  ,
            'build_html_docs' : BuildHTMLDocs    ,
            'cython'          : RunCython        ,
            'clean'           : SaturnaliaClean  ,
            },
        command_options = {
            'aliases': buildAliases( dict(
                prepare  =( 'build_js', 'build_ext' ),
                build    =( 'prepare', 'build' ),
                build_ext=( 'cython', 'build_ext', '--inplace' ),
                test     =( 'prepare', 'test'         ),
                )
              )
            },
        )



def buildCommand ( command, dependencies ):

    result = []


    if command not in dependencies:
        result.append( command )
        
    else:

        for subCommand in dependencies[ command ]:

            if subCommand == command:
                result.append( subCommand )
            
            else:
                for dep in buildCommand( subCommand, dependencies ):
                    result.append( dep )

    return result


def buildAliases ( dependencies ):

    result = {}

    for command in dependencies:
        expanded = buildCommand( command, dependencies )

        result[ command ] = ('setup.py', " ".join( expanded ) )
        

    return result


def initFileLocation ( dirName, fileName ):


    try:
        os.makedirs( dirName )

    except os.error, ex:
        if ex.errno != errno.EEXIST:
            raise ex

    filePath = os.path.join( dirName, fileName )

    if fileName in os.listdir( dirName ):
        os.unlink( filePath )


    return filePath


def deleteTree ( path ):

    try:
        shutil.rmtree( path )

    except os.error, ex:
        if ex.errno != errno.ENOENT:
            raise ex
        

class SaturnaliaClean ( clean.clean ):

    def run(self):
        dirs = [
            os.path.join( rootDir, "test"  ),
            os.path.join( rootDir, "saturnalia.egg-info" ),
            os.path.join( rootDir, "_trial_temp" ),
            os.path.join( rootDir, "build" ),
            ]


        for path in dirs:
            print 'Removing directory: %r' % ( path, )

            try:
                shutil.rmtree( path )

            except os.error, ex:
                if ex.errno != errno.ENOENT:
                    raise ex


        files = [
            os.path.join( rootDir, "src", "html", "console.js" ),
            os.path.join( rootDir, "src", "html", "embed.js" ),
            ]

        for _, pyxPath in CYTHON_MODULES:
            stem   = os.path.splitext( pyxPath )[0]

            for builtExtension in [ '.c', '.so' ]:
                builtPath  = os.path.join( rootDir, stem + builtExtension  )

                files.append( builtPath )

        for path in files:
            print 'Removing file: %r' % ( path, )

            try:
                os.unlink( path )

            except os.error, ex:
                if ex.errno != errno.ENOENT:
                    raise ex


        clean.clean.run(self)

        
class RunCython (Command):
    description = 'generate .c from .pyx files'

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):

        for name, source in CYTHON_MODULES:
            stem, ext = os.path.splitext( source )
            if ext == '.pyx':
                inputpath = os.path.join( rootDir, source )
                csourcepath = os.path.join( rootDir, stem + '.c' )
                if os.path.isfile( csourcepath ) and os.stat( inputpath ).st_mtime < os.stat( csourcepath ).st_mtime:
                    print 'Cython up-to-date: %r' % ( csourcepath, )
                else:
                    print 'Cython processing: %r' % ( inputpath, )
                    systemWorker('cython',  inputpath )

        
class BuildJavaScript (Command):

    description = 'generate java script files'

    user_options = []

    dependencies = {
        'DataContainer.js'      : [ 'saturnalia.js' ],
        'EventBus.js'           : [ 'saturnalia.js' ],
        'TaskHandle.js'         : [ 'saturnalia.js' ],
        'ComponentDB.js'        : [ 'saturnalia.js' ],
        'MessageCoordinator.js' : [ 'saturnalia.js' ],
        'Colors.js'             : [ 'saturnalia.js' ],
        'DataConfig.js'         : [ 'saturnalia.js' ],
        'LineChart.js'          : [ 'Colors.js', 'DataSelector.js' ],
        'ChartComponent.js'     : [ 'saturnalia.js' , 'DataConfig.js', 'RegionSelector.js', 'DataContainer.js' ],
        'components.js'         : [ 'saturnalia.js' ],
        'HeaderComponent.js'    : [ 'saturnalia.js' ],
        'ReportByTag.js'        : [ 'TaskHandle.js', 'saturnalia.js' ],
        'widget.js'             : [ 'saturnalia.js', 'DataContainer.js', 'i18n.js',  ],
        'saturnalia_console.js' : [ 'saturnalia.js', 'EventBus.js', 'TaskHandle.js', 'ComponentDB.js', 'widget.js', 'MessageCoordinator.js', 'cleave.js', 'LineChart.js', 'components.js', 'ChartComponent.js', 'HeaderComponent.js', 'ReportByTag.js' ],
        'boot_console.js'       : [ 'saturnalia_console.js', ],
        'console.js'            : [ 'boot_console.js' ],
        'boot_embed.js'         : [ 'saturnalia_console.js', ],
        'embed.js'              : [ 'boot_embed.js' ],
        }
    

    def initialize_options ( self ):
        pass

    def finalize_options ( self ):
        pass

    def buildIncludes ( self, targetName, dependencies ):

        result = []

        if targetName in dependencies:

            for subTargetName in dependencies[ targetName ]:

                if subTargetName not in result:

                    if subTargetName in dependencies:

                        for dep in self.buildIncludes( subTargetName, dependencies ):

                            if dep not in result:
                                result.append( dep )


                if targetName in result:
                    raise ValueError ( "Circular dependencies not supported. Found for %s" % ( targetName, ) )

                result.append( subTargetName )


        return result
        

    def buildFile ( self, outFile ):

        buildDir    = os.path.join( rootDir, "src", "html" )
        outFilePath = initFileLocation( buildDir, outFile )

        outHandle  = open( outFilePath, 'w' )

        includes = self.buildIncludes( outFile, self.dependencies )

        for fileName in includes:
            path = os.path.join('.', 'src', 'js', fileName )

            subFile = open( path )

            for line in subFile:
                outHandle.write( line )

    def run ( self ):

        self.buildFile( "console.js" )
        self.buildFile( "embed.js" )



class BuildHTMLDocs (Command):

    description = 'generate html documentation from reStructuredText sources'

    user_options = []

    def initialize_options ( self ):
        pass

    def finalize_options ( self ):
        pass

    def run ( self ):

        # Find rst2html:
        rst2html = None

        for binDir in os.environ['PATH'].split(':'):
            for name in [ 'rst2html', 'rst2html.py' ]:
                testPath = os.path.join( binDir, name )
                if os.path.isfile( testPath ):
                    rst2html = testPath
                    break

        if rst2html == None:
            print 'Could not find rst2html - not building HTML docs.'
            print 'To enable this install one of these packages:'
            print '  $ pip install docutils'
            print '  $ sudo apt-get install python-docutils'
            return
            
        for basedir, dirs, files in os.walk('./doc'):
            for filename in files:
                if filename.endswith('.rst'):
                    htmlname = filename[:-4] + '.html'

                    rstpath  = os.path.join( basedir, filename )
                    htmlpath = os.path.join( basedir, htmlname )

                    system( rst2html, rstpath, htmlpath )


class RunTrial (Command):

    description = 'run unittests with trial'

    __slots__ = ['coverage', 'target', 'skip_pyflakes']
    
    user_options = [

        ('skip-pyflakes', None,
         "don't run pyflakes before running tests"),
        
        ('coverage', None,
         'generate --coverage from trial tests'),
        
        ('target=', None,
         'specify a test target instead of default of "saturnalia"'),
        
        ]

    def initialize_options(self):
        self.skip_pyflakes = False
        self.coverage      = False
        self.target        = None

    def finalize_options(self):
        pass

    def run(self):
        deleteTree( "test" )
        shutil.copytree( "src", "test", symlinks=True )

        if self.coverage:
            self._run_coverage()
        else:
            self._run_trial()

            
    def _run_coverage(self):
        if self.target != None:
            raise SystemExit('Options --coverage and --target are mutually exclusive.')

        path = os.path.join( ".", "test", "python" )

        system('coverage', 'run', '--branch', '--source', path, find_exec('trial'), 'saturnalia')
        system('coverage', 'html')
        indexpath = os.path.join('htmlcov', 'index.html')
        print 'Coverage index: %r' % (indexpath,)
        webbrowser.open(indexpath)

    def _run_trial(self):

        target = self.target

        targets = ['saturnaliaclient', 'saturnalia', 'task']

        if target != None:
            targets = [target]

        if not self.skip_pyflakes:
            path = os.path.join( ".", "test", "python" )

            system('pyflakes', path )

        for work in targets:
            system('trial', work)


def system(*argv, **kwargs):
    _tweak_pythonpath()

    print 'Executing: %r' % (argv,)

    systemWorker( *argv, **kwargs )


def systemWorker(*argv, **kwargs):

    r = subprocess.call(argv, **kwargs)
    if r != 0:
        raise SystemExit(r)


def _tweak_pythonpath():
    if not _tweak_pythonpath.completed:
        pysrc = os.path.join( ".", "test", "python" )
        ppath = os.environ.get('PYTHONPATH', '')
        ppath = '%s:%s' % (pysrc, ppath)
        os.environ['PYTHONPATH'] = ppath
        print 'PYTHONPATH=%r' % (ppath,)
        _tweak_pythonpath.completed = True

_tweak_pythonpath.completed = False


def find_exec(name):
    for d in os.environ.get('PATH', []).split(os.pathsep):
        path = os.path.join(d, name)
        print 'DEBUG', `path`
        if os.access(path, os.X_OK):
            return path
    raise SystemExit('Could not find executable: %r' % (name,))


if __name__ == '__main__':
    main()