environment.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jlib.hpp"
  14. #include "environment.hpp"
  15. #include "jptree.hpp"
  16. #include "jexcept.hpp"
  17. #include "jiter.ipp"
  18. #include "jmisc.hpp"
  19. #include "jencrypt.hpp"
  20. #include "mpbase.hpp"
  21. #include "daclient.hpp"
  22. #include "dadfs.hpp"
  23. #include "dafdesc.hpp"
  24. #include "dasds.hpp"
  25. #include "dalienv.hpp"
  26. #define SDS_LOCK_TIMEOUT 30000
  27. #define DEFAULT_DROPZONE_INDEX 1
  28. #define DROPZONE_BY_MACHINE_SUFFIX "-dropzoneByMachine-"
  29. #define DROPZONE_SUFFIX "dropzone-"
  30. #define MACHINE_PREFIX "machine-"
  31. #define NUMBER_OF_DROPZONES_SUFFIX "-numberOfDropZones"
  32. static int environmentTraceLevel = 1;
  33. static Owned <IConstEnvironment> cache;
  34. class CLocalEnvironment;
  35. class CConstMachineInfoIterator : public CSimpleInterfaceOf<IConstMachineInfoIterator>
  36. {
  37. public:
  38. CConstMachineInfoIterator();
  39. virtual bool first() override;
  40. virtual bool next() override;
  41. virtual bool isValid() override;
  42. virtual IConstMachineInfo & query() override;
  43. virtual unsigned count() const override;
  44. protected:
  45. IConstMachineInfo * curr = nullptr;
  46. Owned<CLocalEnvironment> constEnv;
  47. unsigned index = 1;
  48. unsigned maxIndex = 0;
  49. };
  50. class CConstDropZoneInfoIterator : public CSimpleInterfaceOf<IConstDropZoneInfoIterator>
  51. {
  52. public:
  53. CConstDropZoneInfoIterator();
  54. virtual bool first() override;
  55. virtual bool next() override;
  56. virtual bool isValid() override;
  57. virtual IConstDropZoneInfo & query() override;
  58. virtual unsigned count() const override;
  59. protected:
  60. IConstDropZoneInfo * curr = nullptr;
  61. Owned<CLocalEnvironment> constEnv;
  62. unsigned index = 1;
  63. unsigned maxIndex = 0;
  64. };
  65. class CConstDropZoneIteratorByComputer : public CSimpleInterfaceOf<IConstDropZoneInfoIterator>
  66. {
  67. public:
  68. CConstDropZoneIteratorByComputer(const char * computer);
  69. virtual bool first() override;
  70. virtual bool next() override;
  71. virtual bool isValid() override;
  72. virtual IConstDropZoneInfo & query() override;
  73. virtual unsigned count() const override;
  74. protected:
  75. StringBuffer computerName;
  76. IConstDropZoneInfo * curr = nullptr;
  77. Owned<CLocalEnvironment> constEnv;
  78. unsigned index = 1;
  79. unsigned maxIndex = 0;
  80. };
  81. //==========================================================================================
  82. class CConstInstanceInfo;
  83. class CLocalEnvironment : public CInterface, implements IConstEnvironment
  84. {
  85. private:
  86. // NOTE - order is important - we need to construct before p and (especially) destruct after p
  87. Owned<IRemoteConnection> conn;
  88. Owned<IPropertyTree> p;
  89. mutable MapStringToMyClass<IConstEnvBase> cache;
  90. mutable Mutex safeCache;
  91. mutable bool dropZoneCacheBuilt;
  92. mutable bool machineCacheBuilt;
  93. StringBuffer xPath;
  94. Owned<IPropertyTree> numOfDropzonesByComputer;
  95. mutable unsigned numOfMachines;
  96. mutable unsigned numOfDropZones;
  97. IConstEnvBase * getCache(const char *path) const;
  98. void setCache(const char *path, IConstEnvBase *value) const;
  99. void buildMachineCache() const;
  100. void buildDropZoneCache() const;
  101. void init();
  102. public:
  103. IMPLEMENT_IINTERFACE;
  104. CLocalEnvironment(IRemoteConnection *_conn, IPropertyTree *x=nullptr, const char* path="Environment");
  105. CLocalEnvironment(const char* path="config.xml");
  106. virtual ~CLocalEnvironment();
  107. virtual IStringVal & getName(IStringVal & str) const;
  108. virtual IStringVal & getXML(IStringVal & str) const;
  109. virtual IPropertyTree & getPTree() const;
  110. virtual IEnvironment& lock() const;
  111. virtual IConstDomainInfo * getDomain(const char * name) const;
  112. virtual IConstMachineInfo * getMachine(const char * name) const;
  113. virtual IConstMachineInfo * getMachineByAddress(const char * machineIp) const;
  114. virtual IConstMachineInfo * getMachineForLocalHost() const;
  115. virtual IConstDropZoneInfo * getDropZone(const char * name) const;
  116. virtual IConstDropZoneInfo * getDropZoneByComputer(const char * computer) const;
  117. virtual IConstInstanceInfo * getInstance(const char * type, const char * version, const char *domain) const;
  118. virtual CConstInstanceInfo * getInstanceByIP(const char *type, const char *version, IpAddress &ip) const;
  119. virtual IConstComputerTypeInfo * getComputerType(const char * name) const;
  120. virtual bool getRunInfo(IStringVal & path, IStringVal & dir, const char *type, const char *version, const char *machineaddr, const char *defprogname) const;
  121. virtual void preload();
  122. virtual IRemoteConnection* getConnection() const { return conn.getLink(); }
  123. void setXML(const char * logicalName);
  124. const char* getPath() const { return xPath.str(); }
  125. void unlockRemote();
  126. virtual bool isConstEnvironment() const { return true; }
  127. virtual void clearCache();
  128. virtual IConstMachineInfoIterator * getMachineIterator() const;
  129. virtual IConstDropZoneInfo * getDropZoneByComputer(const char * computer, const char * dzname) const;
  130. virtual IConstDropZoneInfoIterator * getDropZoneIteratorByComputer(const char * computer) const;
  131. virtual IConstDropZoneInfo * getDropZoneByAddressPath(const char * netaddress, const char *targetPath) const;
  132. virtual IConstDropZoneInfoIterator * getDropZoneIterator() const;
  133. unsigned getNumberOfMachines() const { buildMachineCache(); return numOfMachines; }
  134. IConstMachineInfo * getMachineByIndex(unsigned index) const;
  135. unsigned getNumberOfDropZonesByComputer(const char * computer) const
  136. {
  137. buildDropZoneCache();
  138. StringBuffer xpath("@");
  139. xpath.append(computer).append(NUMBER_OF_DROPZONES_SUFFIX);
  140. unsigned numOfDropZoneByComputer = numOfDropzonesByComputer->getPropInt(xpath, -1);
  141. return (numOfDropZoneByComputer != -1 ? numOfDropZoneByComputer : 0);
  142. }
  143. IConstDropZoneInfo * getDropZoneByComputerByIndex(const char * computer, unsigned index) const;
  144. unsigned getNumberOfDropZones() const { buildDropZoneCache(); return numOfDropZones; }
  145. IConstDropZoneInfo * getDropZoneByIndex(unsigned index) const;
  146. };
  147. class CLockedEnvironment : public CInterface, implements IEnvironment
  148. {
  149. public:
  150. //note that order of construction/destruction is important
  151. Owned<CLocalEnvironment> c;
  152. Owned<CLocalEnvironment> env;
  153. Owned<CLocalEnvironment> constEnv;
  154. IMPLEMENT_IINTERFACE;
  155. CLockedEnvironment(CLocalEnvironment *_c)
  156. {
  157. Owned<IRemoteConnection> connection = _c->getConnection();
  158. if (connection)
  159. {
  160. constEnv.set(_c); //save original constant environment
  161. //we only wish to allow one party to allow updating the environment.
  162. //
  163. //create a new /NewEnvironment subtree, locked for read/write access for self and entire subtree; delete on disconnect
  164. //
  165. StringBuffer newName("/New");
  166. newName.append(constEnv->getPath());
  167. const unsigned int mode = RTM_CREATE | RTM_CREATE_QUERY | RTM_LOCK_READ | RTM_LOCK_WRITE |
  168. RTM_LOCK_SUB | RTM_DELETE_ON_DISCONNECT;
  169. Owned<IRemoteConnection> conn = querySDS().connect(newName.str(), myProcessSession(), mode, SDS_LOCK_TIMEOUT);
  170. if (conn == nullptr)
  171. {
  172. if (environmentTraceLevel > 0)
  173. PrintLog("Failed to create locked environment %s", newName.str());
  174. throw MakeStringException(-1, "Failed to get a lock on environment /%s", newName.str());
  175. }
  176. //save the locked environment
  177. env.setown(new CLocalEnvironment(conn, nullptr, newName.str()));
  178. //get a lock on the const environment
  179. const unsigned int mode2 = RTM_CREATE_QUERY | RTM_LOCK_READ | RTM_LOCK_WRITE | RTM_LOCK_SUB;
  180. Owned<IRemoteConnection> conn2 = querySDS().connect(constEnv->getPath(), myProcessSession(), mode2, SDS_LOCK_TIMEOUT);
  181. if (conn2 == nullptr)
  182. {
  183. if (environmentTraceLevel > 0)
  184. PrintLog("Failed to lock environment %s", constEnv->getPath());
  185. throw MakeStringException(-1, "Failed to get a lock on environment /%s", constEnv->getPath());
  186. }
  187. //copy const environment to our member environment
  188. Owned<IPropertyTree> pSrc = conn2->getRoot();
  189. c.setown( new CLocalEnvironment(nullptr, createPTreeFromIPT(pSrc)));
  190. conn2->rollback();
  191. }
  192. else
  193. {
  194. c.set(_c);
  195. }
  196. }
  197. virtual ~CLockedEnvironment()
  198. {
  199. }
  200. virtual IStringVal & getName(IStringVal & str) const
  201. { return c->getName(str); }
  202. virtual IStringVal & getXML(IStringVal & str) const
  203. { return c->getXML(str); }
  204. virtual IPropertyTree & getPTree() const
  205. { return c->getPTree(); }
  206. virtual IConstDomainInfo * getDomain(const char * name) const
  207. { return c->getDomain(name); }
  208. virtual IConstMachineInfo * getMachine(const char * name) const
  209. { return c->getMachine(name); }
  210. virtual IConstMachineInfo * getMachineByAddress(const char * machineIp) const
  211. { return c->getMachineByAddress(machineIp); }
  212. virtual IConstMachineInfo * getMachineForLocalHost() const
  213. { return c->getMachineForLocalHost(); }
  214. virtual IConstDropZoneInfo * getDropZone(const char * name) const
  215. { return c->getDropZone(name); }
  216. virtual IConstDropZoneInfo * getDropZoneByComputer(const char * computer) const
  217. { return c->getDropZoneByComputer(computer); }
  218. virtual IConstInstanceInfo * getInstance(const char *type, const char *version, const char *domain) const
  219. { return c->getInstance(type, version, domain); }
  220. virtual bool getRunInfo(IStringVal & path, IStringVal & dir, const char *type, const char *version, const char *machineaddr,const char *defprogname) const
  221. { return c->getRunInfo(path, dir, type, version, machineaddr, defprogname); }
  222. virtual IConstComputerTypeInfo * getComputerType(const char * name) const
  223. { return c->getComputerType(name); }
  224. virtual IEnvironment & lock() const
  225. { ((CInterface*)this)->Link(); return *(IEnvironment*)this; }
  226. virtual void commit();
  227. virtual void rollback();
  228. virtual void setXML(const char * pstr)
  229. { c->setXML(pstr); }
  230. virtual void preload()
  231. { c->preload(); }
  232. virtual bool isConstEnvironment() const { return false; }
  233. virtual void clearCache() { c->clearCache(); }
  234. virtual IConstMachineInfoIterator * getMachineIterator() const
  235. { return c->getMachineIterator(); }
  236. virtual IConstDropZoneInfo * getDropZoneByComputer(const char * computer, const char * dzname) const
  237. { return c->getDropZoneByComputer(computer, dzname); }
  238. virtual IConstDropZoneInfoIterator * getDropZoneIteratorByComputer(const char * computer) const
  239. { return c->getDropZoneIteratorByComputer(computer); }
  240. virtual IConstDropZoneInfo * getDropZoneByAddressPath(const char * netaddress, const char *targetPath) const
  241. { return c->getDropZoneByAddressPath(netaddress, targetPath); }
  242. virtual IConstDropZoneInfoIterator * getDropZoneIterator() const
  243. { return c->getDropZoneIterator(); }
  244. };
  245. void CLockedEnvironment::commit()
  246. {
  247. if (constEnv)
  248. {
  249. //get a lock on const environment momentarily
  250. const unsigned int mode2 = RTM_CREATE_QUERY | RTM_LOCK_READ | RTM_LOCK_WRITE | RTM_LOCK_SUB;
  251. Owned<IRemoteConnection> conn2 = querySDS().connect(constEnv->getPath(), myProcessSession(), mode2, SDS_LOCK_TIMEOUT);
  252. if (conn2 == nullptr)
  253. {
  254. if (environmentTraceLevel > 0)
  255. PrintLog("Failed to lock environment %s", constEnv->getPath());
  256. throw MakeStringException(-1, "Failed to get a lock on environment /%s", constEnv->getPath());
  257. }
  258. //copy locked environment to const environment
  259. Owned<IPropertyTree> pSrc = &getPTree();
  260. Owned<IPropertyTree> pDst = conn2->queryRoot()->getBranch(nullptr);
  261. // JCS - I think it could (and would be more efficient if it had kept the original read lock connection to Env
  262. // - instead of using NewEnv as lock point, still work on copy, then changeMode of original connect
  263. // - as opposed to current scheme, where it recoonects in write mode and has to lazy fetch original env to update.
  264. // ensures pDst is equal to pSrc, whilst minimizing changes to pDst
  265. try { synchronizePTree(pDst, pSrc); }
  266. catch (IException *) { conn2->rollback(); throw; }
  267. conn2->commit();
  268. }
  269. else
  270. {
  271. Owned<IRemoteConnection> conn = c->getConnection();
  272. conn->commit();
  273. }
  274. }
  275. void CLockedEnvironment::rollback()
  276. {
  277. if (constEnv)
  278. {
  279. //get a lock on const environment momentarily
  280. const unsigned int mode2 = RTM_CREATE_QUERY | RTM_LOCK_READ | RTM_LOCK_WRITE | RTM_LOCK_SUB;
  281. Owned<IRemoteConnection> conn2 = querySDS().connect(constEnv->getPath(), myProcessSession(), mode2, SDS_LOCK_TIMEOUT);
  282. if (conn2 == nullptr)
  283. {
  284. if (environmentTraceLevel > 0)
  285. PrintLog("Failed to lock environment %s", constEnv->getPath());
  286. throw MakeStringException(-1, "Failed to get a lock on environment /%s", constEnv->getPath());
  287. }
  288. //copy const environment to locked environment (as it stands now) again losing any changes we made
  289. Owned<IPropertyTree> pSrc = conn2->getRoot();
  290. Owned<IPropertyTree> pDst = &getPTree();
  291. pDst->removeTree( pDst->queryPropTree("Hardware") );
  292. pDst->removeTree( pDst->queryPropTree("Software") );
  293. pDst->removeTree( pDst->queryPropTree("Programs") );
  294. pDst->removeTree( pDst->queryPropTree("Data") );
  295. mergePTree(pDst, pSrc);
  296. conn2->rollback();
  297. }
  298. else
  299. {
  300. Owned<IRemoteConnection> conn = c->getConnection();
  301. conn->rollback();
  302. }
  303. }
  304. //==========================================================================================
  305. // the following class implements notification handler for subscription to dali for environment
  306. // updates by other clients and is used by environment factory below. This also serves as
  307. // a sample self-contained implementation that can be easily tailored for other purposes.
  308. //==========================================================================================
  309. class CSdsSubscription : public CInterface, implements ISDSSubscription
  310. {
  311. public:
  312. CSdsSubscription()
  313. {
  314. m_constEnvUpdated = false;
  315. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory();
  316. sub_id = envFactory->subscribe(this);
  317. }
  318. virtual ~CSdsSubscription()
  319. {
  320. /* note that ideally, we would make this class automatically
  321. unsubscribe in this destructor. However, underlying dali client
  322. layer (CDaliSubscriptionManagerStub) links to this object and so
  323. object would not get destroyed just by an application releasing it.
  324. The application either needs to explicitly unsubscribe or close
  325. the environment which unsubscribes during close down. */
  326. }
  327. void unsubscribe()
  328. {
  329. synchronized block(m_mutexEnv);
  330. if (sub_id)
  331. {
  332. Owned<IEnvironmentFactory> m_envFactory = getEnvironmentFactory();
  333. m_envFactory->unsubscribe(sub_id);
  334. sub_id = 0;
  335. }
  336. }
  337. IMPLEMENT_IINTERFACE;
  338. //another client (like configenv) may have updated the environment and we got notified
  339. //(thanks to our subscription) but don't just reload it yet since this notification is sent on
  340. //another thread asynchronously and we may be actively working with the old environment. Just
  341. //invoke handleEnvironmentChange() when we are ready to invalidate cache in environment factory.
  342. //
  343. void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen=0, const void *valueData=nullptr)
  344. {
  345. DBGLOG("Environment was updated by another client of Dali server. Invalidating cache.\n");
  346. synchronized block(m_mutexEnv);
  347. m_constEnvUpdated = true;
  348. }
  349. void handleEnvironmentChange()
  350. {
  351. synchronized block(m_mutexEnv);
  352. if (m_constEnvUpdated)
  353. {
  354. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory();
  355. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  356. constEnv->clearCache();
  357. m_constEnvUpdated = false;
  358. }
  359. }
  360. private:
  361. SubscriptionId sub_id;
  362. Mutex m_mutexEnv;
  363. bool m_constEnvUpdated;
  364. };
  365. //==========================================================================================
  366. class CEnvironmentFactory : public CInterface,
  367. implements IEnvironmentFactory, implements IDaliClientShutdown
  368. {
  369. public:
  370. IMPLEMENT_IINTERFACE;
  371. typedef ArrayOf<SubscriptionId> SubscriptionIDs;
  372. SubscriptionIDs subIDs;
  373. Mutex mutex;
  374. Owned<CSdsSubscription> subscription;
  375. CEnvironmentFactory()
  376. {
  377. }
  378. virtual void clientShutdown();
  379. virtual ~CEnvironmentFactory()
  380. {
  381. close(); //just in case it was not explicitly closed
  382. }
  383. virtual IConstEnvironment* openEnvironment()
  384. {
  385. synchronized procedure(mutex);
  386. if (!cache)
  387. {
  388. Owned<IRemoteConnection> conn = querySDS().connect("/Environment", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  389. if (conn)
  390. cache.setown(new CLocalEnvironment(conn));
  391. }
  392. return cache.getLink();
  393. }
  394. virtual IEnvironment* updateEnvironment()
  395. {
  396. Owned<IConstEnvironment> pConstEnv = openEnvironment();
  397. synchronized procedure(mutex);
  398. return &pConstEnv->lock();
  399. }
  400. virtual IEnvironment * loadLocalEnvironmentFile(const char * filename)
  401. {
  402. Owned<IPropertyTree> ptree = createPTreeFromXMLFile(filename);
  403. Owned<CLocalEnvironment> pLocalEnv = new CLocalEnvironment(nullptr, ptree);
  404. return new CLockedEnvironment(pLocalEnv);
  405. }
  406. virtual IEnvironment * loadLocalEnvironment(const char * xml)
  407. {
  408. Owned<IPropertyTree> ptree = createPTreeFromXMLString(xml);
  409. Owned<CLocalEnvironment> pLocalEnv = new CLocalEnvironment(nullptr, ptree);
  410. return new CLockedEnvironment(pLocalEnv);
  411. }
  412. void close()
  413. {
  414. SubscriptionIDs copySubIDs;
  415. {
  416. synchronized procedure(mutex);
  417. cache.clear();
  418. //save the active subscriptions in another array
  419. //so they can be unsubscribed without causing deadlock
  420. // since ~CSdsSubscription() would ask us to unsubscribe the
  421. //same requiring a mutex lock (copy is a little price for this
  422. //normally small/empty array).
  423. //
  424. ForEachItemIn(i, subIDs)
  425. copySubIDs.append(subIDs.item(i));
  426. subIDs.kill();
  427. }
  428. //now unsubscribe all outstanding subscriptions
  429. //
  430. subscription.clear();
  431. ForEachItemIn(i, copySubIDs)
  432. querySDS().unsubscribe( copySubIDs.item(i) );
  433. }
  434. virtual SubscriptionId subscribe(ISDSSubscription* pSubHandler)
  435. {
  436. SubscriptionId sub_id = querySDS().subscribe("/Environment", *pSubHandler);
  437. synchronized procedure(mutex);
  438. subIDs.append(sub_id);
  439. return sub_id;
  440. }
  441. virtual void unsubscribe(SubscriptionId sub_id)
  442. {
  443. synchronized procedure(mutex);
  444. aindex_t i = subIDs.find(sub_id);
  445. if (i != NotFound)
  446. {
  447. querySDS().unsubscribe(sub_id);
  448. subIDs.remove(i);
  449. }
  450. }
  451. virtual void validateCache()
  452. {
  453. if (!subscription)
  454. subscription.setown( new CSdsSubscription() );
  455. subscription->handleEnvironmentChange();
  456. }
  457. private:
  458. IRemoteConnection* connect(const char *xpath, unsigned flags)
  459. {
  460. return querySDS().connect(xpath, myProcessSession(), flags, SDS_LOCK_TIMEOUT);
  461. }
  462. };
  463. static CEnvironmentFactory *factory=nullptr;
  464. void CEnvironmentFactory::clientShutdown()
  465. {
  466. closeEnvironment();
  467. }
  468. MODULE_INIT(INIT_PRIORITY_ENV_ENVIRONMENT)
  469. {
  470. return true;
  471. }
  472. MODULE_EXIT()
  473. {
  474. ::Release(factory);
  475. }
  476. //==========================================================================================
  477. class CConstEnvBase : public CInterface
  478. {
  479. protected:
  480. const CLocalEnvironment* env; // Not linked - would be circular....
  481. // That could cause problems
  482. Linked<IPropertyTree> root;
  483. public:
  484. CConstEnvBase(const CLocalEnvironment* _env, IPropertyTree *_root)
  485. : env(_env), root(_root)
  486. {
  487. }
  488. IStringVal& getXML(IStringVal &str) const
  489. {
  490. StringBuffer x;
  491. toXML(root->queryBranch("."), x);
  492. str.set(x.str());
  493. return str;
  494. };
  495. IStringVal& getName(IStringVal &str) const
  496. {
  497. str.set(root->queryProp("@name"));
  498. return str;
  499. }
  500. IPropertyTree& getPTree() const
  501. {
  502. return *LINK(root);
  503. }
  504. };
  505. #define IMPLEMENT_ICONSTENVBASE \
  506. virtual IStringVal& getXML(IStringVal &str) const { return CConstEnvBase::getXML(str); } \
  507. virtual IStringVal& getName(IStringVal &str) const { return CConstEnvBase::getName(str); } \
  508. virtual IPropertyTree& getPTree() const { return CConstEnvBase::getPTree(); }
  509. //==========================================================================================
  510. class CConstDomainInfo : public CConstEnvBase, implements IConstDomainInfo
  511. {
  512. public:
  513. IMPLEMENT_IINTERFACE;
  514. IMPLEMENT_ICONSTENVBASE;
  515. CConstDomainInfo(CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root) {}
  516. virtual void getAccountInfo(IStringVal &name, IStringVal &pw) const
  517. {
  518. if (root->hasProp("@username"))
  519. name.set(root->queryProp("@username"));
  520. else
  521. name.clear();
  522. if (root->hasProp("@password"))
  523. {
  524. StringBuffer pwd;
  525. decrypt(pwd, root->queryProp("@password"));
  526. pw.set(pwd.str());
  527. }
  528. else
  529. pw.clear();
  530. }
  531. virtual void getSnmpSecurityString(IStringVal & securityString) const
  532. {
  533. if (root->hasProp("@snmpSecurityString"))
  534. {
  535. StringBuffer sec_string;
  536. decrypt(sec_string, root->queryProp("@snmpSecurityString"));
  537. securityString.set(sec_string.str());
  538. }
  539. else
  540. securityString.set("");
  541. }
  542. virtual void getSSHAccountInfo(IStringVal &name, IStringVal &sshKeyFile, IStringVal& sshKeyPassphrase) const
  543. {
  544. if (root->hasProp("@username"))
  545. name.set(root->queryProp("@username"));
  546. else
  547. name.clear();
  548. if (root->hasProp("@sshKeyFile"))
  549. sshKeyFile.set(root->queryProp("@sshKeyFile"));
  550. else
  551. sshKeyFile.clear();
  552. if (root->hasProp("@sshKeyPassphrase"))
  553. sshKeyPassphrase.set(root->queryProp("@sshKeyPassphrase"));
  554. else
  555. sshKeyPassphrase.clear();
  556. }
  557. };
  558. //==========================================================================================
  559. struct mapOsEnums { EnvMachineOS val; const char *str; };
  560. static EnvMachineOS getEnum(IPropertyTree *p, const char *propname, mapOsEnums *map)
  561. {
  562. const char *v = p->queryProp(propname);
  563. if (v && *v)
  564. {
  565. while (map->str)
  566. {
  567. if (stricmp(v, map->str)==0)
  568. return map->val;
  569. map++;
  570. }
  571. throw MakeStringException(0, "Unknown operating system: \"%s\"", v);
  572. }
  573. return MachineOsUnknown;
  574. }
  575. struct mapStateEnums { EnvMachineState val; const char *str; };
  576. static EnvMachineState getEnum(IPropertyTree *p, const char *propname, mapStateEnums *map)
  577. {
  578. const char *v = p->queryProp(propname);
  579. if (v && *v)
  580. {
  581. while (map->str)
  582. {
  583. if (stricmp(v, map->str)==0)
  584. return map->val;
  585. map++;
  586. }
  587. assertex(!"Unexpected value in getEnum");
  588. }
  589. return MachineStateUnknown;
  590. }
  591. mapOsEnums OperatingSystems[] = {
  592. { MachineOsW2K, "W2K" },
  593. { MachineOsSolaris, "solaris" },
  594. { MachineOsLinux, "linux" },
  595. { MachineOsSize, nullptr }
  596. };
  597. mapStateEnums MachineStates[] = {
  598. { MachineStateAvailable, "Available" },
  599. { MachineStateUnavailable, "Unavailable" },
  600. { MachineStateUnknown, "Unknown" }
  601. };
  602. //==========================================================================================
  603. class CConstMachineInfo : public CConstEnvBase, implements IConstMachineInfo
  604. {
  605. public:
  606. IMPLEMENT_IINTERFACE;
  607. IMPLEMENT_ICONSTENVBASE;
  608. CConstMachineInfo(CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root) {}
  609. virtual IConstDomainInfo* getDomain() const
  610. {
  611. return env->getDomain(root->queryProp("@domain"));
  612. }
  613. virtual IStringVal& getNetAddress(IStringVal &str) const
  614. {
  615. str.set(root->queryProp("@netAddress"));
  616. return str;
  617. }
  618. virtual IStringVal& getDescription(IStringVal &str) const
  619. {
  620. UNIMPLEMENTED;
  621. }
  622. virtual unsigned getNicSpeedMbitSec() const
  623. {
  624. const char * v = root->queryProp("@nicSpeed");
  625. if (v && *v)
  626. return atoi(v);
  627. Owned<IConstComputerTypeInfo> type = env->getComputerType(root->queryProp("@computerType"));
  628. if (type)
  629. return type->getNicSpeedMbitSec();
  630. return 0;
  631. }
  632. virtual EnvMachineOS getOS() const
  633. {
  634. EnvMachineOS os = getEnum(root, "@opSys", OperatingSystems);
  635. if (os != MachineOsUnknown)
  636. return os;
  637. Owned<IConstComputerTypeInfo> type = env->getComputerType(root->queryProp("@computerType"));
  638. if (type)
  639. return type->getOS();
  640. return MachineOsUnknown;
  641. }
  642. virtual EnvMachineState getState() const
  643. {
  644. return getEnum(root, "@state", MachineStates);
  645. }
  646. };
  647. //==========================================================================================
  648. class CConstComputerTypeInfo : public CConstEnvBase, implements IConstComputerTypeInfo
  649. {
  650. public:
  651. IMPLEMENT_IINTERFACE;
  652. IMPLEMENT_ICONSTENVBASE;
  653. CConstComputerTypeInfo(CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root) {}
  654. virtual EnvMachineOS getOS() const
  655. {
  656. EnvMachineOS os = getEnum(root, "@opSys", OperatingSystems);
  657. if (os != MachineOsUnknown)
  658. return os;
  659. Owned<IConstComputerTypeInfo> type = env->getComputerType(root->queryProp("@computerType"));
  660. if (type && (type.get() != this))
  661. return type->getOS();
  662. return MachineOsUnknown;
  663. }
  664. virtual unsigned getNicSpeedMbitSec() const
  665. {
  666. const char * v = root->queryProp("@nicSpeed");
  667. if (v && *v)
  668. return atoi(v);
  669. Owned<IConstComputerTypeInfo> type = env->getComputerType(root->queryProp("@computerType"));
  670. if (type && (type.get() != this))
  671. return type->getNicSpeedMbitSec();
  672. return 0;
  673. }
  674. };
  675. //==========================================================================================
  676. class CConstInstanceInfo : public CConstEnvBase, implements IConstInstanceInfo
  677. {
  678. public:
  679. IMPLEMENT_IINTERFACE;
  680. IMPLEMENT_ICONSTENVBASE;
  681. CConstInstanceInfo(const CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root)
  682. {
  683. }
  684. virtual IConstMachineInfo * getMachine() const
  685. {
  686. return env->getMachine(root->queryProp("@computer"));
  687. }
  688. virtual IStringVal & getEndPoint(IStringVal & str) const
  689. {
  690. SCMStringBuffer ep;
  691. Owned<IConstMachineInfo> machine = getMachine();
  692. if (machine)
  693. {
  694. machine->getNetAddress(ep);
  695. const char *port = root->queryProp("@port");
  696. if (port)
  697. ep.s.append(':').append(port);
  698. }
  699. str.set(ep.str());
  700. return str;
  701. }
  702. virtual IStringVal & getExecutableDirectory(IStringVal & str) const
  703. {
  704. // this is the deploy directory so uses local path separators (I suspect this call is LEGACY now)
  705. SCMStringBuffer ep;
  706. Owned<IConstMachineInfo> machine = getMachine();
  707. if (machine)
  708. {
  709. machine->getNetAddress(ep);
  710. ep.s.insert(0, PATHSEPSTR PATHSEPSTR);
  711. }
  712. ep.s.append(PATHSEPCHAR).append(root->queryProp("@directory"));
  713. str.set(ep.str());
  714. return str;
  715. }
  716. virtual bool doGetRunInfo(IStringVal & progpath, IStringVal & workdir, const char *defprogname, bool useprog) const
  717. {
  718. // this is remote path i.e. path should match *target* nodes format
  719. Owned<IConstMachineInfo> machine = getMachine();
  720. if (!machine)
  721. return false;
  722. char psep;
  723. bool appendexe;
  724. switch (machine->getOS())
  725. {
  726. case MachineOsSolaris:
  727. case MachineOsLinux:
  728. psep = '/';
  729. appendexe = false;
  730. break;
  731. default:
  732. psep = '\\';
  733. appendexe = true;
  734. }
  735. StringBuffer tmp;
  736. const char *program = useprog?root->queryProp("@program"):nullptr; // if program specified assume absolute
  737. if (!program||!*program)
  738. {
  739. SCMStringBuffer ep;
  740. machine->getNetAddress(ep);
  741. const char *dir = root->queryProp("@directory");
  742. if (dir)
  743. {
  744. if (isPathSepChar(*dir))
  745. dir++;
  746. if (!*dir)
  747. return false;
  748. tmp.append(psep).append(psep).append(ep.s).append(psep);
  749. do {
  750. if (isPathSepChar(*dir))
  751. tmp.append(psep);
  752. else
  753. tmp.append(*dir);
  754. dir++;
  755. } while (*dir);
  756. if (!isPathSepChar(tmp.charAt(tmp.length()-1)))
  757. tmp.append(psep);
  758. tmp.append(defprogname);
  759. size32_t l = strlen(defprogname);
  760. if (appendexe&&((l<5)||(stricmp(defprogname+l-4,".exe")!=0)))
  761. tmp.append(".exe");
  762. }
  763. program = tmp.str();
  764. }
  765. progpath.set(program);
  766. const char *workd = root->queryProp("@workdir"); // if program specified assume absolute
  767. workdir.set(workd?workd:"");
  768. return true;
  769. }
  770. virtual bool getRunInfo(IStringVal & progpath, IStringVal & workdir, const char *defprogname) const
  771. {
  772. return doGetRunInfo(progpath,workdir,defprogname,true);
  773. }
  774. virtual unsigned getPort() const
  775. {
  776. return root->getPropInt("@port", 0);
  777. }
  778. };
  779. class CConstDropZoneInfo : public CConstEnvBase, implements IConstDropZoneInfo
  780. {
  781. public:
  782. IMPLEMENT_IINTERFACE;
  783. IMPLEMENT_ICONSTENVBASE;
  784. CConstDropZoneInfo(CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root) {}
  785. virtual IStringVal& getComputerName(IStringVal &str) const
  786. {
  787. str.set(root->queryProp("@computer"));
  788. return str;
  789. }
  790. virtual IStringVal& getDescription(IStringVal &str) const
  791. {
  792. str.set(root->queryProp("@description"));
  793. return str;
  794. }
  795. virtual IStringVal& getDirectory(IStringVal &str) const
  796. {
  797. str.set(root->queryProp("@directory"));
  798. return str;
  799. }
  800. virtual IStringVal& getUMask(IStringVal &str) const
  801. {
  802. if (root->hasProp("@umask"))
  803. str.set(root->queryProp("@umask"));
  804. return str;
  805. }
  806. };
  807. #if 0
  808. //==========================================================================================
  809. class CConstProcessInfo : public CConstEnvBase, implements IConstProcessInfo
  810. {
  811. IArrayOf<IConstInstanceInfo> w;
  812. CArrayIteratorOf<IInterface, IIterator> it;
  813. public:
  814. IMPLEMENT_IINTERFACE;
  815. IMPLEMENT_ICONSTENVBASE;
  816. CConstProcessInfo(CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root), it(w)
  817. {
  818. Owned<IPropertyTreeIterator> _it = root->getElements("*"); // MORE - should be instance
  819. for (_it->first(); _it->isValid(); _it->next())
  820. {
  821. IPropertyTree *rp = &_it->query();
  822. w.append(*new CConstInstanceInfo(env, rp)); // CConstInstanceInfo will link rp
  823. }
  824. }
  825. bool first() { return it.first(); }
  826. bool isValid() { return it.isValid(); }
  827. bool next() { return it.next(); }
  828. IConstInstanceInfo & query() { return (IConstInstanceInfo &) it.query();}
  829. virtual IConstInstanceInfo * getInstance(const char *domain)
  830. {
  831. for (int pass=0; pass<2; pass++)
  832. {
  833. ForEachItemIn(idx, w)
  834. {
  835. Owned<IConstMachineInfo> m = w.item(idx).getMachine();
  836. if (m)
  837. {
  838. Owned<IConstDomainInfo> dm = m->getDomain();
  839. if (dm)
  840. {
  841. StringBuffer thisdomain;
  842. //dm->getName(StringBufferAdaptor(thisdomain)); // confuses g++
  843. StringBufferAdaptor strval(thisdomain);
  844. dm->getName(strval);
  845. if (thisdomain.length() && strcmp(domain, thisdomain.str())==0)
  846. return LINK(&w.item(idx));
  847. }
  848. }
  849. }
  850. }
  851. return nullptr;
  852. }
  853. };
  854. #endif
  855. //==========================================================================================
  856. CLocalEnvironment::CLocalEnvironment(const char* environmentFile)
  857. {
  858. if (environmentFile && *environmentFile)
  859. {
  860. IPropertyTree* root = createPTreeFromXMLFile(environmentFile);
  861. if (root)
  862. p.set(root);
  863. }
  864. init();
  865. }
  866. CLocalEnvironment::CLocalEnvironment(IRemoteConnection *_conn, IPropertyTree* root/*=nullptr*/,
  867. const char* path/*="/Environment"*/)
  868. : xPath(path)
  869. {
  870. conn.set(_conn);
  871. if (root)
  872. p.set(root);
  873. else
  874. p.setown(conn->getRoot());
  875. init();
  876. }
  877. void CLocalEnvironment::init()
  878. {
  879. machineCacheBuilt = false;
  880. dropZoneCacheBuilt = false;
  881. numOfMachines = 0;
  882. numOfDropZones = 0;
  883. numOfDropzonesByComputer.setown(createPTree("computers"));
  884. }
  885. CLocalEnvironment::~CLocalEnvironment()
  886. {
  887. if (conn)
  888. conn->rollback();
  889. }
  890. IEnvironment& CLocalEnvironment::lock() const
  891. {
  892. return *new CLockedEnvironment((CLocalEnvironment*)this);
  893. }
  894. IStringVal & CLocalEnvironment::getName(IStringVal & str) const
  895. {
  896. synchronized procedure(safeCache);
  897. str.set(p->queryProp("@name"));
  898. return str;
  899. }
  900. IStringVal & CLocalEnvironment::getXML(IStringVal & str) const
  901. {
  902. StringBuffer xml;
  903. {
  904. synchronized procedure(safeCache);
  905. toXML(p->queryBranch("."), xml);
  906. }
  907. str.set(xml.str());
  908. return str;
  909. }
  910. IPropertyTree & CLocalEnvironment::getPTree() const
  911. {
  912. synchronized procedure(safeCache);
  913. return *LINK(p);
  914. }
  915. IConstEnvBase * CLocalEnvironment::getCache(const char *path) const
  916. {
  917. IConstEnvBase * ret = cache.getValue(path);
  918. ::Link(ret);
  919. return ret;
  920. }
  921. void CLocalEnvironment::setCache(const char *path, IConstEnvBase *value) const
  922. {
  923. cache.setValue(path, value);
  924. }
  925. IConstDomainInfo * CLocalEnvironment::getDomain(const char * name) const
  926. {
  927. if (!name)
  928. return nullptr;
  929. StringBuffer xpath;
  930. xpath.appendf("Hardware/Domain[@name=\"%s\"]", name);
  931. synchronized procedure(safeCache);
  932. IConstEnvBase *cached = getCache(xpath.str());
  933. if (!cached)
  934. {
  935. IPropertyTree *d = p->queryPropTree(xpath.str());
  936. if (!d)
  937. return nullptr;
  938. cached = new CConstDomainInfo((CLocalEnvironment *) this, d);
  939. setCache(xpath.str(), cached);
  940. }
  941. return (IConstDomainInfo *) cached;
  942. }
  943. void CLocalEnvironment::buildMachineCache() const
  944. {
  945. synchronized procedure(safeCache);
  946. if (!machineCacheBuilt)
  947. {
  948. Owned<IPropertyTreeIterator> it = p->getElements("Hardware/Computer");
  949. ForEach(*it)
  950. {
  951. const char *name = it->query().queryProp("@name");
  952. if (name)
  953. {
  954. StringBuffer x("Hardware/Computer[@name=\"");
  955. x.append(name).append("\"]");
  956. Owned<IConstEnvBase> cached = new CConstMachineInfo((CLocalEnvironment *) this, &it->query());
  957. cache.setValue(x.str(), cached);
  958. }
  959. const char * netAddress = it->query().queryProp("@netAddress");
  960. if (netAddress)
  961. {
  962. StringBuffer x("Hardware/Computer[@netAddress=\"");
  963. x.append(netAddress).append("\"]");
  964. Owned<IConstEnvBase> cached = new CConstMachineInfo((CLocalEnvironment *) this, &it->query());
  965. cache.setValue(x.str(), cached);
  966. IpAddress ip;
  967. ip.ipset(netAddress);
  968. if (ip.isLocal())
  969. cache.setValue("Hardware/Computer[@netAddress=\".\"]", cached);
  970. }
  971. numOfMachines++;
  972. StringBuffer x("Hardware/Computer[@id=\"");
  973. x.append(MACHINE_PREFIX).append(numOfMachines).append("\"]");
  974. Owned<IConstEnvBase> cached = new CConstMachineInfo((CLocalEnvironment *) this, &it->query());
  975. cache.setValue(x.str(), cached);
  976. }
  977. machineCacheBuilt = true;
  978. }
  979. }
  980. void CLocalEnvironment::buildDropZoneCache() const
  981. {
  982. synchronized procedure(safeCache);
  983. if (!dropZoneCacheBuilt)
  984. {
  985. Owned<IPropertyTreeIterator> it = p->getElements("Software/DropZone");
  986. ForEach(*it)
  987. {
  988. const char *name = it->query().queryProp("@name");
  989. if (name)
  990. {
  991. StringBuffer x("Software/DropZone[@name=\"");
  992. x.append(name).append("\"]");
  993. Owned<IConstEnvBase> cached = new CConstDropZoneInfo((CLocalEnvironment *) this, &it->query());
  994. cache.setValue(x.str(), cached);
  995. }
  996. const char * computer = it->query().queryProp("@computer");
  997. if (computer)
  998. {
  999. StringBuffer xpath("@");
  1000. xpath.append(computer).append(NUMBER_OF_DROPZONES_SUFFIX);
  1001. unsigned numOfDropZoneByComputer = numOfDropzonesByComputer->getPropInt(xpath, -1);
  1002. if (numOfDropZoneByComputer == -1)
  1003. {
  1004. numOfDropZoneByComputer = 0;
  1005. numOfDropzonesByComputer->addPropInt(xpath, numOfDropZoneByComputer );
  1006. }
  1007. numOfDropZoneByComputer++;
  1008. numOfDropzonesByComputer->setPropInt(xpath, numOfDropZoneByComputer);
  1009. StringBuffer x("Software/DropZone[@computer=\"");
  1010. x.append(computer);
  1011. x.append(DROPZONE_BY_MACHINE_SUFFIX).append(numOfDropZoneByComputer);
  1012. x.append("\"]");
  1013. Owned<IConstEnvBase> cached = new CConstDropZoneInfo((CLocalEnvironment *) this, &it->query());
  1014. cache.setValue(x.str(), cached);
  1015. }
  1016. numOfDropZones++;
  1017. StringBuffer x("Software/DropZone[@id=\"");
  1018. x.append(DROPZONE_SUFFIX).append(numOfDropZones).append("\"]");
  1019. Owned<IConstEnvBase> cached = new CConstDropZoneInfo((CLocalEnvironment *) this, &it->query());
  1020. cache.setValue(x.str(), cached);
  1021. }
  1022. dropZoneCacheBuilt = true;
  1023. }
  1024. }
  1025. IConstComputerTypeInfo * CLocalEnvironment::getComputerType(const char * name) const
  1026. {
  1027. if (!name)
  1028. return nullptr;
  1029. StringBuffer xpath;
  1030. xpath.appendf("Hardware/ComputerType[@name=\"%s\"]", name);
  1031. synchronized procedure(safeCache);
  1032. IConstEnvBase *cached = getCache(xpath.str());
  1033. if (!cached)
  1034. {
  1035. IPropertyTree *d = p->queryPropTree(xpath.str());
  1036. if (!d)
  1037. return nullptr;
  1038. cached = new CConstComputerTypeInfo((CLocalEnvironment *) this, d);
  1039. setCache(xpath.str(), cached);
  1040. }
  1041. return (CConstComputerTypeInfo *) cached;
  1042. }
  1043. IConstMachineInfo * CLocalEnvironment::getMachine(const char * name) const
  1044. {
  1045. if (!name)
  1046. return nullptr;
  1047. buildMachineCache();
  1048. StringBuffer xpath;
  1049. xpath.appendf("Hardware/Computer[@name=\"%s\"]", name);
  1050. synchronized procedure(safeCache);
  1051. IConstEnvBase *cached = getCache(xpath.str());
  1052. if (!cached)
  1053. {
  1054. IPropertyTree *d = p->queryPropTree(xpath.str());
  1055. if (!d)
  1056. return nullptr;
  1057. cached = new CConstMachineInfo((CLocalEnvironment *) this, d);
  1058. setCache(xpath.str(), cached);
  1059. }
  1060. return (CConstMachineInfo *) cached;
  1061. }
  1062. IConstMachineInfo * CLocalEnvironment::getMachineByAddress(const char * machineIp) const
  1063. {
  1064. if (!machineIp)
  1065. return nullptr;
  1066. buildMachineCache();
  1067. Owned<IPropertyTreeIterator> iter;
  1068. StringBuffer xpath;
  1069. xpath.appendf("Hardware/Computer[@netAddress=\"%s\"]", machineIp);
  1070. synchronized procedure(safeCache);
  1071. IConstEnvBase *cached = getCache(xpath.str());
  1072. if (!cached)
  1073. {
  1074. IPropertyTree *d = p->queryPropTree(xpath.str());
  1075. if (!d)
  1076. {
  1077. // I suspect not in the original spirit of this but look for resolved IP
  1078. Owned<IPropertyTreeIterator> iter = p->getElements("Hardware/Computer");
  1079. IpAddress ip;
  1080. ip.ipset(machineIp);
  1081. ForEach(*iter)
  1082. {
  1083. IPropertyTree &computer = iter->query();
  1084. IpAddress ip2;
  1085. const char *ips = computer.queryProp("@netAddress");
  1086. if (ips&&*ips)
  1087. {
  1088. ip2.ipset(ips);
  1089. if (ip.ipequals(ip2))
  1090. {
  1091. d = &computer;
  1092. break;
  1093. }
  1094. }
  1095. }
  1096. }
  1097. if (!d)
  1098. return nullptr;
  1099. StringBuffer xpath1;
  1100. xpath1.appendf("Hardware/Computer[@name=\"%s\"]", d->queryProp("@name"));
  1101. cached = getCache(xpath1.str());
  1102. if (!cached)
  1103. {
  1104. cached = new CConstMachineInfo((CLocalEnvironment *) this, d);
  1105. setCache(xpath1.str(), cached);
  1106. setCache(xpath.str(), cached);
  1107. }
  1108. }
  1109. return (CConstMachineInfo *) cached;
  1110. }
  1111. IConstMachineInfo * CLocalEnvironment::getMachineByIndex(unsigned index) const
  1112. {
  1113. if (!numOfMachines || (index == 0))
  1114. return nullptr;
  1115. buildMachineCache();
  1116. if (index > numOfMachines)
  1117. return nullptr;
  1118. StringBuffer xpath("Hardware/Computer[@id=\"");
  1119. xpath.append(MACHINE_PREFIX).append(index).append("\"]");
  1120. synchronized procedure(safeCache);
  1121. return (IConstMachineInfo *) getCache(xpath.str());
  1122. }
  1123. IConstMachineInfo * CLocalEnvironment::getMachineForLocalHost() const
  1124. {
  1125. buildMachineCache();
  1126. synchronized procedure(safeCache);
  1127. return (CConstMachineInfo *) getCache("Hardware/Computer[@netAddress=\".\"]");
  1128. }
  1129. IConstDropZoneInfo * CLocalEnvironment::getDropZone(const char * name) const
  1130. {
  1131. if (!name)
  1132. return nullptr;
  1133. buildDropZoneCache();
  1134. VStringBuffer xpath("Software/DropZone[@name=\"%s\"]", name);
  1135. synchronized procedure(safeCache);
  1136. return (CConstDropZoneInfo *) getCache(xpath.str());
  1137. }
  1138. IConstDropZoneInfo * CLocalEnvironment::getDropZoneByComputer(const char * computer) const
  1139. {
  1140. if (!computer)
  1141. return nullptr;
  1142. buildDropZoneCache();
  1143. StringBuffer x("@");
  1144. x.append(computer).append(NUMBER_OF_DROPZONES_SUFFIX);
  1145. unsigned numOfDropZoneByComputer = numOfDropzonesByComputer->getPropInt(x, -1);
  1146. if (numOfDropZoneByComputer == -1)
  1147. return nullptr;
  1148. StringBuffer xpath("Software/DropZone[@computer=\"");
  1149. xpath.append(computer);
  1150. xpath.append(DROPZONE_BY_MACHINE_SUFFIX).append(DEFAULT_DROPZONE_INDEX);
  1151. xpath.append("\"]");
  1152. synchronized procedure(safeCache);
  1153. return (CConstDropZoneInfo *) getCache(xpath.str());
  1154. }
  1155. IConstDropZoneInfo * CLocalEnvironment::getDropZoneByComputer(const char * computer, const char * dzname) const
  1156. {
  1157. IConstDropZoneInfo * dzInfo = getDropZone(dzname);
  1158. if (!dzInfo)
  1159. return nullptr;
  1160. SCMStringBuffer cachedComputer;
  1161. dzInfo->getComputerName(cachedComputer);
  1162. if (!streq(computer, cachedComputer.str()))
  1163. return nullptr;
  1164. return dzInfo;
  1165. }
  1166. IConstDropZoneInfo * CLocalEnvironment::getDropZoneByComputerByIndex(const char * computer, unsigned index) const
  1167. {
  1168. if (!computer || (index == 0))
  1169. return nullptr;
  1170. buildDropZoneCache();
  1171. if (index > getNumberOfDropZonesByComputer(computer))
  1172. return nullptr;
  1173. StringBuffer xpath("Software/DropZone[@computer=\"");
  1174. xpath.append(computer).append(DROPZONE_BY_MACHINE_SUFFIX).append(index).append("\"]");
  1175. synchronized procedure(safeCache);
  1176. return (CConstDropZoneInfo *) getCache(xpath.str());
  1177. }
  1178. IConstDropZoneInfo * CLocalEnvironment::getDropZoneByIndex(unsigned index) const
  1179. {
  1180. if (!numOfDropZones || (index == 0))
  1181. return nullptr;
  1182. buildDropZoneCache();
  1183. if (index > numOfDropZones)
  1184. return nullptr;
  1185. StringBuffer xpath("Software/DropZone[@id=\"");
  1186. xpath.append(DROPZONE_SUFFIX).append(index).append("\"]");
  1187. synchronized procedure(safeCache);
  1188. return (CConstDropZoneInfo *) getCache(xpath.str());
  1189. }
  1190. IConstInstanceInfo * CLocalEnvironment::getInstance(const char *type, const char *version, const char *domain) const
  1191. {
  1192. StringBuffer xpath("Software/");
  1193. xpath.append(type);
  1194. if (version)
  1195. xpath.append("[@version='").append(version).append("']");
  1196. xpath.append("/Instance");
  1197. synchronized procedure(safeCache);
  1198. Owned<IPropertyTreeIterator> _it = p->getElements(xpath);
  1199. for (_it->first(); _it->isValid(); _it->next())
  1200. {
  1201. IPropertyTree *rp = &_it->query();
  1202. Owned<CConstInstanceInfo> inst = new CConstInstanceInfo(this, rp); // CConstInstanceInfo will link rp
  1203. Owned<IConstMachineInfo> m = inst->getMachine();
  1204. if (m)
  1205. {
  1206. Owned<IConstDomainInfo> dm = m->getDomain();
  1207. if (dm)
  1208. {
  1209. SCMStringBuffer thisdomain;
  1210. dm->getName(thisdomain);
  1211. if (thisdomain.length() && strcmp(domain, thisdomain.str())==0)
  1212. return inst.getClear();
  1213. }
  1214. }
  1215. }
  1216. return nullptr;
  1217. }
  1218. CConstInstanceInfo * CLocalEnvironment::getInstanceByIP(const char *type, const char *version, IpAddress &ip) const
  1219. {
  1220. StringBuffer xpath("Software/");
  1221. xpath.append(type);
  1222. if (version)
  1223. xpath.append("[@version='").append(version).append("']");
  1224. xpath.append("/Instance");
  1225. synchronized procedure(safeCache);
  1226. assertex(p);
  1227. Owned<IPropertyTreeIterator> _it = p->getElements(xpath);
  1228. assertex(_it);
  1229. for (_it->first(); _it->isValid(); _it->next())
  1230. {
  1231. IPropertyTree *rp = &_it->query();
  1232. assertex(rp);
  1233. Owned<CConstInstanceInfo> inst = new CConstInstanceInfo(this, rp); // CConstInstanceInfo will link rp
  1234. Owned<IConstMachineInfo> m = inst->getMachine();
  1235. if (m)
  1236. {
  1237. SCMStringBuffer eps;
  1238. m->getNetAddress(eps);
  1239. SocketEndpoint ep(eps.str());
  1240. if (ep.ipequals(ip))
  1241. return inst.getClear();
  1242. }
  1243. }
  1244. return nullptr;
  1245. }
  1246. void CLocalEnvironment::unlockRemote()
  1247. {
  1248. #if 0
  1249. conn->commit(true);
  1250. conn->changeMode(0, SDS_LOCK_TIMEOUT);
  1251. #else
  1252. if (conn)
  1253. {
  1254. synchronized procedure(safeCache);
  1255. p.clear();
  1256. conn.setown(querySDS().connect(xPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT));
  1257. p.setown(conn->getRoot());
  1258. }
  1259. #endif
  1260. }
  1261. void CLocalEnvironment::preload()
  1262. {
  1263. synchronized procedure(safeCache);
  1264. p->queryBranch(".");
  1265. }
  1266. void CLocalEnvironment::setXML(const char *xml)
  1267. {
  1268. Owned<IPropertyTree> newRoot = createPTreeFromXMLString(xml);
  1269. synchronized procedure(safeCache);
  1270. Owned<IPropertyTreeIterator> it = p->getElements("*");
  1271. ForEach(*it)
  1272. {
  1273. p->removeTree(&it->query());
  1274. }
  1275. it.setown(newRoot->getElements("*"));
  1276. ForEach(*it)
  1277. {
  1278. IPropertyTree *sub = &it->get();
  1279. p->addPropTree(sub->queryName(), sub);
  1280. }
  1281. }
  1282. bool CLocalEnvironment::getRunInfo(IStringVal & path, IStringVal & dir, const char * tag, const char * version, const char *machineaddr, const char *defprogname) const
  1283. {
  1284. try
  1285. {
  1286. // PrintLog("getExecutablePath %s %s %s", tag, version, machineaddr);
  1287. // first see if local machine with deployed on
  1288. SocketEndpoint ep(machineaddr);
  1289. Owned<CConstInstanceInfo> ipinstance = getInstanceByIP(tag, version, ep);
  1290. if (ipinstance)
  1291. {
  1292. StringAttr testpath;
  1293. StringAttrAdaptor teststrval(testpath);
  1294. if (ipinstance->doGetRunInfo(teststrval,dir,defprogname,false))
  1295. { // this returns full string
  1296. RemoteFilename rfn;
  1297. rfn.setRemotePath(testpath.get());
  1298. Owned<IFile> file = createIFile(rfn);
  1299. if (file->exists())
  1300. {
  1301. StringBuffer tmp;
  1302. rfn.getLocalPath(tmp);
  1303. path.set(tmp.str());
  1304. return true;
  1305. }
  1306. }
  1307. }
  1308. Owned<IConstMachineInfo> machine = getMachineByAddress(machineaddr);
  1309. if (!machine)
  1310. {
  1311. LOG(MCdebugInfo, unknownJob, "Unable to find machine for %s", machineaddr);
  1312. return false;
  1313. }
  1314. StringAttr targetdomain;
  1315. Owned<IConstDomainInfo> domain = machine->getDomain();
  1316. if (!domain)
  1317. {
  1318. LOG(MCdebugInfo, unknownJob, "Unable to find domain for %s", machineaddr);
  1319. return false;
  1320. }
  1321. //domain->getName(StringAttrAdaptor(targetdomain)); // confuses g++
  1322. StringAttrAdaptor strval(targetdomain);
  1323. domain->getName(strval);
  1324. Owned<IConstInstanceInfo> instance = getInstance(tag, version, targetdomain);
  1325. if (!instance)
  1326. {
  1327. LOG(MCdebugInfo, unknownJob, "Unable to find process %s for domain %s", tag, targetdomain.get());
  1328. return false;
  1329. }
  1330. return instance->getRunInfo(path,dir,defprogname);
  1331. }
  1332. catch (IException * e)
  1333. {
  1334. EXCLOG(e, "Extracting slave version");
  1335. e->Release();
  1336. return false;
  1337. }
  1338. }
  1339. void CLocalEnvironment::clearCache()
  1340. {
  1341. synchronized procedure(safeCache);
  1342. if (conn)
  1343. {
  1344. p.clear();
  1345. conn->reload();
  1346. p.setown(conn->getRoot());
  1347. }
  1348. cache.kill();
  1349. numOfDropzonesByComputer.clear();
  1350. init();
  1351. resetPasswordsFromSDS();
  1352. }
  1353. IConstDropZoneInfo * CLocalEnvironment::getDropZoneByAddressPath(const char * netaddress, const char *targetFilePath) const
  1354. {
  1355. IConstDropZoneInfo * retVal = nullptr;
  1356. Owned<IConstMachineInfo> machineInfo = getMachineByAddress(netaddress);
  1357. if (!machineInfo)
  1358. return retVal;
  1359. SCMStringBuffer machineName;
  1360. machineInfo->getName(machineName);
  1361. const char * pmachineName = machineName.str();
  1362. Owned<IConstDropZoneInfoIterator> zoneIt= getDropZoneIteratorByComputer(pmachineName);
  1363. #ifdef _DEBUG
  1364. LOG(MCdebugInfo, unknownJob, "Check remote drop zones (%d) by iterator on '%s':", zoneIt->count(), pmachineName);
  1365. #endif
  1366. SCMStringBuffer dropzonePath;
  1367. const char * pdropzonePath = nullptr;
  1368. unsigned dropzonePathLen = _MAX_PATH + 1;
  1369. ForEach(*zoneIt)
  1370. {
  1371. SCMStringBuffer dropZoneDir;
  1372. zoneIt->query().getDirectory(dropZoneDir);
  1373. StringBuffer fullDropZoneDir(dropZoneDir.str());
  1374. const char pathSeparator = fullDropZoneDir.charAt(0);
  1375. if (fullDropZoneDir.charAt(fullDropZoneDir.length()) != pathSeparator)
  1376. fullDropZoneDir.append(pathSeparator);
  1377. const char * pdropzoneDir = fullDropZoneDir.str();
  1378. // Check target file path starts with this Drop zone path
  1379. // the drop zone paths can be nested (nothing forbids it) like
  1380. // dz1: /a/b/c/d
  1381. // dz2: /a/b/c
  1382. // dz3: /a/b
  1383. // check all and select the shortest
  1384. if (strncmp(pdropzoneDir, targetFilePath, strlen(pdropzoneDir)) == 0)
  1385. {
  1386. if (dropzonePathLen > strlen(pdropzoneDir))
  1387. {
  1388. dropzonePathLen = strlen(pdropzoneDir);
  1389. dropzonePath.set(pdropzoneDir);
  1390. pdropzonePath = dropzonePath.str();
  1391. retVal = &zoneIt->query();
  1392. }
  1393. }
  1394. }
  1395. return retVal;
  1396. }
  1397. IConstDropZoneInfoIterator * CLocalEnvironment::getDropZoneIteratorByComputer(const char * computer) const
  1398. {
  1399. return new CConstDropZoneIteratorByComputer(computer);
  1400. }
  1401. IConstDropZoneInfoIterator * CLocalEnvironment::getDropZoneIterator() const
  1402. {
  1403. return new CConstDropZoneInfoIterator();
  1404. }
  1405. IConstMachineInfoIterator * CLocalEnvironment::getMachineIterator() const
  1406. {
  1407. return new CConstMachineInfoIterator();
  1408. }
  1409. //==========================================================================================
  1410. // Iterators implementation
  1411. CConstMachineInfoIterator::CConstMachineInfoIterator()
  1412. {
  1413. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  1414. constEnv.setown((CLocalEnvironment *)factory->openEnvironment());
  1415. maxIndex = constEnv->getNumberOfMachines();
  1416. }
  1417. bool CConstMachineInfoIterator::first()
  1418. {
  1419. index = 1;
  1420. curr = constEnv->getMachineByIndex(index);
  1421. return (curr != nullptr);
  1422. }
  1423. bool CConstMachineInfoIterator::next()
  1424. {
  1425. if (index < maxIndex)
  1426. {
  1427. index++;
  1428. curr = constEnv->getMachineByIndex(index);
  1429. }
  1430. else
  1431. curr = nullptr;
  1432. return (curr ? true : false);
  1433. }
  1434. bool CConstMachineInfoIterator::isValid()
  1435. {
  1436. return curr != nullptr;
  1437. }
  1438. IConstMachineInfo & CConstMachineInfoIterator::query()
  1439. {
  1440. return *curr;
  1441. }
  1442. unsigned CConstMachineInfoIterator::count() const
  1443. {
  1444. return maxIndex;
  1445. }
  1446. //--------------------------------------------------
  1447. CConstDropZoneIteratorByComputer::CConstDropZoneIteratorByComputer(const char * computer)
  1448. {
  1449. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  1450. constEnv.setown((CLocalEnvironment *)factory->openEnvironment());
  1451. computerName.set(computer);
  1452. maxIndex = constEnv->getNumberOfDropZonesByComputer(computer);
  1453. }
  1454. bool CConstDropZoneIteratorByComputer::first()
  1455. {
  1456. index = 1;
  1457. curr = constEnv->getDropZoneByComputerByIndex(computerName.str(), index);
  1458. return (curr != nullptr);
  1459. }
  1460. bool CConstDropZoneIteratorByComputer::next()
  1461. {
  1462. if (index < maxIndex)
  1463. {
  1464. index++;
  1465. curr = constEnv->getDropZoneByComputerByIndex(computerName.str(), index);
  1466. }
  1467. else
  1468. curr = nullptr;
  1469. return (curr ? true : false);
  1470. }
  1471. bool CConstDropZoneIteratorByComputer::isValid()
  1472. {
  1473. return curr != nullptr;
  1474. }
  1475. IConstDropZoneInfo & CConstDropZoneIteratorByComputer::query()
  1476. {
  1477. return *curr;
  1478. }
  1479. unsigned CConstDropZoneIteratorByComputer::count() const
  1480. {
  1481. return maxIndex;
  1482. }
  1483. //--------------------------------------------------
  1484. CConstDropZoneInfoIterator::CConstDropZoneInfoIterator()
  1485. {
  1486. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  1487. constEnv.setown((CLocalEnvironment *)factory->openEnvironment());
  1488. maxIndex = constEnv->getNumberOfDropZones();
  1489. }
  1490. bool CConstDropZoneInfoIterator::first()
  1491. {
  1492. index = 1;
  1493. curr = constEnv->getDropZoneByIndex(index);
  1494. return (curr != nullptr);
  1495. }
  1496. bool CConstDropZoneInfoIterator::next()
  1497. {
  1498. if (index < maxIndex)
  1499. {
  1500. index++;
  1501. curr = constEnv->getDropZoneByIndex(index);
  1502. }
  1503. else
  1504. curr = nullptr;
  1505. return (curr ? true : false);
  1506. }
  1507. bool CConstDropZoneInfoIterator::isValid()
  1508. {
  1509. return curr != nullptr;
  1510. }
  1511. IConstDropZoneInfo & CConstDropZoneInfoIterator::query()
  1512. {
  1513. return *curr;
  1514. }
  1515. unsigned CConstDropZoneInfoIterator::count() const
  1516. {
  1517. return maxIndex;
  1518. }
  1519. //==========================================================================================
  1520. static CriticalSection getEnvSect;
  1521. extern ENVIRONMENT_API IEnvironmentFactory * getEnvironmentFactory()
  1522. {
  1523. CriticalBlock block(getEnvSect);
  1524. if (!factory)
  1525. {
  1526. factory = new CEnvironmentFactory();
  1527. addShutdownHook(*factory);
  1528. }
  1529. return LINK(factory);
  1530. }
  1531. extern ENVIRONMENT_API void closeEnvironment()
  1532. {
  1533. try
  1534. {
  1535. CEnvironmentFactory* pFactory;
  1536. {
  1537. //this method is not meant to be invoked by multiple
  1538. //threads concurrently but just in case...
  1539. CriticalBlock block(getEnvSect);
  1540. pFactory = factory;
  1541. factory = nullptr;
  1542. }
  1543. clearPasswordsFromSDS();
  1544. if (pFactory)
  1545. {
  1546. removeShutdownHook(*pFactory);
  1547. pFactory->close();
  1548. pFactory->Release();
  1549. }
  1550. }
  1551. catch (IException *e)
  1552. {
  1553. EXCLOG(e);
  1554. }
  1555. }