environment.cpp 57 KB

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