Esempio n. 1
0
    def get(self, request, format=None, **kwargs):
        serializer = kwargs['serializer']
        card_number = serializer.validated_data['cardNumber']
        port_number = serializer.validated_data['portNumber']
        host_address = serializer.validated_data['deviceIp']
        shelf_number = serializer.validated_data.get('shelfNumber')
        community_id = serializer.validated_data['communityId']
        transaction_id = serializer.validated_data.get('transactionId')

        client = get_client(community_id)
        result, msg, physical_status = client.get_subscriber_status(
            host_address, port_number, card_number, shelf_number)
        if not result:
            response = {
                'success': False,
                'msg': "Error while getting ADSL subscriber, {0}".format(msg)
            }
            log_action("{0}.{1}".format(str(self), 'get'), request, response,
                       transaction_id)
            return Response(response, status=status.HTTP_200_OK)

        response = {'success': True, 'enabled': physical_status, 'msg': None}
        log_action("{0}.{1}".format(str(self), 'get'), request, response,
                   transaction_id)
        return Response(response, status=status.HTTP_200_OK)
Esempio n. 2
0
    def post(self, request, format=None, **kwargs):
        serializer = kwargs['serializer']
        frame = serializer.validated_data['frame']
        slot = serializer.validated_data['slot']
        port = serializer.validated_data['port']
        ont_id = serializer.validated_data['ontId']
        host_address = serializer.validated_data['hostAddress']
        device_type = serializer.validated_data['deviceType']
        transaction_id = serializer.validated_data['transactionId']
        port_operation = serializer.validated_data['portOperation']

        client = get_client(device_type)
        try:
            if port_operation == 'reset':
                result = client.reset_port(frame, slot, port, ont_id,
                                           host_address)

        except TimeoutException:
            return Response({
                'success': False,
                'msg': "connection timeout"
            },
                            status=status.HTTP_200_OK)

        #log_action("{0}.{1}".format(str(self), 'get'), request, response, transaction_id)
        return Response(result, status=status.HTTP_200_OK)
Esempio n. 3
0
 def get(self):
   user = users.get_current_user()
   if not user:
     self.redirect(users.create_login_url(self.request.uri))
   else:
     # Sux create fast solution
     client = get_client(user=user, create=True)
     
     if not client.char:
       # Sux create fast first map
       place = first_place()
       client.char = create_char(place=place)
     
     else:
       # Put char online and atualize his last_modified
       # to do not become ofline again
       client.char.online = True
       client.char.put()
     
     
     # Client need to update all the screen...
     client.last_update = datetime.datetime.min
     client.put()
     
     template_values = {
                         'is_develompent': is_development,
                         'client_id': client.id,
                         'client_char_id': client.char.id,
                         'client_char_place_id': client.char.place.id,
                         'logout_url': users.create_logout_url(self.request.uri),
                       }
     self.response.headers['Content-Type'] = 'text/html'
     self.response.out.write(template.render(INDEX_PATH, template_values))
Esempio n. 4
0
    def handle_msg(self, command):
        ex = Exchange()
        try:
            ex.ParseFromString(command)
        except Exception as e:
            print 'Exception received ', e
            logging.error(e)
            self.transport.loseConnection()
            return
        exr = Exchange()
        if not self.registered:
            if not ex.HasField('hb'):
                exr.mid = ex.mid
                ex.sm.sv = StatusMsg.FAIL
                resp = exr.SerializeToString()
                outlen = len(resp)
                outbuf = pack('i', outlen)
                self.sendData(outbuf + resp)
                return
            else:
                self.registered = True
                hb = ex.hb
                self.clientId = hb.clientId
                statusdata = utility.get_StatusMsg_bin(ex.mid,
                                                       StatusMsg.SUCCESS)
                self.sendData(statusdata)
                self.allclients.add_client(self.clientId, self)
        else:
            if ex.HasField('ur'):
                logging.debug('Unregistering client ' + self.clientId)
                self.allclients.unRegisterClient(self.clientId)
                self.transport.loseConnection()
                return
            self.allclients.add_client(self.clientId)
            if ex.HasField('clocks'):
                # details about locks is wanted
                c_locks = ex.clocks
                clientId = c_locks.clientId
                if not get_client().is_registered(clientId):
                    exr.sm = CLIENT_NOT_REGISTERED
                    resp = exr.SerializeToString()
                    outlen = len(resp)
                    outbuf(pack('i', outlen))
                    self.sendData(outbuf + resp)
                else:
                    clocks = get_lc().getClientLocks(clientId)
            elif ex.HasField('ld'):
                logging.debug('Getting lock dettails  ' + ex.ld.lockName)
                ld = get_lc().getLockDetails(ex.ld.lockName)
                lddata = utility.get_lockDetail_resp_msg(ex.mid, ld)
                self.sendData(lddata)

            elif ex.HasField('lc'):
                lcl = ex.lc
                logging.debug('Received lock request ' + ' ' + lcl.clientId +
                              ' ' + lcl.cmd.lockId + ' ' +
                              str(lcl.cmd.op.opval))
                eobj = event(common.LOCKOP_TOPIC, ex, str(lcl.cmd.lockId))
                self.ebus.post(eobj)
Esempio n. 5
0
 def __init__(self, ebus):
     DataChunk.__init__(self)
     subscriber.__init__(self)
     self.ebus = ebus
     self.clientId = None
     self.allclients = get_client()
     self.registered = False
     self.peer = None
 def __init__(self, ebus):
     DataChunk.__init__(self)
     subscriber.__init__(self)
     self.ebus = ebus
     self.clientId = None
     self.allclients = get_client()
     self.registered = False
     self.peer = None
    def handle_msg(self, command):
        ex = Exchange()
        try:
            ex.ParseFromString(command)
        except Exception as e:
            print 'Exception received ', e
            logging.error(e)
            self.transport.loseConnection()
            return
        exr = Exchange()
        if not self.registered:
            if not ex.HasField('hb'):
                exr.mid = ex.mid
                ex.sm.sv = StatusMsg.FAIL
                resp = exr.SerializeToString()
                outlen = len(resp)
                outbuf = pack('i', outlen)
                self.sendData(outbuf + resp)
                return
            else:
                self.registered = True
                hb = ex.hb
                self.clientId = hb.clientId
                statusdata = utility.get_StatusMsg_bin(ex.mid, StatusMsg.SUCCESS)
                self.sendData(statusdata)
                self.allclients.add_client(self.clientId, self)
        else:
            if ex.HasField('ur'):
                logging.debug('Unregistering client ' + self.clientId)
                self.allclients.unRegisterClient(self.clientId)
                self.transport.loseConnection()
                return
            self.allclients.add_client(self.clientId)
            if ex.HasField('clocks'):
                # details about locks is wanted
                c_locks = ex.clocks
                clientId = c_locks.clientId 
                if not get_client().is_registered(clientId):
                    exr.sm = CLIENT_NOT_REGISTERED
                    resp = exr.SerializeToString()
                    outlen = len(resp)
                    outbuf(pack('i', outlen))
                    self.sendData(outbuf + resp)
                else:
                    clocks = get_lc().getClientLocks(clientId) 
            elif ex.HasField('ld'):
                logging.debug('Getting lock dettails  ' + ex.ld.lockName) 
                ld = get_lc().getLockDetails(ex.ld.lockName)
                lddata = utility.get_lockDetail_resp_msg(ex.mid, ld) 
                self.sendData(lddata)

            elif ex.HasField('lc'):
                lcl = ex.lc 
                logging.debug('Received lock request ' + ' ' +
                               lcl.clientId + ' ' + lcl.cmd.lockId + ' ' +
                               str(lcl.cmd.op.opval))
                eobj = event(common.LOCKOP_TOPIC, ex, str(lcl.cmd.lockId))
                self.ebus.post(eobj)
Esempio n. 8
0
def add():
    client = get_client()
    ssh_config = defaultdict(str)

    while True:
        ssh_config['hostname'] = prompt_line('HostName[{}]: ',
                                             ssh_config['hostname'],
                                             (ssh_config['hostname'], ))

        ssh_config['host'] = prompt_line('Host[{}]: ', ssh_config['host'],
                                         (ssh_config['host'], ))

        ssh_config['port'] = prompt_line('Port[{}]: ', ssh_config['port'],
                                         (ssh_config['port'], ))

        ssh_config['user'] = prompt_line('User[{}]: ', ssh_config['user'],
                                         (ssh_config['user'], ))

        ssh_config['identityfile'] = prompt_line(
            'IdentityFile[{}]: ', ssh_config['identityfile'],
            (ssh_config['identityfile'], ))

        ok = raw_input(
            json.dumps(ssh_config, indent=4) + '\nare you sure? [Y/N]: ')
        ok = ok.strip()

        if ok.lower() == 'y':
            break
        else:
            continue

    hostname = ssh_config['hostname']
    identityfile = ssh_config['identityfile']

    if identityfile:
        with open(identityfile) as f:
            cert_content = f.read()
            cert_filename = '{}.cert'.format(hostname)
            client.upload(cert_content, cert_filename)

    config_filename = '{}.json'.format(hostname)
    ssh_config = json.dumps(ssh_config, indent=4)
    client.upload(ssh_config, config_filename)
Esempio n. 9
0
def connect(hostname):
    client = get_client()
    ssh_json = '{}.json'.format(hostname)
    content = client.download(ssh_json)
    ssh_config = json.loads(content)
    local_ssh_cert_path = ''

    if ssh_config.get('identityfile', None):
        ssh_cert_path = '{}.cert'.format(hostname)
        ssh_cert_filename = '{}.cert'.format(hostname)
        home_env = os.getenv('HOME', None)
        local_ssh_cert_dir = os.path.join(home_env, '.sshr_certs')
        mkdir(local_ssh_cert_dir)
        local_ssh_cert_path = os.path.join(local_ssh_cert_dir,
                                           ssh_cert_filename)

        content = client.download(ssh_cert_path)
        with open(local_ssh_cert_path, 'w') as f:
            f.write(str(content))

        os.chmod(local_ssh_cert_path, 0o600)

    user = ssh_config['user']
    host = ssh_config['host']
    port = ssh_config['port']
    ssh_command = ''
    if local_ssh_cert_path:
        ssh_command = 'ssh {}@{} -p {} -i {}'.format(user, host, port,
                                                     local_ssh_cert_path)
    else:
        ssh_command = 'ssh {}@{} -p {}'.format(user, host, port)

    # mac Sierra(10.12.2)   ssh-add -K
    os.system(ssh_command)

    if local_ssh_cert_path:
        os.remove(local_ssh_cert_path)
Esempio n. 10
0
 def post(self):
   user = users.get_current_user()
   if not user:
     self.error(403) # access denied
     return
   
   client = get_client(user)
   if not client:
     self.error(403) # access denied
     return
   
   #debug = self.request.get('debug', False)
   
   
   # CAUTION: IT WANNA BE BY ANOTHER WAY (NEED TO IMPLEMENT)
   #char.logged = True
   #char.put()
   
   #self.response.headers.add_header("Content-Type", 'application/json')
   
   # Action to execute
   action = self.request.get('action')
   
   # Arguments of the action
   args = self.request.get_all('args[]')
   # REMOVE ALL EMPTY VALUE OF THE ARGS
   for i in range(args.count('')):
     args.remove('')
   
   
   # Target of the action
   target_id = self.request.get('target')
   if target_id:
     target = db.get(db.Key(target_id))
     # DEBUG
     if not target:
       response['alert'].append('TARGET NOT AVAILABLE')
   else:
     target = None
   
   
   # Client time that executed the action
   client_time = self.request.get('time')
   
   # Append to the response the action feedback or one alert or error if it has
   response = {
                 'action': action,
                 'target': target,
                 'args': args,
                 'client_time': client_time,
                 #'server_hour': datetime.datetime.now().strftime('%I:%M:%S'),
                 'self': client.char.id,
                 #'object': {}, Thinking about it here in action_handler
                 #'listener': {}, Not implemented yet
                 'alert': [],
                 'error': [],
               }
   
   
   if action == 'ping':
     pass
   
   elif action == 'get_channel_token':
     client.channel_token = create_channel(client.id)
     client.put()
     response['channel_token'] = client.channel_token
   
   elif action in actions_signatures:
     #response['alert'].append('Action found:' + action)
     if validate_args(actions_signatures[action], args):
       #function = getattr(actions, action)
       #function(client, response, args)
       query = db.Query(Action)
       query.filter('active =', True)
       query.filter('action =', action)
       query.filter('char =', client.char)
       saved_action = query.get()
       if saved_action:
         response['alert'].append('ACTION ACTIVE FOUND')
         saved_action.args = args
         saved_action.target = target
         saved_action.put()
       else:
         response['alert'].append('NEW ACTION CREATED')
         action = Action(char=client.char,
                         action=action,
                         args=args,
                         target=target)
         action.put()
         
       
     else:
       response['error'].append('ERROR TO VALIDATE ARGS')
   
   else:
     response['error'].append('ACTION NOT ALLOWED')
   
   self.response.out.write(simplejson.dumps(response))
   return
Esempio n. 11
0
def delete(hostname):
    client = get_client()
    ssh_json = '{}.json'.format(hostname)
    ssh_cert = '{}.cert'.format(hostname)
    client.delete(ssh_json)
    client.delete(ssh_cert)
Esempio n. 12
0
def info(hostname):
    client = get_client()
    path = '{}.json'.format(hostname)
    content = client.download(path)
    click.echo(content)
Esempio n. 13
0
def list():
    client = get_client()
    for filename in client.list(''):
        if filename.endswith('.json'):
            click.echo(os.path.splitext(filename)[0])
Esempio n. 14
0
 def post(self, is_get=False):
 
   if is_get:
     self.response.out.write('is_get = '+str(is_get)+'<br />')
   
   user = users.get_current_user()
   if not user:
     self.error(403) # access denied
     return
   
   client = get_client(user)
   if not client:
     self.error(403) # access denied
     return
   
   
   
   if is_development or is_get:
     loop_range = 1
   else:
     loop_range = 28
   for i in range(loop_range):
     
     
     # Checks if the player d made the atualization in this second
     # if he made the atualization this second,
     # he must wait to the next second
     # Server delay is a timedelta that the server
     # spent to process last update, something like 3500microseconds
     
     feeder_start = datetime.datetime.now()
     deltatime = feeder_start - client.last_update
     if deltatime.seconds == 0:
       # now is less than a second since the last update
       
       # Estimated time to sleep
       sleep_time = float(1000000 - deltatime.microseconds)/1000000
       if is_development or is_get:
         self.response.out.write('sleep: '+str(sleep_time)+'<br />')
       sleep(sleep_time)
       feeder_start = datetime.datetime.now()
     
     
     # This is a especial case that the client has just opened the browser
     # and he needs to get full_updates of all places
     if client.last_update == datetime.datetime.min:
       if is_development or is_get:
         self.response.out.write('FULL UPDATES<br />')
       updates = full_updates(client)
     
     
     else:
       """
       # Henceforward (daqui em diante) assume that the char have ur screen
       
       # If the server has not responded yet, wait for its response
       server_last_update = memcache.get('server_last_update')
       if not server_last_update:
         # We can't set datetime.datetime.min,
         # because strftime can't mannage years before 1900
         server_last_update = datetime.datetime(2000,1,1)
       deltatime = feeder_start - server_last_update
       while deltatime.seconds > 0:
         # Server do not atualize in this second, wait the atualization
         sleep(float(server_delay*(10))/1000000)
         server_last_update = memcache.get('server_last_update')
         if not server_last_update:
           # We can't set datetime.datetime.min,
           # because strftime can't mannage years before 1900
           server_last_update = datetime.datetime(2000,1,1)
         deltatime = feeder_start - server_last_update
         if datetime.datetime.now().second > feeder_start.second:
           # It tryed all this second for te actualization
           break
       """
       updates = {
                   #'server_hour':server_last_update.strftime('%I:%M:%S ')
                   #              + ':' +str(server_last_update.microsecond),
                   #'server_delay':server_delay
                 }
       
       
       if is_development or is_get:
         self.response.out.write('HALF UPDATES<br />')
       
       
       query = db.Query(Update)
       query.filter('place =', client.char.place)
       query.filter('datetime >', client.last_update)
       for update in query:
         new_update = update.update
         if is_development or is_get:
           self.response.out.write('update:'+str(update.place)+'<br />')
         
         # ADDING UPDATES CHANGES
         for update_type in new_update:
           if type(new_update[update_type]) == str:
             updates[update_type] = new_update[update_type]
           
           elif type(new_update[update_type]) == list:
             if not update_type in updates:
               updates[update_type] = []
             for new_obj in new_update[update_type]:
               updates[update_type].append(new_obj)
           
           elif type(new_update[update_type]) == dict:
             if not update_type in updates:
               updates[update_type] = {}
             for key in new_update[update_type]:
               updates[update_type][key] = new_update[update_type][key]
         
     
   
   
   
     client.last_update = feeder_start
     
     #updates = 'testando'
     if updates:
       #updates['object'] = object_list
       if is_development or is_get:
         self.response.out.write('sending to:'+client.id+'<br />')
         self.response.out.write('<br />'+simplejson.dumps(updates)+'<br />')
       send_message(client.id, simplejson.dumps(updates))
     else:
       self.response.out.write('no updates to send to:'+client.channel_token+'<br />')
     
   client.put()