//------------------------------------------------------------------------------------- void Base::onCellWriteToDBCompleted() { PyObject* pyResult = PyObject_CallMethod(this, const_cast<char*>("onPreArchive"), const_cast<char*>("")); if(pyResult != NULL) Py_DECREF(pyResult); else PyErr_PrintEx(0); hasDB(true); onWriteToDB(); isArchiveing_ = false; MemoryStream* s = MemoryStream::ObjPool().createObject(); addPersistentsDataToStream(ED_FLAG_ALL, s); Components::COMPONENTS cts = Components::getSingleton().getComponents(DBMGR_TYPE); Components::ComponentInfos* dbmgrinfos = NULL; if(cts.size() > 0) dbmgrinfos = &(*cts.begin()); if(dbmgrinfos == NULL || dbmgrinfos->pChannel == NULL || dbmgrinfos->cid == 0) { ERROR_MSG("Base::onCellWriteToDBCompleted: not found dbmgr!\n"); return; } Mercury::Bundle bundle; bundle.newMessage(DbmgrInterface::writeEntity); bundle << this->getID(); bundle << this->getScriptModule()->getUType(); bundle.append(*s); bundle.send(Baseapp::getSingleton().getNetworkInterface(), dbmgrinfos->pChannel); MemoryStream::ObjPool().reclaimObject(s); }
static void t_bootstrap(void *boot_raw) { struct bootstate *boot = (struct bootstate *) boot_raw; PyThreadState *tstate; PyObject *res; tstate = PyThreadState_New(boot->interp); PyEval_AcquireThread(tstate); res = PyEval_CallObjectWithKeywords( boot->func, boot->args, boot->keyw); if (res == NULL) { if (PyErr_ExceptionMatches(PyExc_SystemExit)) PyErr_Clear(); else { PyObject *file; PySys_WriteStderr( "Unhandled exception in thread started by "); file = PySys_GetObject("stderr"); if (file) PyFile_WriteObject(boot->func, file, 0); else PyObject_Print(boot->func, stderr, 0); PySys_WriteStderr("\n"); PyErr_PrintEx(0); } } else Py_DECREF(res); Py_DECREF(boot->func); Py_DECREF(boot->args); Py_XDECREF(boot->keyw); PyMem_DEL(boot_raw); PyThreadState_Clear(tstate); PyThreadState_DeleteCurrent(); PyThread_exit_thread(); }
//------------------------------------------------------------------------------------- PyObject* Cellapp::__py_executeRawDatabaseCommand(PyObject* self, PyObject* args) { int argCount = PyTuple_Size(args); PyObject* pycallback = NULL; int ret = -1; char* data = NULL; Py_ssize_t size; if(argCount == 2) ret = PyArg_ParseTuple(args, "s#|O", &data, &size, &pycallback); else if(argCount == 1) ret = PyArg_ParseTuple(args, "s#", &data, &size); if(ret == -1) { PyErr_Format(PyExc_TypeError, "KBEngine::executeRawDatabaseCommand: args is error!"); PyErr_PrintEx(0); } Cellapp::getSingleton().executeRawDatabaseCommand(data, size, pycallback); S_Return; }
int htpy_log_callback(htp_log_t *log) { PyObject *obj = (PyObject *) htp_connp_get_user_data(log->connp); PyObject *arglist = NULL; PyObject *res; long i; if (((htpy_connp *) obj)->obj_store) arglist = Py_BuildValue("(OsiO)", (htpy_connp *) obj, log->msg, log->level, ((htpy_connp *) obj)->obj_store); else arglist = Py_BuildValue("(Osi)", (htpy_connp *) obj, log->msg, log->level); if (!arglist) return HTP_ERROR; res = PyObject_CallObject(((htpy_connp *) obj)->log_callback, arglist); Py_DECREF(arglist); if (PyErr_Occurred() != NULL) { PyErr_PrintEx(0); return HTP_ERROR; } i = PyInt_AsLong(res); Py_DECREF(res); return((int) i); }
int run_code(int val){ //int main(void){ int ret = 0; PyObject* retval; Py_Initialize(); PyRun_SimpleString("print('hello word from embedded python')"); PyObject* main_mod = PyImport_AddModule("__main__"); PyObject* main_dic = PyModule_GetDict(main_mod); const char *script_name = "hello.py"; FILE* script = fopen(script_name,"r"); retval = PyImport_ImportModule("numpy"); // retval = PyImport_ImportModuleEx("numpy", main_dic, main_dic, NULL); if(!retval) goto py_error; retval = PyRun_File(script, script_name, Py_file_input, main_dic, main_dic); if(!retval) goto py_error; /* PyObject* retobj = PyRun_String("foo(11)", Py_eval_input, main_dic, main_dic); long retval = PyLong_AsLong(retobj); */ py_exit: Py_Finalize(); return ret; py_error: ret = -1; printf("exception in script !?"); PyErr_PrintEx(0); goto py_exit; }
PyObject * Entities<T>::mp_subscript(PyObject* self, PyObject* key /*entityID*/) { Entities* lpEntities = static_cast<Entities*>(self); ENTITY_ID entityID = PyLong_AsLong(key); if (PyErr_Occurred()) return NULL; PyObject * pyEntity = NULL; ENTITYS_MAP& entities = lpEntities->getEntities(); ENTITYS_MAP::const_iterator iter = entities.find(entityID); if (iter != entities.end()) pyEntity = iter->second.get(); if(pyEntity == NULL) { PyErr_Format(PyExc_KeyError, "%d", entityID); PyErr_PrintEx(0); return NULL; } Py_INCREF(pyEntity); return pyEntity; }
//------------------------------------------------------------------------------------- PyObject* ScriptVector2::__py_pyDistSqrTo(PyObject* self, PyObject* args) { if (PyTuple_Size(args) != 1) { PyErr_SetString(PyExc_TypeError, "args > 1 is error!\n"); PyErr_PrintEx(0); S_Return; } PyObject* pyVal = PyTuple_GET_ITEM(args, 0); if(!check(pyVal)) { S_Return; } ScriptVector2* sv = static_cast<ScriptVector2*>(self); Vector2& v = sv->getVector(); Vector2 v1; convertPyObjectToVector2(v1, pyVal); Vector2 rv = (v - v1); return PyFloat_FromDouble(KBEVec2LengthSq(&rv)); //计算点乘并返回 }
//------------------------------------------------------------------------------------- PyObject* EntityRemoteMethod::tp_call(PyObject* self, PyObject* args, PyObject* kwds) { EntityRemoteMethod* rmethod = static_cast<EntityRemoteMethod*>(self); MethodDescription* methodDescription = rmethod->getDescription(); EntityMailboxAbstract* mailbox = rmethod->getMailbox(); if(!mailbox->isClient()) { return RemoteEntityMethod::tp_call(self, args, kwds); } Entity* pEntity = Cellapp::getSingleton().findEntity(mailbox->id()); if(pEntity == NULL || pEntity->pWitness() == NULL) { //WARNING_MSG(fmt::format("EntityRemoteMethod::callClientMethod: not found entity({}).\n", // mailbox->id())); return RemoteEntityMethod::tp_call(self, args, kwds); } Network::Channel* pChannel = pEntity->pWitness()->pChannel(); if(!pChannel) { PyErr_Format(PyExc_AssertionError, "%s:EntityRemoteMethod(%s)::tp_call: no client, srcEntityID(%d).\n", pEntity->scriptName(), methodDescription->getName(), pEntity->id()); PyErr_PrintEx(0); return RemoteEntityMethod::tp_call(self, args, kwds); } // 如果是调用客户端方法, 我们记录事件并且记录带宽 if(methodDescription->checkArgs(args)) { Network::Bundle* pBundle = pChannel->createSendBundle(); mailbox->newMail((*pBundle)); MemoryStream* mstream = MemoryStream::createPoolObject(); methodDescription->addToStream(mstream, args); if(mstream->wpos() > 0) (*pBundle).append(mstream->data(), (int)mstream->wpos()); if(Network::g_trace_packet > 0) { if(Network::g_trace_packet_use_logfile) DebugHelper::getSingleton().changeLogger("packetlogs"); DEBUG_MSG(fmt::format("EntityRemoteMethod::tp_call: pushUpdateData: ClientInterface::onRemoteMethodCall({}::{})\n", pEntity->scriptName(), methodDescription->getName())); switch(Network::g_trace_packet) { case 1: mstream->hexlike(); break; case 2: mstream->textlike(); break; default: mstream->print_storage(); break; }; if(Network::g_trace_packet_use_logfile) DebugHelper::getSingleton().changeLogger(COMPONENT_NAME_EX(g_componentType)); } // 记录这个事件产生的数据量大小 g_privateClientEventHistoryStats.trackEvent(pEntity->scriptName(), methodDescription->getName(), pBundle->currMsgLength(), "::"); pEntity->pWitness()->sendToClient(ClientInterface::onRemoteMethodCall, pBundle); MemoryStream::reclaimPoolObject(mstream); } S_Return; }
//------------------------------------------------------------------------------------- PyObject* Proxy::__py_pyStreamStringToClient(PyObject* self, PyObject* args) { uint16 currargsSize = PyTuple_Size(args); Proxy* pobj = static_cast<Proxy*>(self); if(pobj->clientMailbox() == NULL) { PyErr_Format(PyExc_AssertionError, "Proxy::streamStringToClient: has no client."); PyErr_PrintEx(0); return NULL; } if(currargsSize > 3 || currargsSize == 0) { PyErr_Format(PyExc_AssertionError, "Proxy::streamStringToClient: args max require 3, gived %d! is script[%s].\n", currargsSize, pobj->scriptName()); PyErr_PrintEx(0); return NULL; } PyObject* pyData = NULL; PyObject* pyDesc = NULL; int16 id = -1; if(currargsSize == 1) { if(PyArg_ParseTuple(args, "O", &pyData) == -1) { PyErr_Format(PyExc_TypeError, "Proxy::streamStringToClient: args is error!"); PyErr_PrintEx(0); return NULL; } } else if(currargsSize == 2) { if(PyArg_ParseTuple(args, "O|O", &pyData, &pyDesc) == -1) { PyErr_Format(PyExc_TypeError, "Proxy::streamStringToClient: args is error!"); PyErr_PrintEx(0); return NULL; } } else if(currargsSize == 3) { if(PyArg_ParseTuple(args, "O|O|H", &pyData, &pyDesc, &id) == -1) { PyErr_Format(PyExc_TypeError, "Proxy::streamStringToClient: args is error!"); PyErr_PrintEx(0); return NULL; } } char* pDescr = NULL; if(pDescr != NULL) { wchar_t* PyUnicode_AsWideCharStringRet1 = PyUnicode_AsWideCharString(pyDesc, NULL); pDescr = strutil::wchar2char(PyUnicode_AsWideCharStringRet1); PyMem_Free(PyUnicode_AsWideCharStringRet1); } if(pDescr && strlen(pDescr) > 255) { PyErr_Format(PyExc_TypeError, "Proxy::streamFileToClient: the descr-size(%d > 255)!", strlen(pDescr)); PyErr_PrintEx(0); free(pDescr); return NULL; } int16 rid = pobj->streamStringToClient(pyData, (pDescr == NULL ? "" : pDescr), id); if(pDescr) free(pDescr); return PyLong_FromLong(rid); }
//------------------------------------------------------------------------------------- void Proxy::giveClientTo(Proxy* proxy) { if(isDestroyed()) { char err[255]; kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: %d is destroyed.", scriptName(), id()); PyErr_SetString(PyExc_TypeError, err); PyErr_PrintEx(0); onGiveClientToFailure(); return; } if(clientMailbox_ == NULL || clientMailbox_->getChannel() == NULL) { char err[255]; kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: no has client.", scriptName()); PyErr_SetString(PyExc_TypeError, err); PyErr_PrintEx(0); onGiveClientToFailure(); return; } Network::Channel* lpChannel = clientMailbox_->getChannel(); if(proxy) { if(proxy->isDestroyed()) { char err[255]; kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: target(%d) is destroyed.", scriptName(), proxy->id()); PyErr_SetString(PyExc_TypeError, err); PyErr_PrintEx(0); onGiveClientToFailure(); return; } if(proxy->id() == this->id()) { char err[255]; kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: target(%d) is self.", scriptName(), proxy->id()); PyErr_SetString(PyExc_TypeError, err); PyErr_PrintEx(0); onGiveClientToFailure(); return; } EntityMailbox* mb = proxy->clientMailbox(); if(mb != NULL) { ERROR_MSG(fmt::format("Proxy::giveClientTo: {}[{}] give client to {}[{}], {} has clientMailbox.\n", scriptName(), id(), proxy->scriptName(), proxy->id(), proxy->scriptName())); onGiveClientToFailure(); return; } if(cellMailbox()) { // 当前这个entity如果有cell,说明已经绑定了witness, 那么既然我们将控制权 // 交换给了另一个entity, 这个entity需要解绑定witness。 // 通知cell丢失witness Network::Bundle* pBundle = Network::Bundle::ObjPool().createObject(); (*pBundle).newMessage(CellappInterface::onLoseWitness); (*pBundle) << this->id(); sendToCellapp(pBundle); } // 既然客户端失去对其的控制, 那么通知client销毁这个entity Network::Bundle* pBundle = Network::Bundle::ObjPool().createObject(); (*pBundle).newMessage(ClientInterface::onEntityDestroyed); (*pBundle) << this->id(); sendToClient(ClientInterface::onEntityDestroyed, pBundle); // 将控制权交换 entitiesEnabled_ = false; clientMailbox()->addr(Network::Address::NONE); Py_DECREF(clientMailbox()); proxy->setClientType(this->getClientType()); proxy->setClientDatas(this->getClientDatas()); this->setClientType(UNKNOWN_CLIENT_COMPONENT_TYPE); this->setClientDatas(""); clientMailbox(NULL); proxy->onGiveClientTo(lpChannel); addr(Network::Address::NONE); } }
//------------------------------------------------------------------------------------- PyObject* ScriptVector2::seq_slice(PyObject* self, Py_ssize_t startIndex, Py_ssize_t endIndex) { if(startIndex < 0) startIndex = 0; if(endIndex > VECTOR_SIZE) endIndex = VECTOR_SIZE; if(endIndex < startIndex) endIndex = startIndex; ScriptVector2* sv = static_cast<ScriptVector2*>(self); Vector2& my_v = sv->getVector(); PyObject* pyResult = NULL; int length = (int)(endIndex - startIndex); if (length == VECTOR_SIZE) { pyResult = sv; Py_INCREF(pyResult); } else switch(length) { case 0: pyResult = PyTuple_New(0); break; case 1: pyResult = PyTuple_New(1); PyTuple_SET_ITEM(pyResult, 0, PyFloat_FromDouble(sv->getVector()[static_cast<int>(startIndex)])); break; case 2: { Vector2 v; for (int i = (int)startIndex; i < (int)endIndex; ++i){ v[i - static_cast<int>(startIndex)] = my_v[i]; } pyResult = new ScriptVector2(v); break; } case 3: { Vector3 v; for (int i = (int)startIndex; i < (int)endIndex; ++i){ v[i - static_cast<int>(startIndex)] = my_v[i]; } pyResult = new ScriptVector3(v); break; } default: PyErr_Format(PyExc_IndexError, "Bad slice indexes [%d, %d] for Vector%d", startIndex, endIndex, VECTOR_SIZE); PyErr_PrintEx(0); break; } return pyResult; }
void PyErr_Print(void) { PyErr_PrintEx(1); }
PyObject *TuplesDefaultImpl::ubiquitous_caller ( exceptionHandler &h , PyObject *args , PyObject *kwds , const bool is_probe , const callerTypes ct ) { const callVariants cv = m_data.cv; const modes mode = is_probe ? (_G_signature_hack_enabled ? modeInitHack : modeInit) : modeRun; TuplesData2DefaultImpl &data = dynamic_cast<TuplesData2DefaultImpl &>(m_data); if (mode == modeRun && !m_data.m_valid) { PyErr_Format(PyExc_AttributeError, "Tuple invalid due to one or more previous errors. Call impossible in any way (%s)", Container::container().context_by_address(data.m_address).c_str()); return NULL; } if (ct == ctGetter) { TupleState::set_mode_getter(); } else if (ct == ctSetter) { TupleState::set_mode_setter(); } if (mode == modeRun) { m_exec = true; m_tuple = args; m_kw = kwds; m_retval = NULL; } if (mode == modeRun || mode == modeInitHack) { m_clear_before_execute(); bool just_filled = false , exception_thrown ; try { exception_thrown = !exceptionHandler::call(h, data.m_address); just_filled = !exception_thrown; } catch (const ParseException &ex) { //Неверные аргументы Python; только в режиме исполнения PyErr_Format(PyExc_TypeError, "%s (%s)", ex.what(), Container::container().context_by_address(data.m_address).c_str()); exception_thrown = true; just_filled = true; } /* NOTE Despite of exception thrown user call can leave return value inited Non null return value in case of not filled tuple is unbelievable internal error */ if (m_retval && (exception_thrown || !TupleState::is_filled())) { Py_DecRef(m_retval); m_retval = NULL; } if (mode == modeInitHack && PyErr_Occurred()) { PyErr_PrintEx(0); PyErr_Clear(); } if (!TupleState::is_filled()) { /* NOTE Tuple must be filled during first call in any way. Any exceptions or invalid actions inside (TuplesData::*call_t) whereby tuple not filled during first call causes inevitable invalidation. Any subsequent calls waved aside This in the same way as for v_getsetter calls: even if getter filled successfully, error in setter invalidates tuple at all and virce versa */ m_data.m_valid = false; just_filled = false; if (!exception_thrown) { PyErr_Format(PyExc_AttributeError, "Tuple invalid due to unknown reason. Any further calls impossible in any way (%s)", Container::container().context_by_address(data.m_address).c_str()); } } else if (just_filled) { //Here: user call executed successfully or caused parse error just_filled = false; try { just_filled = TupleState::just_filled(); } catch (const CheckCalls::ForbiddenCall &ex) { PyErr_Format(PyExc_AttributeError, "%s (%s)", ex.what(), Container::container().context_by_address(data.m_address).c_str()); } } if (just_filled || m_data.m_valid && (mode == modeInit || mode == modeInitHack)) { m_generate_description(); } } if (cv == v_getsetter && TupleState::mode() == TupleFillState::modSetter || cv == v_setter || cv == v_protof || cv == v_ctor) { return NULL; } if (!PyErr_Occurred() && !m_retval && mode == modeRun) { Py_IncRef(Py_None); m_retval = Py_None; } return m_retval; }
static tree handle_python_attribute(tree *node, tree name, tree args, int flags, bool *no_add_attrs) { PyObject *callable; /* Debug code: */ if (0) { printf("handle_python_attribute called\n"); fprintf(stderr, "node: "); debug_tree(*node); /* the site of the attribute e.g. a var_decl */ fprintf(stderr, "name: "); debug_tree(name); /* an identifier_node e.g. "custom_attribute_without_args" */ fprintf(stderr, "args: "); debug_tree(args); /* if present, a tree_list, e.g. of constants */ fprintf(stderr, "flags: %i\n", flags); fprintf(stderr, "and here!\n"); } /* How do we get to the attribute? This code: const struct attribute_spec *spec = lookup_attribute_spec (name); suggests that attributes must have unique names, so keep a dict mapping strings to callables */ assert(IDENTIFIER_NODE == TREE_CODE(name)); callable = PyDict_GetItemString(attribute_dict, IDENTIFIER_POINTER(name)); assert(callable); { PyGILState_STATE gstate; PyObject *py_args = NULL; PyObject *result = NULL; gstate = PyGILState_Ensure(); /* The args to the function call will be the node, plus the args of the attribute: */ py_args = make_args_for_attribute_callback(*node, args); if (!py_args) { goto cleanup; } result = PyObject_Call(callable, py_args, NULL); if (!result) { /* Treat an unhandled Python error as a compilation error: */ error("Unhandled Python exception raised within %s attribute handler", IDENTIFIER_POINTER(name)); PyErr_PrintEx(1); } /* (the result is ignored) */ cleanup: Py_XDECREF(py_args); Py_XDECREF(result); PyGILState_Release(gstate); } return NULL; // FIXME }
//------------------------------------------------------------------------------------- PyObject* ClientEntity::onScriptGetAttribute(PyObject* attr) { Entity* srcEntity = Cellapp::getSingleton().findEntity(srcEntityID_); if(srcEntity == NULL) { PyErr_Format(PyExc_AssertionError, "Entity::clientEntity: srcEntityID(%d) not found!\n", srcEntityID_); PyErr_PrintEx(0); return 0; } if(srcEntity->isDestroyed()) { PyErr_Format(PyExc_AssertionError, "Entity::clientEntity: srcEntityID(%d) is destroyed!\n", srcEntityID_); PyErr_PrintEx(0); return 0; } if(srcEntity->pWitness() == NULL) { PyErr_Format(PyExc_AssertionError, "%s::clientEntity: no client, srcEntityID(%d).\n", srcEntity->getScriptName(), srcEntity->getID()); PyErr_PrintEx(0); return 0; } EntityRef::AOI_ENTITIES::iterator iter = srcEntity->pWitness()->aoiEntities().begin(); Entity* e = NULL; for(; iter != srcEntity->pWitness()->aoiEntities().end(); iter++) { if((*iter)->id() == clientEntityID_ && ((*iter)->flags() & ENTITYREF_FLAG_ENTER_CLIENT_PENDING) <= 0) { e = (*iter)->pEntity(); break; } } if(e == NULL) { PyErr_Format(PyExc_AssertionError, "%s::clientEntity: not found entity(%d), srcEntityID(%d).\n", srcEntity->getScriptName(), clientEntityID_, srcEntity->getID()); PyErr_PrintEx(0); return 0; } wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(attr, NULL); char* ccattr = strutil::wchar2char(PyUnicode_AsWideCharStringRet0); PyMem_Free(PyUnicode_AsWideCharStringRet0); MethodDescription* md = const_cast<ScriptDefModule*>(e->getScriptModule())->findClientMethodDescription(ccattr); free(ccattr); if(md != NULL) { return new ClientEntityMethod(md, srcEntityID_, clientEntityID_); } return ScriptObject::onScriptGetAttribute(attr); }
//------------------------------------------------------------------------------------- void Proxy::giveClientTo(Proxy* proxy) { if(isDestroyed()) { char err[255]; kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: %d is destroyed.", scriptName(), id()); PyErr_SetString(PyExc_TypeError, err); PyErr_PrintEx(0); onGiveClientToFailure(); return; } if(clientMailbox_ == NULL || clientMailbox_->getChannel() == NULL) { char err[255]; kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: no has client.", scriptName()); PyErr_SetString(PyExc_TypeError, err); PyErr_PrintEx(0); onGiveClientToFailure(); return; } Mercury::Channel* lpChannel = clientMailbox_->getChannel(); if(proxy) { if(proxy->isDestroyed()) { char err[255]; kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: target(%d) is destroyed.", scriptName(), proxy->id()); PyErr_SetString(PyExc_TypeError, err); PyErr_PrintEx(0); onGiveClientToFailure(); return; } if(proxy->id() == this->id()) { char err[255]; kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: target(%d) is self.", scriptName(), proxy->id()); PyErr_SetString(PyExc_TypeError, err); PyErr_PrintEx(0); onGiveClientToFailure(); return; } EntityMailbox* mb = proxy->clientMailbox(); if(mb != NULL) { ERROR_MSG(boost::format("Proxy::giveClientTo: %1%[%2%] give client to %3%[%4%], %5% has clientMailbox.\n") % scriptName() % id() % proxy->scriptName() % proxy->id() % proxy->scriptName()); onGiveClientToFailure(); return; } if(cellMailbox()) { // 通知cell丢失客户端 Mercury::Bundle* pBundle = Mercury::Bundle::ObjPool().createObject(); (*pBundle).newMessage(CellappInterface::onResetWitness); (*pBundle) << this->id(); sendToCellapp(pBundle); } entitiesEnabled_ = false; clientMailbox()->addr(Mercury::Address::NONE); Py_DECREF(clientMailbox()); proxy->onGiveClientTo(lpChannel); clientMailbox(NULL); addr(Mercury::Address::NONE); if(proxy->clientMailbox() != NULL) { // 通知client销毁当前entity Mercury::Bundle* pBundle = Mercury::Bundle::ObjPool().createObject(); (*pBundle).newMessage(ClientInterface::onEntityDestroyed); (*pBundle) << this->id(); proxy->sendToClient(ClientInterface::onEntityDestroyed, pBundle); //Mercury::Bundle::ObjPool().reclaimObject(pBundle); } } }
//------------------------------------------------------------------------------------- bool MethodDescription::checkArgs(PyObject* args) { if (args == NULL || !PyTuple_Check(args)) { PyErr_Format(PyExc_AssertionError, "Method::checkArgs: method[%s] args is not a tuple.\n", getName()); PyErr_PrintEx(0); return false; } int offset = (isExposed() == true && g_componentType == CELLAPP_TYPE && isCell()) ? 1 : 0; uint8 argsSize = argTypes_.size(); uint8 giveArgsSize = PyTuple_Size(args); if (giveArgsSize != argsSize + offset) { PyErr_Format(PyExc_AssertionError, "Method::checkArgs: method[%s] requires exactly %d argument%s%s; %d given", getName(), argsSize, (offset > 0) ? " + exposed(1)" : "", (argsSize == 1) ? "" : "s", PyTuple_Size(args)); PyErr_PrintEx(0); return false; } // 检查是否是一个exposed方法 if(offset > 0) { PyObject* pyExposed = PyTuple_GetItem(args, 0); if (!PyLong_Check(pyExposed)) { PyObject* pyeid = PyObject_GetAttrString(pyExposed, "id"); if (pyeid == NULL || !PyLong_Check(pyeid)) { Py_XDECREF(pyeid); PyErr_Format( PyExc_TypeError, "Method::checkArgs: method[%s] requires None, an id, or an object with an " "id as its first agument", getName()); PyErr_PrintEx(0); return false; } Py_DECREF(pyeid); } } for(uint8 i=0; i <argsSize; i++) { PyObject* pyArg = PyTuple_GetItem(args, i + offset); if (!argTypes_[i]->isSameType(pyArg)) { PyObject* pExample = argTypes_[i]->parseDefaultStr(""); PyErr_Format(PyExc_AssertionError, "Method::checkArgs: method[%s] argument %d: Expected %s, %s found", getName(), i+1, pExample->ob_type->tp_name, pyArg != NULL ? pyArg->ob_type->tp_name : "NULL"); PyErr_PrintEx(0); Py_DECREF(pExample); return false; } } return true; }
//------------------------------------------------------------------------------------- PyObject* ClientEntityMethod::callmethod(PyObject* args, PyObject* kwds) { Entity* srcEntity = Cellapp::getSingleton().findEntity(srcEntityID_); if(srcEntity == NULL) { PyErr_Format(PyExc_AssertionError, "Entity::clientEntity(%s): srcEntityID(%d) not found!\n", methodDescription_->getName(), srcEntityID_); PyErr_PrintEx(0); return 0; } if(srcEntity->isDestroyed()) { PyErr_Format(PyExc_AssertionError, "Entity::clientEntity(%s): srcEntityID(%d) is destroyed!\n", methodDescription_->getName(), srcEntityID_); PyErr_PrintEx(0); return 0; } if(!srcEntity->isReal()) { PyErr_Format(PyExc_AssertionError, "%s::clientEntity(%s): not is real entity, srcEntityID(%d).\n", srcEntity->scriptName(), methodDescription_->getName(), srcEntity->id()); PyErr_PrintEx(0); return 0; } if(srcEntity->pWitness() == NULL) { PyErr_Format(PyExc_AssertionError, "%s::clientEntity(%s): no client, srcEntityID(%d).\n", srcEntity->scriptName(), methodDescription_->getName(), srcEntity->id()); PyErr_PrintEx(0); return 0; } Network::Channel* pChannel = srcEntity->pWitness()->pChannel(); if(!pChannel) { PyErr_Format(PyExc_AssertionError, "%s::clientEntity(%s): no client, srcEntityID(%d).\n", srcEntity->scriptName(), methodDescription_->getName(), srcEntity->id()); PyErr_PrintEx(0); return 0; } EntityRef* pEntityRef = srcEntity->pWitness()->getAOIEntityRef(clientEntityID_); Entity* e = (pEntityRef && ((pEntityRef->flags() & (ENTITYREF_FLAG_ENTER_CLIENT_PENDING | ENTITYREF_FLAG_LEAVE_CLIENT_PENDING)) <= 0)) ? pEntityRef->pEntity() : NULL; if(e == NULL) { PyErr_Format(PyExc_AssertionError, "%s::clientEntity(%s): not found entity(%d), srcEntityID(%d).\n", srcEntity->scriptName(), methodDescription_->getName(), clientEntityID_, srcEntity->id()); PyErr_PrintEx(0); return 0; } MethodDescription* methodDescription = getDescription(); if(methodDescription->checkArgs(args)) { MemoryStream* mstream = MemoryStream::createPoolObject(); methodDescription->addToStream(mstream, args); Network::Bundle* pSendBundle = pChannel->createSendBundle(); NETWORK_ENTITY_MESSAGE_FORWARD_CLIENT_START(srcEntity->id(), (*pSendBundle)); int ialiasID = -1; const Network::MessageHandler& msgHandler = srcEntity->pWitness()->getAOIEntityMessageHandler(ClientInterface::onRemoteMethodCall, ClientInterface::onRemoteMethodCallOptimized, clientEntityID_, ialiasID); ENTITY_MESSAGE_FORWARD_CLIENT_START(pSendBundle, msgHandler, aOIEntityMessage); if(ialiasID != -1) { KBE_ASSERT(msgHandler.msgID == ClientInterface::onRemoteMethodCallOptimized.msgID); (*pSendBundle) << (uint8)ialiasID; } else { KBE_ASSERT(msgHandler.msgID == ClientInterface::onRemoteMethodCall.msgID); (*pSendBundle) << clientEntityID_; } if(mstream->wpos() > 0) (*pSendBundle).append(mstream->data(), (int)mstream->wpos()); if(Network::g_trace_packet > 0) { if(Network::g_trace_packet_use_logfile) DebugHelper::getSingleton().changeLogger("packetlogs"); DEBUG_MSG(fmt::format("ClientEntityMethod::callmethod: pushUpdateData: ClientInterface::onRemoteOtherEntityMethodCall({}::{})\n", srcEntity->scriptName(), methodDescription->getName())); switch(Network::g_trace_packet) { case 1: mstream->hexlike(); break; case 2: mstream->textlike(); break; default: mstream->print_storage(); break; }; if(Network::g_trace_packet_use_logfile) DebugHelper::getSingleton().changeLogger(COMPONENT_NAME_EX(g_componentType)); } ENTITY_MESSAGE_FORWARD_CLIENT_END(pSendBundle, msgHandler, aOIEntityMessage); // 记录这个事件产生的数据量大小 g_publicClientEventHistoryStats.trackEvent(srcEntity->scriptName(), (std::string(e->scriptName()) + "." + methodDescription->getName()), pSendBundle->currMsgLength(), "::"); srcEntity->pWitness()->sendToClient(ClientInterface::onRemoteMethodCallOptimized, pSendBundle); MemoryStream::reclaimPoolObject(mstream); } S_Return; }
PyThreadState * Py_NewInterpreter(void) { PyInterpreterState *interp; PyThreadState *tstate, *save_tstate; PyObject *bimod, *sysmod; if (!initialized) Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); #ifdef WITH_THREAD /* Issue #10915, #15751: The GIL API doesn't work with multiple interpreters: disable PyGILState_Check(). */ _PyGILState_check_enabled = 0; #endif interp = PyInterpreterState_New(); if (interp == NULL) return NULL; tstate = PyThreadState_New(interp); if (tstate == NULL) { PyInterpreterState_Delete(interp); return NULL; } save_tstate = PyThreadState_Swap(tstate); /* XXX The following is lax in error checking */ interp->modules = PyDict_New(); bimod = _PyImport_FindBuiltin("builtins"); if (bimod != NULL) { interp->builtins = PyModule_GetDict(bimod); if (interp->builtins == NULL) goto handle_error; Py_INCREF(interp->builtins); } /* initialize builtin exceptions */ _PyExc_Init(bimod); sysmod = _PyImport_FindBuiltin("sys"); if (bimod != NULL && sysmod != NULL) { PyObject *pstderr; interp->sysdict = PyModule_GetDict(sysmod); if (interp->sysdict == NULL) goto handle_error; Py_INCREF(interp->sysdict); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); /* Set up a preliminary stderr printer until we have enough infrastructure for the io module in place. */ pstderr = PyFile_NewStdPrinter(fileno(stderr)); if (pstderr == NULL) Py_FatalError("Py_Initialize: can't set preliminary stderr"); _PySys_SetObjectId(&PyId_stderr, pstderr); PySys_SetObject("__stderr__", pstderr); Py_DECREF(pstderr); _PyImportHooks_Init(); import_init(interp, sysmod); if (initfsencoding(interp) < 0) goto handle_error; if (initstdio() < 0) Py_FatalError( "Py_Initialize: can't initialize sys standard streams"); initmain(interp); if (!Py_NoSiteFlag) initsite(); } if (!PyErr_Occurred()) return tstate; handle_error: /* Oops, it didn't work. Undo it all. */ PyErr_PrintEx(0); PyThreadState_Clear(tstate); PyThreadState_Swap(save_tstate); PyThreadState_Delete(tstate); PyInterpreterState_Delete(interp); return NULL; }
//------------------------------------------------------------------------------------- PyObject* Space::__py_DelSpaceData(PyObject* self, PyObject* args) { SPACE_ID spaceID = 0; if(PyTuple_Size(args) != 2) { PyErr_Format(PyExc_AssertionError, "KBEngine::delSpaceData: (argssize != (spaceID, key)) is error!"); PyErr_PrintEx(0); return 0; } char* key = NULL; if(PyArg_ParseTuple(args, "Is", &spaceID, &key) == -1) { PyErr_Format(PyExc_AssertionError, "KBEngine::delSpaceData: args is error!"); PyErr_PrintEx(0); return 0; } if(key == NULL) { PyErr_Format(PyExc_AssertionError, "KBEngine::delSpaceData: key not is string!"); PyErr_PrintEx(0); return 0; } if(strlen(key) == 0) { PyErr_Format(PyExc_AssertionError, "KBEngine::delSpaceData: key is empty!"); PyErr_PrintEx(0); return 0; } Space* space = Spaces::findSpace(spaceID); if(space == NULL) { PyErr_Format(PyExc_AssertionError, "KBEngine::delSpaceData: (spaceID=%u) not found!", spaceID); PyErr_PrintEx(0); return 0; } if(!space->hasSpaceData(key)) { PyErr_Format(PyExc_AssertionError, "KBEngine::delSpaceData: (spaceID=%u, key=%s) not found!", spaceID, key); PyErr_PrintEx(0); return 0; } if(kbe_stricmp(key, "_mapping") == 0) { PyErr_Format(PyExc_AssertionError, "KBEngine::delSpaceData: key{_mapping} is protected!", spaceID); PyErr_PrintEx(0); return 0; } space->delSpaceData(key); S_Return; }
/* * External interface */ static void DoPythonCommand(exarg_T *eap, const char *cmd, typval_T *rettv) { #ifndef PY_CAN_RECURSE static int recursive = 0; #endif #if defined(MACOS) && !defined(MACOS_X_UNIX) GrafPtr oldPort; #endif #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) char *saved_locale; #endif #ifndef PY_CAN_RECURSE if (recursive) { EMSG(_("E659: Cannot invoke Python recursively")); return; } ++recursive; #endif #if defined(MACOS) && !defined(MACOS_X_UNIX) GetPort(&oldPort); /* Check if the Python library is available */ if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress) goto theend; #endif if (Python_Init()) goto theend; if (rettv == NULL) { RangeStart = eap->line1; RangeEnd = eap->line2; } else { RangeStart = (PyInt) curwin->w_cursor.lnum; RangeEnd = RangeStart; } Python_Release_Vim(); /* leave vim */ #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) /* Python only works properly when the LC_NUMERIC locale is "C". */ saved_locale = setlocale(LC_NUMERIC, NULL); if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0) saved_locale = NULL; else { /* Need to make a copy, value may change when setting new locale. */ saved_locale = (char *)vim_strsave((char_u *)saved_locale); (void)setlocale(LC_NUMERIC, "C"); } #endif Python_RestoreThread(); /* enter python */ if (rettv == NULL) PyRun_SimpleString((char *)(cmd)); else { PyObject *r; r = PyRun_String((char *)(cmd), Py_eval_input, globals, globals); if (r == NULL) { if (PyErr_Occurred() && !msg_silent) PyErr_PrintEx(0); EMSG(_("E858: Eval did not return a valid python object")); } else { if (ConvertFromPyObject(r, rettv) == -1) EMSG(_("E859: Failed to convert returned python object to vim value")); Py_DECREF(r); } PyErr_Clear(); } Python_SaveThread(); /* leave python */ #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) if (saved_locale != NULL) { (void)setlocale(LC_NUMERIC, saved_locale); vim_free(saved_locale); } #endif Python_Lock_Vim(); /* enter vim */ PythonIO_Flush(); #if defined(MACOS) && !defined(MACOS_X_UNIX) SetPort(oldPort); #endif theend: #ifndef PY_CAN_RECURSE --recursive; #endif return; }
//------------------------------------------------------------------------------------- PyObject* ClientEntityMethod::callmethod(PyObject* args, PyObject* kwds) { Entity* srcEntity = Cellapp::getSingleton().findEntity(srcEntityID_); if(srcEntity == NULL) { PyErr_Format(PyExc_AssertionError, "Entity::clientEntity(%s): srcEntityID(%d) not found!\n", methodDescription_->getName(), srcEntityID_); PyErr_PrintEx(0); return 0; } if(srcEntity->isDestroyed()) { PyErr_Format(PyExc_AssertionError, "Entity::clientEntity(%s): srcEntityID(%d) is destroyed!\n", methodDescription_->getName(), srcEntityID_); PyErr_PrintEx(0); return 0; } if(srcEntity->pWitness() == NULL) { PyErr_Format(PyExc_AssertionError, "%s::clientEntity(%s): no client, srcEntityID(%d).\n", srcEntity->getScriptName(), methodDescription_->getName(), srcEntity->getID()); PyErr_PrintEx(0); return 0; } EntityRef::AOI_ENTITIES::iterator iter = srcEntity->pWitness()->aoiEntities().begin(); Entity* e = NULL; for(; iter != srcEntity->pWitness()->aoiEntities().end(); iter++) { if((*iter)->id() == clientEntityID_ && ((*iter)->flags() & ENTITYREF_FLAG_ENTER_CLIENT_PENDING) <= 0) { e = (*iter)->pEntity(); break; } } if(e == NULL) { PyErr_Format(PyExc_AssertionError, "%s::clientEntity(%s): not found entity(%d), srcEntityID(%d).\n", srcEntity->getScriptName(), methodDescription_->getName(), clientEntityID_, srcEntity->getID()); PyErr_PrintEx(0); return 0; } MethodDescription* methodDescription = getDescription(); if(methodDescription->checkArgs(args)) { MemoryStream* mstream = MemoryStream::ObjPool().createObject(); methodDescription->addToStream(mstream, args); Mercury::Bundle* pForwardBundle = Mercury::Bundle::ObjPool().createObject(); Mercury::Bundle* pSendBundle = Mercury::Bundle::ObjPool().createObject(); srcEntity->pWitness()->addSmartAOIEntityMessageToBundle(pForwardBundle, ClientInterface::onRemoteMethodCall, ClientInterface::onRemoteOtherEntityMethodCall, clientEntityID_); if(mstream->wpos() > 0) (*pForwardBundle).append(mstream->data(), mstream->wpos()); if(Mercury::g_trace_packet > 0) { if(Mercury::g_trace_packet_use_logfile) DebugHelper::getSingleton().changeLogger("packetlogs"); DEBUG_MSG(boost::format("ClientEntityMethod::callmethod: pushUpdateData: ClientInterface::onRemoteOtherEntityMethodCall(%1%::%2%)\n") % srcEntity->getScriptName() % methodDescription->getName()); switch(Mercury::g_trace_packet) { case 1: mstream->hexlike(); break; case 2: mstream->textlike(); break; default: mstream->print_storage(); break; }; if(Mercury::g_trace_packet_use_logfile) DebugHelper::getSingleton().changeLogger(COMPONENT_NAME_EX(g_componentType)); } MERCURY_ENTITY_MESSAGE_FORWARD_CLIENT(srcEntity->getID(), (*pSendBundle), (*pForwardBundle)); srcEntity->pWitness()->sendToClient(ClientInterface::onRemoteOtherEntityMethodCall, pSendBundle); // 记录这个事件产生的数据量大小 g_publicClientEventHistoryStats.trackEvent(srcEntity->getScriptName(), (std::string(e->getScriptName()) + "." + methodDescription->getName()), pForwardBundle->currMsgLength(), "::"); MemoryStream::ObjPool().reclaimObject(mstream); Mercury::Bundle::ObjPool().reclaimObject(pForwardBundle); } S_Return; }
//------------------------------------------------------------------------------------- PyObject* Base::__py_pyDestroyEntity(PyObject* self, PyObject* args, PyObject * kwargs) { Base* pobj = static_cast<Base*>(self); if(pobj->initing()) { PyErr_Format(PyExc_AssertionError, "%s::destroy(): is initing, reject the request!\n", pobj->scriptName()); PyErr_PrintEx(0); return NULL; } static char * keywords[] = { const_cast<char *> ("deleteFromDB"), const_cast<char *> ("writeToDB"), NULL }; if(pobj->isDestroyed()) { PyErr_Format(PyExc_AssertionError, "%s::destroy: %d is destroyed!\n", pobj->scriptName(), pobj->id()); PyErr_PrintEx(0); return NULL; } if(pobj->creatingCell() || pobj->cellMailbox() != NULL) { PyErr_Format(PyExc_Exception, "%s::destroy: id:%i has cell! creatingCell=%s\n", pobj->scriptName(), pobj->id(), pobj->creatingCell() ? "true" : "false"); PyErr_PrintEx(0); return NULL; } PyObject* pyDeleteFromDB = NULL; PyObject* pyWriteToDB = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OO", keywords, &pyDeleteFromDB, &pyWriteToDB)) { PyErr_Format(PyExc_AssertionError, "%s::destroy: %d ParseTupleAndKeywords(deleteFromDB, &writeToDB) error!\n", pobj->scriptName(), pobj->id()); PyErr_PrintEx(0); return NULL; } bool deleteFromDB = (pyDeleteFromDB != NULL) ? (PyObject_IsTrue(pyDeleteFromDB) ? true : false) : false; bool writeToDB = (pyWriteToDB != NULL) ? (PyObject_IsTrue(pyWriteToDB) ? true : false) : pobj->hasDB(); if(deleteFromDB || writeToDB) { // 有可能已经请求了writeToDB但还未返回写入的dbid // 这种情况需要返回给用户一个错误, 用户可以继续尝试这个操作 if(pobj->hasDB() && pobj->dbid() == 0) { PyErr_Format(PyExc_AssertionError, "%s::destroy: id:%i has db, current dbid is 0. " "please wait for dbmgr to processing!\n", pobj->scriptName(), pobj->id()); PyErr_PrintEx(0); return NULL; } } pobj->onDestroyEntity(deleteFromDB, writeToDB); pobj->destroyEntity(); S_Return; }
PyObject* EntityApp<E>::__py_getWatcher(PyObject* self, PyObject* args) { int argCount = PyTuple_Size(args); if(argCount != 1) { PyErr_Format(PyExc_TypeError, "KBEngine::getWatcher(): args[strpath] is error!"); PyErr_PrintEx(0); return 0; } char* path; if(PyArg_ParseTuple(args, "s", &path) == -1) { PyErr_Format(PyExc_TypeError, "KBEngine::getWatcher(): args[strpath] is error!"); PyErr_PrintEx(0); return 0; } //DebugHelper::getSingleton().setScriptMsgType(type); KBEShared_ptr< WatcherObject > pWobj = WatcherPaths::root().getWatcher(path); if(pWobj.get() == NULL) { PyErr_Format(PyExc_TypeError, "KBEngine::getWatcher(): not found watcher[%s]!", path); PyErr_PrintEx(0); return 0; } WATCHER_VALUE_TYPE wtype = pWobj->getType(); PyObject* pyval = NULL; MemoryStream* stream = MemoryStream::ObjPool().createObject(); pWobj->addToStream(stream); WATCHER_ID id; (*stream) >> id; switch(wtype) { case WATCHER_VALUE_TYPE_UINT8: { uint8 v; (*stream) >> v; pyval = PyLong_FromUnsignedLong(v); } break; case WATCHER_VALUE_TYPE_UINT16: { uint16 v; (*stream) >> v; pyval = PyLong_FromUnsignedLong(v); } break; case WATCHER_VALUE_TYPE_UINT32: { uint32 v; (*stream) >> v; pyval = PyLong_FromUnsignedLong(v); } break; case WATCHER_VALUE_TYPE_UINT64: { uint64 v; (*stream) >> v; pyval = PyLong_FromUnsignedLongLong(v); } break; case WATCHER_VALUE_TYPE_INT8: { int8 v; (*stream) >> v; pyval = PyLong_FromLong(v); } break; case WATCHER_VALUE_TYPE_INT16: { int16 v; (*stream) >> v; pyval = PyLong_FromLong(v); } break; case WATCHER_VALUE_TYPE_INT32: { int32 v; (*stream) >> v; pyval = PyLong_FromLong(v); } break; case WATCHER_VALUE_TYPE_INT64: { int64 v; (*stream) >> v; pyval = PyLong_FromLongLong(v); } break; case WATCHER_VALUE_TYPE_FLOAT: { float v; (*stream) >> v; pyval = PyLong_FromDouble(v); } break; case WATCHER_VALUE_TYPE_DOUBLE: { double v; (*stream) >> v; pyval = PyLong_FromDouble(v); } break; case WATCHER_VALUE_TYPE_CHAR: case WATCHER_VALUE_TYPE_STRING: { std::string v; (*stream) >> v; pyval = PyUnicode_FromString(v.c_str()); } break; case WATCHER_VALUE_TYPE_BOOL: { bool v; (*stream) >> v; pyval = PyBool_FromLong(v); } break; case WATCHER_VALUE_TYPE_COMPONENT_TYPE: { COMPONENT_TYPE v; (*stream) >> v; pyval = PyBool_FromLong(v); } break; default: KBE_ASSERT(false && "no support!\n"); }; MemoryStream::ObjPool().reclaimObject(stream); return pyval; }
//------------------------------------------------------------------------------------- static PyObject* addWatcher(PyObject* self, PyObject* args) { if(PyTuple_Size(args) != 3) { PyErr_Format(PyExc_Exception, "KBEngine::addWatcher: args is error! " "arg(watcherName, deftype[UINT32|STRING...], pyCallable).\n"); PyErr_PrintEx(0); return NULL; } PyObject* pyName = NULL; PyObject* pyType = NULL; PyObject* pyObj = NULL; if(PyArg_ParseTuple(args, "O|O|O", &pyName, &pyType, &pyObj) == -1) { PyErr_Format(PyExc_Exception, "KBEngine::addWatcher: args is error! " "arg(watcherPath, deftype[UINT32|STRING...], pyCallable).\n"); PyErr_PrintEx(0); return NULL; } if(!PyUnicode_Check(pyName)) { PyErr_Format(PyExc_Exception, "KBEngine::addWatcher: args1 is error! " "arg=watcherPath\n"); PyErr_PrintEx(0); return NULL; } if(!PyUnicode_Check(pyType)) { PyErr_Format(PyExc_Exception, "KBEngine::addWatcher: args2 is error! " "arg=deftype[UINT32|STRING...]\n"); PyErr_PrintEx(0); return NULL; } wchar_t* wstr = PyUnicode_AsWideCharString(pyName, NULL); char* pwatchername = strutil::wchar2char(wstr); std::string watchername = pwatchername; PyMem_Free(wstr); free(pwatchername); wstr = PyUnicode_AsWideCharString(pyType, NULL); pwatchername = strutil::wchar2char(wstr); std::string type = pwatchername; PyMem_Free(wstr); free(pwatchername); PyObject* pyObj1 = NULL; if(!PyCallable_Check(pyObj)) { PyErr_Format(PyExc_Exception, "Baseapp::createBase: args3 is error! " "arg=pyCallable.\n"); PyErr_PrintEx(0); return NULL; } pyObj1 = PyObject_CallFunction(pyObj, const_cast<char*>("")); if(!pyObj1) { PyErr_Clear(); PyErr_Format(PyExc_Exception, "Baseapp::createBase: return is error for args3! " "arg=pyCallable.\n"); PyErr_PrintEx(0); return NULL; } Py_INCREF(pyObj); if(strcmp("UINT8", type.c_str()) == 0) { _addWatcher<uint8>(pwatchername, pyObj); } else if(strcmp("UINT16", type.c_str()) == 0) { _addWatcher<uint16>(pwatchername, pyObj); } else if(strcmp("UINT32", type.c_str()) == 0) { _addWatcher<uint32>(pwatchername, pyObj); } else if(strcmp("UINT64", type.c_str()) == 0) { _addWatcher<uint64>(pwatchername, pyObj); } else if(strcmp("INT8", type.c_str()) == 0) { _addWatcher<int8>(pwatchername, pyObj); } else if(strcmp("INT16", type.c_str()) == 0) { _addWatcher<int16>(pwatchername, pyObj); } else if(strcmp("INT32", type.c_str()) == 0) { _addWatcher<int32>(pwatchername, pyObj); } else if(strcmp("INT64", type.c_str()) == 0) { _addWatcher<int64>(pwatchername, pyObj); } else if(strcmp("FLOAT", type.c_str()) == 0) { _addWatcher<float>(pwatchername, pyObj); } else if(strcmp("DOUBLE", type.c_str()) == 0) { _addWatcher<double>(pwatchername, pyObj); } else if(strcmp("BOOL", type.c_str()) == 0) { _addWatcher<uint8>(pwatchername, pyObj); } else if(strcmp("STRING", type.c_str()) == 0) { _addWatcher<std::string>(pwatchername, pyObj); } Py_DECREF(pyObj1); S_Return; }
//------------------------------------------------------------------------------------- int Sequence::seq_ass_slice(PyObject* self, Py_ssize_t index1, Py_ssize_t index2, PyObject* oterSeq) { Sequence* seq = static_cast<Sequence*>(self); std::vector<PyObject*>& values = seq->getValues(); // 是否是删除元素 if (!oterSeq) { if (index1 < index2) values.erase(values.begin() + index1, values.begin() + index2); return 0; } // oterSeq必须是一个 sequence if (!PySequence_Check(oterSeq)) { PyErr_Format(PyExc_TypeError, "Sequence slices can only be assigned to a sequence"); PyErr_PrintEx(0); return -1; } if (oterSeq == seq) { PyErr_Format(PyExc_TypeError, "Sequence does not support assignment of itself to a slice of itself"); PyErr_PrintEx(0); return -1; } int sz = values.size(); int osz = PySequence_Size(oterSeq); // 保证index不会越界 if (index1 > sz) index1 = sz; if (index1 < 0) index1 = 0; if (index2 > sz) index2 = sz; if (index2 < 0) index2 = 0; // 检查一下 看看有无错误类别 for (int i = 0; i < osz; ++i) { PyObject* pyVal = PySequence_GetItem(oterSeq, i); bool ok = seq->isSameItemType(pyVal); Py_DECREF(pyVal); if (!ok) { PyErr_Format(PyExc_TypeError, "Array elements must be set to type %s (setting slice %d-%d)", "ss", index1, index2); PyErr_PrintEx(0); return -1; } } if (index1 < index2) values.erase(values.begin() + index1, values.begin() + index2); // 先让vector分配好内存 values.insert(values.begin() + index1, osz, (PyObject*)NULL); for(int i = 0; i < osz; ++i) { PyObject* pyTemp = PySequence_GetItem(oterSeq, i); if(pyTemp == NULL) { PyErr_Format(PyExc_TypeError, "Sequence::seq_ass_slice::PySequence_GetItem %d is NULL.", i); PyErr_PrintEx(0); } values[index1 + i] = seq->createNewItemFromObj(pyTemp); Py_DECREF(pyTemp); } return 0; }
static void pyt_exec_str(RESULT * result, const char *module, const char *function, int argc, const char *argv[]) { PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; const char *rv = NULL; int i; pName = PyString_FromString(module); /* Error checking of pName left out */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pDict = PyModule_GetDict(pModule); /* pDict is a borrowed reference */ pFunc = PyDict_GetItemString(pDict, function); /* pFun: Borrowed reference */ if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(argc); for (i = 0; i < argc; ++i) { pValue = PyString_FromString(argv[i]); if (!pValue) { Py_DECREF(pArgs); Py_DECREF(pModule); error("Cannot convert argument \"%s\" to python format", argv[i]); SetResult(&result, R_STRING, ""); return; } /* pValue reference stolen here: */ PyTuple_SetItem(pArgs, i, pValue); } pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { rv = PyString_AsString(pValue); SetResult(&result, R_STRING, rv); Py_DECREF(pValue); /* rv is now a 'dangling reference' */ return; } else { Py_DECREF(pModule); error("Python call failed (\"%s.%s\")", module, function); /* print traceback on stderr */ PyErr_PrintEx(0); SetResult(&result, R_STRING, ""); return; } /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */ } else { error("Can not find python function \"%s.%s\"", module, function); } Py_DECREF(pModule); } else { error("Failed to load python module \"%s\"", module); /* print traceback on stderr */ PyErr_PrintEx(0); } SetResult(&result, R_STRING, ""); return; }
static void t_bootstrap(void* rawself) { // printf("Hello, iam Threadi :)\n"); PyObject * callback; PyThreadState *tstate; PyObject* args = NULL; char buf; tstate = PyThreadState_New(interp); PyEval_AcquireThread(tstate); int retval, i, fd_glow; PyObject *res = NULL; while (global_nfds > 0) { Py_BEGIN_ALLOW_THREADS retval = poll(global_pfd, global_nfds, 20); // timeout to check if cb still set Py_END_ALLOW_THREADS if (retval == 0) continue; // poll timed out if (retval < 0) { PyErr_SetFromErrno(PyExc_IOError); break; } // printf("Threadi: nfds: %i\n", global_nfds); for (i = 0; i < global_nfds; i++) { if (global_pfd[i].revents != 0) { // fd_glow = global_pfd[i].fd; lseek(global_pfd[i].fd, 0, SEEK_SET); read(global_pfd[i].fd, &buf, 1 ); res = NULL; args = Py_BuildValue("(i)", buf - 48); // we got ASCII '0' callback = get_poll_cb(global_pfd[i].fd)->callback; // printf("Threadi: fd: %i, revents: %i\n", global_pfd[i].fd, global_pfd[i].revents); PyGILState_STATE s = PyGILState_Ensure(); res = PyObject_CallObject(callback, args); PyGILState_Release(s); // printf("Threadi :5\n"); Py_DECREF(args); if (res == NULL) { Py_XDECREF(res); break; /* Pass error back */ } /* Here maybe use res maybe exit loop at some defined return value (i.e. res == -1) */ Py_DECREF(res); } } } if (PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_SystemExit)) PyErr_Clear(); else { PySys_WriteStderr("Unhandled exception in poll thread:\n"); PyErr_PrintEx(0); } } PyThread_release_lock(lock); // printf("terminating poll thread\n"); // PyEval_ReleaseThread(tstate); lock = NULL; PyThreadState_Clear(tstate); PyThreadState_DeleteCurrent(); PyThread_exit_thread(); }
int initializing_khan(char * mnt_dir) { //log_msg("In initialize\n"); unmounting(mnt_dir); //Opening root directory and creating if not present //cout<<"khan_root[0] is "<<servers.at(0)<<endl; if(NULL == opendir(servers.at(0).c_str())) { sprintf(msg,"Error msg on opening directory : %s\n",strerror(errno)); //log_msg(msg); //log_msg("Root directory might not exist..Creating\n"); string command = "mkdir " + servers.at(0); if (system(command.c_str()) < 0) { log_msg("Unable to create storage directory...Aborting\n"); exit(1); } } else { fprintf(stderr, "directory opened successfully\n"); } init_database(); //check if we've loaded metadata before string output=database_getval("setup","value"); if(output.compare("true")==0){ log_msg("Database was previously initialized."); tot_time+=(stop.tv_sec-start.tv_sec)+(stop.tv_nsec-start.tv_nsec)/BILLION; return 0; //setup has happened before } //if we have not setup, do so now //log_msg("it hasnt happened, setvalue then setup"); database_setval("setup","value","true"); //load metadata associatons for(int i=0; i<servers.size(); i++){ process_transducers(servers.at(i)); } //load metadata for each file on each server string types=database_getval("allfiles","types"); //cout << "================= types to look for ="<<types<<endl; for(int i=0; i<servers.size(); i++) { if(servers.at(i) == "cloud") { PyObject* myFunction = PyObject_GetAttrString(cloud_interface,(char*)"get_all_titles"); PyObject* myResult = PyObject_CallObject(myFunction, NULL); if(myResult==NULL) { PyErr_PrintEx(0); continue; } int n = PyList_Size(myResult); //cout << "SIZE = " << n << endl << flush; for(int j = 0; j<n; j++) { PyObject* title = PyList_GetItem(myResult, j); char* temp = PyString_AsString(title); if(temp==NULL) { PyErr_PrintEx(0); continue; } string filename = temp; //cout << "Checking " << filename << " ... " << endl << flush; if(database_getval("name",filename)=="null") { string fileid = database_setval("null","name",filename); string ext = strrchr(filename.c_str(),'.')+1; database_setval(fileid,"ext",ext); database_setval(fileid,"server",servers.at(i)); database_setval(fileid,"location",server_ids.at(i)); string attrs=database_getval(ext,"attrs"); string token=""; stringstream ss2(attrs.c_str()); PyObject* myFunction = PyObject_GetAttrString(cloud_interface,(char*)"get_metadata"); while(getline(ss2,token,':')){ if(strcmp(token.c_str(),"null")!=0){ //cout << "========= looking at attr = " << token << endl << flush; PyObject* arglist = PyTuple_New(2); PyTuple_SetItem(arglist, 0, PyString_FromString(filename.c_str())); PyTuple_SetItem(arglist, 1, PyString_FromString(token.c_str())); PyObject* myResult = PyObject_CallObject(myFunction, arglist); //cout << myResult << endl << flush; if(myResult==NULL) { PyErr_PrintEx(0); continue; } char* msg = PyString_AsString(myResult); if(!msg) { PyErr_PrintEx(0); continue; } string val = msg; Py_DECREF(arglist); Py_DECREF(myResult); //cout << "========= got val = " << val << endl << flush; if(val!="na") { database_setval(fileid,token,val); } } } } else { string fileid = database_getval("name", filename); database_setval(fileid,"server",servers.at(i)); database_setval(fileid,"location",server_ids.at(i)); } } } else { glob_t files; glob((servers.at(i)+"/*.*").c_str(),0,NULL,&files); for(int j=0; j<files.gl_pathc; j++) {//for each file string file = files.gl_pathv[j]; string ext = strrchr(file.c_str(),'.')+1; string filename=strrchr(file.c_str(),'/')+1; if(database_getval("name", filename) == "null") { string fileid = database_setval("null","name",filename); database_setval(fileid,"ext",ext); database_setval(fileid,"server",servers.at(i)); database_setval(fileid,"location",server_ids.at(i)); for(int k=0; k<server_ids.size(); k++) { database_setval(fileid, server_ids.at(k), "0"); } if(j%10==0) { cout << "processed file " << j << "\n"; } process_file(servers.at(i), fileid); } else { string fileid = database_getval("name",filename); database_setval(fileid,"server",servers.at(i)); database_setval(fileid,"location",server_ids.at(i)); } } } } //log_msg("At the end of initialize\n"); return 0; }
PyObject* EntityApp<E>::__py_listPathRes(PyObject* self, PyObject* args) { int argCount = PyTuple_Size(args); if(argCount < 1 || argCount > 2) { PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!"); PyErr_PrintEx(0); return 0; } std::wstring wExtendName = L"*"; PyObject* pathobj = NULL; PyObject* path_argsobj = NULL; if(argCount == 1) { if(PyArg_ParseTuple(args, "O", &pathobj) == -1) { PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is error!"); PyErr_PrintEx(0); return 0; } } else { if(PyArg_ParseTuple(args, "O|O", &pathobj, &path_argsobj) == -1) { PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!"); PyErr_PrintEx(0); return 0; } if(PyUnicode_Check(path_argsobj)) { wchar_t* fargs = NULL; fargs = PyUnicode_AsWideCharString(path_argsobj, NULL); wExtendName = fargs; PyMem_Free(fargs); } else { if(PySequence_Check(path_argsobj)) { wExtendName = L""; Py_ssize_t size = PySequence_Size(path_argsobj); for(int i=0; i<size; i++) { PyObject* pyobj = PySequence_GetItem(path_argsobj, i); if(!PyUnicode_Check(pyobj)) { PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!"); PyErr_PrintEx(0); return 0; } wchar_t* wtemp = NULL; wtemp = PyUnicode_AsWideCharString(pyobj, NULL); wExtendName += wtemp; wExtendName += L"|"; PyMem_Free(wtemp); } } else { PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[pathargs] is error!"); PyErr_PrintEx(0); return 0; } } } if(!PyUnicode_Check(pathobj)) { PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is error!"); PyErr_PrintEx(0); return 0; } if(wExtendName.size() == 0) { PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[pathargs] is NULL!"); PyErr_PrintEx(0); return 0; } if(wExtendName[0] == '.') wExtendName.erase(wExtendName.begin()); if(wExtendName.size() == 0) wExtendName = L"*"; wchar_t* respath = PyUnicode_AsWideCharString(pathobj, NULL); if(respath == NULL) { PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is NULL!"); PyErr_PrintEx(0); return 0; } char* cpath = strutil::wchar2char(respath); std::string foundPath = Resmgr::getSingleton().matchPath(cpath); free(cpath); PyMem_Free(respath); respath = strutil::char2wchar(foundPath.c_str()); std::vector<std::wstring> results; Resmgr::getSingleton().listPathRes(respath, wExtendName, results); PyObject* pyresults = PyTuple_New(results.size()); std::vector<std::wstring>::iterator iter = results.begin(); int i = 0; for(; iter != results.end(); iter++) { PyTuple_SET_ITEM(pyresults, i++, PyUnicode_FromWideChar((*iter).c_str(), (*iter).size())); } free(respath); return pyresults; }