Source

octopoda / octopoda.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
#!/usr/bin/python
#===============================================================================
#                _____                                  _       
#               / ___ \       _                        | |      
#              | |   | | ____| |_  ___  ____   ___   _ | | ____ 
#              | |   | |/ ___)  _)/ _ \|  _ \ / _ \ / || |/ _  |
#              | |___| ( (___| |_| |_| | | | | |_| ( (_| ( ( | |
#               \_____/ \____)\___)___/| ||_/ \___/ \____|\_||_|
#                                      |_|                      
#                           MapReduce for Human Beings                                                             
# Repo: http://code.thejeshgn.com/octopoda
# Copyright (C) 2012 Thejesh GB <i@thejeshgn.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# History:
# Initial code: http://code.google.com/p/octopy 
# Initial License : New BSD License
#===============================================================================

from __future__ import with_statement

import asynchat
import asyncore
import base64
import bsddb
import bz2
import contextlib
import imp
import itertools
import logging
from optparse import OptionParser
import os
import os.path
import cPickle as pickle
import shelve
import socket
import threading
import tempfile
import time
import traceback
import UserDict


__version__ = "0.1"

#===========================PROTOCAL SETTINGS===================================
DEFAULT_CHAT_PORT = 18272
DEFAULT_CHAT_POLL = 60
DEFAULT_CHAT_RETRY = 3
DEFAULT_CHAT_CLIENT_BUFFER = 1024
#===============================================================================


class Lock(object):
    """Context-able (with-block) wrapper for a lock.
    """
    def __init__(self):
        self.__lock = threading.Lock()


    def __enter__(self):
        self.__lock.acquire()
        return self
    

    def __exit__(self, type, value, traceback):
        self.__lock.release()
        


class Task(object):
    """Represents a single task for the WorkQueue.
    """
    def __init__(self, key, value):
        self.key = key
        self.value = value


    def __eq__(self, other):
        return self.key == other.key


class WorkQueue(object):
    """Manages a list of tasks to complete."""
    def __init__(self, tasks, retry=False):
        """Creates a work queue from the given dictionary-like
        collection of tasks.
        """
        self.tasks = tasks
        self.unassigned = iter(tasks)
        self.unassigned_lock = Lock()
        self.pending = [ ]
        self.pending_lock = Lock()
        self.retry = retry


    def get_task(self):
        with self.unassigned_lock:
            try:
                key = self.unassigned.next()
            except StopIteration:
                # do we retry the pending tasks?
                if self.retry:
                    with self.pending_lock:
                        # grab a pending task if available
                        if self.pending:
                            task = self.pending.pop(0)
                            self.pending.append(task)
                            return task.key, task.value
                        else:
                            return None
                else:
                    return None
            else:
                task = Task(key, self.tasks[key])
                with self.pending_lock:
                    self.pending.append(task)
                return task.key, task.value


    def __iter__(self):
        return self


    def next(self):
        task = self.get_task()
        if not task:
            raise StopIteration("No more tasks")
        return task


    def mark_completed(self, key):
        task = Task(key, None)
        with self.pending_lock:
            try:
                self.pending.remove(task)
            except ValueError:
                pass


    def is_completed(self):
        with contextlib.nested(self.unassigned_lock, self.pending_lock):
            self.unassigned, unassigned_lookahead = \
                itertools.tee(self.unassigned)
            try:
                unassigned_lookahead.next()
            except StopIteration:
                return len(self.pending) == 0
            else:
                return False
            


class PersistantDict(UserDict.DictMixin):
    """Persistant (disk-backed) dictionary.
    """
    def __init__(self, path=None):
        self.logging = logging.getLogger(self.__class__.__name__)
        if not path:
            fd, path = tempfile.mkstemp(".shelve", "octo_", text=False)
            os.close(fd)
        self.logging.debug("Shelve DB: %s", path)
        self._db = bsddb.hashopen(path, 'n')
        self._shelve = shelve.BsdDbShelf(self._db, protocol=2,
                                         writeback=True)


    def __del__(self):
        self._shelve.close()
        self._db.close()
        

    def __delitem__(self, key):
        pkey = pickle.dumps(key)
        self._shelve.__delitem__(pkey)


    def __getitem__(self, key):
        pkey = pickle.dumps(key)
        return self._shelve.__getitem__(pkey)


    def __setitem__(self, key, value):
        pkey = pickle.dumps(key)
        self._shelve.__setitem__(pkey, value)
        self._shelve.sync()


    def keys(self):
        return (pickle.loads(pkey) for pkey in self._shelve.keys())


    def sync(self):
        self._shelve.sync()


    def append(self, key, value):
        pkey = pickle.dumps(key)
        self._shelve.setdefault(pkey, []).append(value)
        self._shelve.sync()
        
    



class Protocol(asynchat.async_chat):
    """Base class for the simple Chat protocol.

    This handles buffering of network traffic and calls the abstract
    received() method.
    """
    def __init__(self):
        self.set_terminator("\n")
        self.buffer = []
    
    def collect_incoming_data(self, data):
        self.buffer.append(data)

    def found_terminator(self):
        data = "".join(self.buffer)
        self.buffer = []
        self.received(data)
        
    def decode_data(self, data):
        return pickle.loads(bz2.decompress(base64.b64decode(data)))

    def encode_data(self, data):
        return base64.b64encode(bz2.compress(pickle.dumps(data, 2)))


#START - TaskClient ===========================================================
class TaskClient():
    """Simple socket-based client for tasks.
    """
    class ClientChannel(Protocol):

        def __init__(self, host, port, id, taskclient):
            self.logging = logging.getLogger(self.__class__.__name__)
            asynchat.async_chat.__init__(self)
            Protocol.__init__(self)
            self.decode = False
            self.id = id
            self.data = None
            self.taskclient = taskclient
            # connect
            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
            self.logging.debug("Connecting to %s:%s", host, port)
            self.connect((host, port))

        def handle_connect(self):
            self.logging.debug("Connected")
            self.taskclient.retry = 0

        def handle_expt(self):
            self.logging.error("Connection failed")
            self.close()
            self.taskclient.retry += 1

        def get_auth(self, password):
            self.decode = False
            self.push("auth,%s,%s\n" % (self.id , password))
                

        def get_task(self):
            self.decode = True
            self.push("get,%s,\n" % self.id)

        def get_taskfile(self):
            self.decode = True
            self.push("taskfile,%s,\n" % self.id)

        def post_result(self, key, value):
            self.decode = False
            data = self.encode_data((key, value))
            self.push("post,%s,%s\n" % (self.id, data))

        def post_results(self, results):
            self.decode = False
            data = self.encode_data(results)
            self.push("posts,%s,%s\n" % (self.id, data))

        def post_completed(self, key):
            self.decode = False
            data = self.encode_data(key)
            self.push("completed,%s,%s\n" % (self.id, data))

        def received(self, data):
            print data
            if self.decode:
                self.data = self.decode_data(data)
            else:
                self.data = data
            self.handle_close()

    
    def __init__(self,
                 host="localhost", port=DEFAULT_CHAT_PORT,
                 poll=DEFAULT_CHAT_POLL, maxretries=DEFAULT_CHAT_RETRY,
                 buffersize=DEFAULT_CHAT_CLIENT_BUFFER, password=None):
        self.logging = logging.getLogger(self.__class__.__name__)
        self.id = hash(socket.gethostname())
        self.logging.info("id: %s", self.id)
        self.host = host
        self.port = port
        self.poll = poll
        self.maxretries = maxretries
        self.retry = 0
        self.results_buffer = [ ]
        self.buffersize = buffersize


    def channel(self, method, *args):
        channel = TaskClient.ClientChannel(self.host, self.port,
                                               self.id, self)
        method(channel, *args)
        asyncore.loop()
        return channel.data


    def start(self, mapfn, reducefn):
        while True:
            # get a task            
            data = self.channel(TaskClient.ClientChannel.get_task)
            if data:
                # work on the task
                phase, key, value = data
                self.logging.info("%s on %s", phase, key)
                if phase == "map":
                    for i_key, i_value in mapfn(key, value):
                        self.post_result(key, (i_key, i_value))
                    self.post_completed(key)
                elif phase == "reduce":
                    f_value = reducefn(key, value)
                    self.post_result(key, f_value)
                    self.post_completed(key)
            else:
                # no task
                if self.retry >= self.maxretries:
                    self.logging.error("Maximum retries; quitting...")
                    break
                self.logging.info("No work; sleeping...")
                time.sleep(self.poll)


    def stop(self):
        self.close()


    def post_completed(self, key):
        # if buffers aren't empty, flush them
        if self.results_buffer:
            self.post_results()
        self.channel(TaskClient.ClientChannel.post_completed, key)
        
    
    def post_results(self):
        self.logging.debug("Reporting multiple results...")
        buffer = self.results_buffer
        self.results_buffer = []
        self.channel(TaskClient.ClientChannel.post_results, buffer)
        

    def post_result(self, key, value):
        # check if we are buffering
        if self.buffersize:
            # buffer results
            self.results_buffer.append((key, value))
            # if buffer is full, flush them
            if len(self.results_buffer) >= self.buffersize:
                self.post_results()
        else:
            # report results
            self.logging.debug("Reporting results for %s...", key)
            self.channel(TaskClient.ClientChannel.post_result,
                         key, value)
        
    
    def get_taskfile(self):
        data = self.channel(TaskClient.ClientChannel.get_taskfile)
        return data   

    def authenticate_client(self, password):
        self.logging.debug("Calling get authenticate_client -> get_auth ...... using pw="+str(password))
        data = self.channel(TaskClient.ClientChannel.get_auth,str(password))
        return data   
        


#END TaskClient ===============================================================



#START TaskServer =============================================================
class TaskServer(object,asyncore.dispatcher):
    """Generic task server."""

    class ServerChannel(Protocol):
        def __init__(self, conn, taskserver):
            self.logging = logging.getLogger(self.__class__.__name__)
            asynchat.async_chat.__init__(self, conn)
            Protocol.__init__(self)
            self.taskserver = taskserver

        def command_get(self, id, data):
            """Get the next available task.
            """
            task = self.taskserver.next_task()
            if task:
                self.logging.info("Assigning %s task %s", task[0], task[1])
            data = self.encode_data(task)
            self.push(data)
            self.push("\n")

        def command_post(self, id, data):
            """Post a single key-value pair as a result.
            """
            # split data into task and result
            key, value = self.decode_data(data)
            self.logging.debug("Putting %s, %s", key, value)
            self.taskserver.handle_results(key, value)
            self.push("ok\n")
            
        def command_posts(self, id, data):
            """Post a list of key-value pairs as results.

            Note that this method does not take a dictionary.
            """
            data_dict = self.decode_data(data)
            for key, value in data_dict:
                self.logging.debug("Putting %s, %s", key, value)
                self.taskserver.handle_results(key, value)
            self.push("ok\n")

        def command_completed(self, id, data):
            """Indicate that work on a given key is complete.
            """
            key = self.decode_data(data)
            self.logging.debug("Completed %s", key)
            self.taskserver.handle_completed(key)
            self.push("ok\n")
            
        def command_taskfile(self, id, data):
            """Retrieve the taskfile.
            """
            with open(self.taskserver.taskfile) as f:
                taskfilecontents = f.read()
            data = self.encode_data(taskfilecontents)
            self.push(data)
            self.push("\n")
            
        def command_auth(self, id, data):
            """ auth the client """
            self.logging.error("Authentication on server side: %s", str(data))
            if self.taskserver.password == str(data):
                self.taskserver.authenticated_clients.append(str(id))
                self.logging.error("Authentication sucess") 
                self.push("sucess\n")        
            else:
                self.logging.error("Authentication failed")
                self.push("fail\n")


        def command_invalid(self, id, data):
            """Invalid command.
            """
            self.logging.error("Invalid command: %s", comand)
            self.push("error\n")
            
        def authenticated(self,id):
            if self.taskserver.authenticated_clients.count(str(id)):
                return True
            else:
                return False

        def received(self, data):
            """Handles a request of the form:
            
            command,id,[data]
            
            where the data is optional, but the 2nd comma seperator is
            not.

            See .command_ methods for accepted commands.
            
            Data is encoded via the pickle and base64 modules.
            """
            self.logging.debug("Data from client %s", data)
            command, id, data = data.split(",", 2)
            command = command.lower()
            id = int(id)
            self.logging.debug("Command: %s From: %s with data %s", command, id, str(data))

            #1.check if the client is already authenticated
            if(self.authenticated(id)):
                pass
            else:
                command = "auth"


            # act on the command
            {"auth":      self.command_auth,
             "get":       self.command_get,
             "post":      self.command_post,
             "posts":     self.command_posts,
             "completed": self.command_completed,
             "taskfile":  self.command_taskfile,
            }.get(command, self.command_invalid)(id, data)
            self.close_when_done()
           
            



    def __init__(self, tasks, taskfile,
                 host="", port=DEFAULT_CHAT_PORT, password="", taskretry=False,intermediate=None, final=None):
        self.logging = logging.getLogger(self.__class__.__name__)
        asyncore.dispatcher.__init__(self)

        self.taskfile = taskfile
        self.taskretry = taskretry
        self.workqueue = WorkQueue(tasks, retry=taskretry)
        self.intermediate = PersistantDict(intermediate)
        self.final = PersistantDict(final)
        self.handle_results = self.handle_map_results
        self.handle_completed = self.handle_map_completed
        self.phase = "map"
        self.password = password
        self.authenticated_clients=[]
        self.lock = Lock()
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.logging.info("Listening on %s:%s", host, port)
        self.bind((host, port))
        self.listen(5)


    def __del__(self):
        del self.intermediate
        del self.final


    def next_task(self):
        """Get the next task from the queue.
        """
        try:
            key, value = self.workqueue.next()
        except StopIteration:
            self.logging.info("No more tasks")
            return None
        else:
            self.logging.debug("Next task: %s", key)
            return self.phase, key, value

    
    def handle_map_results(self, key, value):
        """Store the results of a map task.
        """
        with self.lock:
            self.logging.debug("Map results: %s", value)
            i_key, i_value = value
            self.intermediate.append(i_key, i_value)
            self.intermediate.sync()


    def handle_map_completed(self, key):
        """Mark a map task as completed.
        """
        self.logging.debug("Map complete")
        with self.lock:
            self.workqueue.mark_completed(key)
            if self.workqueue.is_completed():
                self.logging.info("Map phase complete")
                self.process_intermediate()


    def process_intermediate(self):
        """Process the intermediate map results and prepare for the reduce
        phase.
        """
        self.workqueue = WorkQueue(self.intermediate, retry=self.taskretry)
        self.handle_results = self.handle_reduce_results
        self.handle_completed = self.handle_reduce_completed
        self.phase = "reduce"


    def handle_reduce_results(self, key, value):
        """Store the results of a reduce task.
        """
        with self.lock:
            self.logging.debug("Reduce results: %s", value)
            self.final[key] = value


    def handle_reduce_completed(self, key):
        """Mark a reduce task as completed.
        """
        self.logging.debug("Reduce complete")
        with self.lock:
            self.workqueue.mark_completed(key)
            if self.workqueue.is_completed():
                self.logging.info("Reduce phase complete")
                self.stop()

                
    def handle_accept(self):
        channel, address = self.accept()
        self.logging.debug("Accepted connection from %s:%s", *address)
        TaskServer.ServerChannel(channel, self)


    def start(self):
        self.logging.info("Starting server...")
        asyncore.loop()
        self.logging.info("Server stopped")


    def stop(self):
        self.logging.info("Stopping server...")
        self.close()
#END TaskServer ===============================================================        







   
def parse_options():
    parser = OptionParser(usage="""%prog [options] server TASKFILE or %prog [options] client SERVER_ADDRESS""")
    parser.add_option("-v", "--verbose", help="print more detailed messages", action="store_true")
    parser.add_option("-p", "--password", help="password", type="string")
    options, args = parser.parse_args()
    if len(args) != 2:
        parser.error('invalid number of arguments')
    args[0] = args[0].lower()
    if args[0] not in ('client', 'server'):
        parser.error('argument must be either "server" or "client"')
    else:
        mode = args[0]
    taskfile = args[1]
    extraoptions = {}
    if options.password:
        extraoptions["password"] = options.password
    return (mode, taskfile, options.verbose, extraoptions)


def prepare_taskfile(taskfile):
    """Attempt to load the taskfile as a module.
    """
    path = os.path.dirname(taskfile)
    taskmodulename = os.path.splitext(os.path.basename(taskfile))[0]
    logging.info("Loading task file %s from %s", taskmodulename, path)
    fp, pathname, description = imp.find_module(taskmodulename, [path])
    try:
        return imp.load_module(taskmodulename, fp, pathname, description)
    finally:
        if fp:
            fp.close()


def do_server(taskfile, **options):
    """Starts the server.

    The taskfile is loaded and tasks retrieved. The server is then
    started with the specified tasks, taskfile, and type. The server
    first distributes map tasks then reduce tasks and then finalizes
    the results.
    
    Additional options are passed through to the specific server
    constructor.


    """
    SERVER_IP_ADDRESS = str(socket.gethostbyname(socket.gethostname()))
    print "===============================================================================" 
    print "                            +++  SERVER  +++                                   " 
    print "          SERVER IP:"+SERVER_IP_ADDRESS+"       PORT:"+str(DEFAULT_CHAT_PORT)+""
    print "          TASK : "+str(taskfile)+"                                             "
    print "===============================================================================" 

    taskmodule = prepare_taskfile(taskfile)
    # prepare tasks
    tasks = taskmodule.source
    # start task/data server
    taskserver = TaskServer(tasks, taskfile, **options)
    taskserver.start()
    # tasks completed, run final
    if hasattr(taskmodule, "final"):
        for key in sorted(list(taskserver.final.keys())):
            taskmodule.final(key, taskserver.final[key])

    
def do_client(taskfile, **options):
    """Starts the client.

    Attempts to load/retrieve the taskfile. The client is then started
    with the work function from the taskfile and specified type.

    Additional options are passed through to the specific client
    constructor.


    """
    print "===============================================================================" 
    print "                            +++  CLIENT  +++                                   " 
 
    server = taskfile
    taskclient = TaskClient(host=server, **options)
    if options.has_key('password'):
        pw = options['password']
    else:
        pw = ""
    is_auth = taskclient.authenticate_client(password=pw)
    if is_auth != "sucess":
        print "Wrong Authentication"     
    else:
        print "authenticated"
        taskfilecontents = taskclient.get_taskfile()
        if taskfilecontents:
            # write task file to temporary file
            fd, taskfile = tempfile.mkstemp(".py", "octo_", text=True)
            try:
                os.write(fd, taskfilecontents)
            finally:
                os.close(fd)
            taskmodule = prepare_taskfile(taskfile)
        else:
            logging.critical("Unable to retrieve task file")
            return
        # start the task client
        print "      TASK : "+str(taskfile)+"               PORT:"+str(DEFAULT_CHAT_PORT)+"   " 
        print "===============================================================================" 

        taskclient.start(taskmodule.mapfn, taskmodule.reducefn)
    

def main():
    print "===============================================================================" 
    print "                _____                                  _                       "
    print "               / ___ \       _                        | |                      "
    print "              | |   | | ____| |_  ___  ____   ___   _ | | ____                 "
    print "              | |   | |/ ___)  _)/ _ \|  _ \ / _ \ / || |/ _  |                "
    print "              | |___| ( (___| |_| |_| | | | | |_| ( (_| ( ( | |                "
    print "               \_____/ \____)\___)___/| ||_/ \___/ \____|\_||_|                "
    print "                                      |_|                                      "
    print "                         MapReduce for Human Beings                            "              
    print "                       By: Thejesh GN <i@thejeshgn.com>                        "
    print "                    Repo: http://code.thejeshgn.com/octopoda                   "
    print "==============================================================================="

    # parse arguments
    mode, taskfile, verbose, options = parse_options()
    # set up logging
    if verbose:
        logging.basicConfig(logging=logging.DEBUG,
                            format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
        logging.getLogger("").setLevel(logging.DEBUG)
    else:
        logging.basicConfig(logging=logging.INFO,
                            format="[%(levelname)s] %(message)s")
        logging.getLogger("").setLevel(logging.INFO)
    # are we server or client?

    if mode == 'server':
        do_server(taskfile, **options)
    else:
        do_client(taskfile, **options)

    

if __name__ == "__main__":
    main()