Beispiel #1
0
 def delete(self, req, agent_id, body=None):
     """call buy agent"""
     # if force is true
     # will not notify agent, just delete agent from database
     body = body or {}
     force = body.get('force', False)
     rpc = get_client()
     global_data = get_global()
     metadata = None
     with global_data.delete_agent(agent_id) as agent:
         if not force:
             metadata = BaseContorller.agent_metadata(agent.agent_id)
             if metadata is None:
                 raise RpcPrepareError('Can not delete offline agent, try force')
             agent_ipaddr = metadata.get('local_ip')
             secret = uuidutils.generate_uuid()
             # tell agent wait delete
             finishtime, timeout = rpcfinishtime()
             delete_agent_precommit = rpc.call(targetutils.target_agent(agent),
                                               ctxt={'finishtime': finishtime},
                                               msg={'method': 'delete_agent_precommit',
                                                    'args': {'agent_id': agent.agent_id,
                                                             'agent_type': agent.agent_type,
                                                             'host': agent.host,
                                                             'agent_ipaddr': agent_ipaddr,
                                                             'secret': secret}
                                                    }, timeout=timeout)
             if not delete_agent_precommit:
                 raise RpcResultError('delete_agent_precommit result is None')
             if delete_agent_precommit.get('resultcode') != manager_common.RESULT_SUCCESS:
                 return resultutils.results(result=delete_agent_precommit.get('result'),
                                            resultcode=manager_common.RESULT_ERROR)
     # if not force:
             # tell agent delete itself
             finishtime = rpcfinishtime()[0]
             LOG.info('Delete agent %s postcommit with secret %s' % (agent_ipaddr, secret))
             rpc.cast(targetutils.target_agent(agent),
                      ctxt={'finishtime': finishtime},
                      msg={'method': 'delete_agent_postcommit',
                           'args': {'agent_id': agent.agent_id,
                                    'agent_type': agent.agent_type,
                                    'host': agent.host,
                                    'agent_ipaddr': agent_ipaddr,
                                    'secret': secret}})
     def wapper():
         rpc.cast(targetutils.target_rpcserver(fanout=True),
                  msg={'method': 'deletesource',
                       'args': {'agent_id': agent_id}})
     threadpool.add_thread(safe_func_wrapper, wapper, LOG)
     result = resultutils.results(result='Delete agent success',
                                  data=[dict(agent_id=agent.agent_id,
                                             host=agent.host,
                                             status=agent.status,
                                             metadata=metadata,
                                             ports_range=jsonutils.safe_loads_as_bytes(agent.ports_range) or [])
                                        ])
     return result
Beispiel #2
0
    def readlog(self, req, agent_id, body=None):
        """call by agent"""
        body = body or {}
        lines = body.get('lines', 10)
        rpc = get_client()
        metadata = BaseContorller.agent_metadata(agent_id)
        if metadata is None:
            raise RpcPrepareError('Can not get log from offline agent: %d' % agent_id)

        session = get_session()
        query = model_query(session, Agent, filter=Agent.agent_id == agent_id)
        agent = query.one()
        rpc_ret = rpc.call(targetutils.target_agent(agent),
                           ctxt={'finishtime': rpcfinishtime()[0]},
                           msg={'method': 'readlog', 'args': {'lines': lines}})
        if not rpc_ret:
            raise RpcResultError('Get log agent rpc result is None')
        if rpc_ret.get('resultcode') != manager_common.RESULT_SUCCESS:
            raise RpcResultError('Get log agent rpc result: ' + rpc_ret.get('result'))
        return resultutils.results(result=rpc_ret.get('result'), data=[rpc_ret.get('uri')])
Beispiel #3
0
 def active(self, req, agent_id, body=None):
     """call buy client"""
     body = body or {}
     status = body.get('status', manager_common.ACTIVE)
     if status not in (manager_common.ACTIVE, manager_common.UNACTIVE):
         raise InvalidArgument('Argument status not right')
     rpc = get_client()
     session = get_session()
     query = model_query(session, Agent,
                         filter=and_(Agent.agent_id == agent_id,
                                     Agent.status > manager_common.DELETED))
     agent = query.one()
     # make sure agent is online
     metadata = BaseContorller.agent_metadata(agent.agent_id)
     if metadata is None:
         raise RpcPrepareError('Can not active or unactive a offline agent: %d' % agent_id)
     agent_ipaddr = metadata.get('local_ip')
     with session.begin():
         agent.update({'status': status})
         active_agent = rpc.call(targetutils.target_agent(agent),
                                 ctxt={'finishtime': rpcfinishtime()[0]},
                                 msg={'method': 'active_agent',
                                      'args': {'agent_id': agent_id,
                                               'agent_ipaddr': agent_ipaddr,
                                               'status': status}
                                      })
         if not active_agent:
             raise RpcResultError('Active agent rpc result is None')
         if active_agent.pop('resultcode') != manager_common.RESULT_SUCCESS:
             raise RpcResultError('Call agent active or unactive fail: ' + active_agent.get('result'))
         result = resultutils.results(result=active_agent.pop('result'),
                                      data=[dict(agent_id=agent.agent_id,
                                                 host=agent.host,
                                                 agent_type=agent.agent_type,
                                                 metadata=metadata,
                                                 status=agent.status)
                                            ])
         return result
Beispiel #4
0
    def create(self, req, agent_id, endpoint, body=None, action='create'):
        body = body or {}
        endpoint = validateutils.validate_endpoint(endpoint)
        ports = body.pop('ports', None)
        notify = body.pop('notify', True)
        desc = body.pop('desc', None)
        session = get_session()
        metadata = None
        if ports:
            ports = argutils.map_with(ports, validators['type:port'])
            used_ports = model_count_with_key(
                session,
                AllocatedPort.port,
                filter=and_(AllocatedPort.agent_id == agent_id,
                            AllocatedPort.port.in_(ports)))
            if used_ports:
                raise InvalidArgument('Ports has been used count %d' %
                                      used_ports)

        if notify:
            metadata = BaseContorller.agent_metadata(agent_id)
            # make sure agent is online
            if not metadata:
                raise RpcPrepareError(
                    'Can not create entity on a offline agent %d' % agent_id)

        entity = 0
        glock = get_global().lock('agents')
        elock = get_global().lock('endpoint')
        result = 'add entity success.'
        with glock([
                agent_id,
        ]):
            with elock(endpoint):
                with session.begin(subtransactions=True):
                    query = model_query(session,
                                        Agent,
                                        filter=Agent.agent_id == agent_id)
                    query = query.options(
                        joinedload(Agent.endpoints, innerjoin=False))
                    agent = query.one()
                    if agent.status != manager_common.ACTIVE:
                        raise InvalidArgument(
                            'Create entity fail, agent status is not active')

                    _endpoint = None
                    for e in agent.endpoints:
                        if endpoint == e.endpoint:
                            _endpoint = e
                            break
                    if not _endpoint:
                        raise InvalidArgument(
                            'Create entity fail, agent %d has no endpoint %s' %
                            (agent_id, endpoint))
                    entity_autoincrement_id = model_autoincrement_id(
                        session,
                        AgentEntity.entity,
                        filter=AgentEntity.endpoint == endpoint)
                    entity = body.get('entity') or entity_autoincrement_id
                    if entity < entity_autoincrement_id:
                        raise InvalidArgument(
                            'Create entity fail, entity less then autoincrement id'
                        )
                    _entity = AgentEntity(entity=entity,
                                          endpoint=endpoint,
                                          agent_id=agent_id,
                                          endpoint_id=_endpoint.id,
                                          desc=desc)
                    session.add(_entity)
                    session.flush()
                    LOG.info('Create entity %s.%d with entity id %s' %
                             (endpoint, entity, _entity.id))
                    if ports:
                        for port in ports:
                            session.add(
                                AllocatedPort(port=port,
                                              agent_id=agent_id,
                                              endpoint_id=_endpoint.id,
                                              entity_id=entity.id,
                                              endpoint=endpoint,
                                              entity=entity))
                            session.flush()
                    if notify:
                        target = targetutils.target_agent(agent)
                        target.namespace = endpoint
                        create_result = self.notify_create(
                            target, agent.agent_id, entity, body, action)
                        if not create_result:
                            raise RpcResultError(
                                'create entitys result is None')
                        if create_result.get(
                                'resultcode') != manager_common.RESULT_SUCCESS:
                            raise RpcResultError('create entity fail %s' %
                                                 create_result.get('result'))
                        result += create_result.get('result')
                        notify = create_result
        return resultutils.results(result=result,
                                   data=[
                                       dict(entity=entity,
                                            agent_id=agent_id,
                                            metadata=metadata,
                                            endpoint=endpoint,
                                            ports=ports or [],
                                            notify=notify)
                                   ])