environment.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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. static int environmentTraceLevel = 1;
  28. static Owned <IConstEnvironment> cache;
  29. class CConstInstanceInfo;
  30. class CLocalEnvironment : public CInterface, implements IConstEnvironment
  31. {
  32. private:
  33. // NOTE - order is important - we need to construct before p and (especially) destruct after p
  34. Owned<IRemoteConnection> conn;
  35. Owned<IPropertyTree> p;
  36. mutable MapStringToMyClass<IConstEnvBase> cache;
  37. mutable Mutex safeCache;
  38. mutable bool machineCacheBuilt;
  39. StringBuffer xPath;
  40. IConstEnvBase * getCache(const char *path) const;
  41. void setCache(const char *path, IConstEnvBase *value) const;
  42. void buildMachineCache() const;
  43. public:
  44. IMPLEMENT_IINTERFACE;
  45. CLocalEnvironment(IRemoteConnection *_conn, IPropertyTree *x=NULL, const char* path="Environment");
  46. CLocalEnvironment(const char* path="config.xml");
  47. virtual ~CLocalEnvironment();
  48. virtual IStringVal & getName(IStringVal & str) const;
  49. virtual IStringVal & getXML(IStringVal & str) const;
  50. virtual IPropertyTree & getPTree() const;
  51. virtual IEnvironment& lock() const;
  52. virtual IConstDomainInfo * getDomain(const char * name) const;
  53. virtual IConstMachineInfo * getMachine(const char * name) const;
  54. virtual IConstMachineInfo * getMachineByAddress(const char * name) const;
  55. virtual IConstInstanceInfo * getInstance(const char * type, const char * version, const char *domain) const;
  56. virtual CConstInstanceInfo * getInstanceByIP(const char *type, const char *version, IpAddress &ip) const;
  57. virtual IConstComputerTypeInfo * getComputerType(const char * name) const;
  58. virtual bool getRunInfo(IStringVal & path, IStringVal & dir, const char *type, const char *version, const char *machineaddr, const char *defprogname) const;
  59. virtual void preload();
  60. virtual IRemoteConnection* getConnection() const { return conn.getLink(); }
  61. void setXML(const char * logicalName);
  62. const char* getPath() const { return xPath.str(); }
  63. void unlockRemote();
  64. virtual bool isConstEnvironment() const { return true; }
  65. virtual void clearCache();
  66. };
  67. class CLockedEnvironment : public CInterface, implements IEnvironment
  68. {
  69. public:
  70. //note that order of construction/destruction is important
  71. Owned<CLocalEnvironment> c;
  72. Owned<CLocalEnvironment> env;
  73. Owned<CLocalEnvironment> constEnv;
  74. IMPLEMENT_IINTERFACE;
  75. CLockedEnvironment(CLocalEnvironment *_c)
  76. {
  77. Owned<IRemoteConnection> connection = _c->getConnection();
  78. if (connection)
  79. {
  80. constEnv.set(_c); //save original constant environment
  81. //we only wish to allow one party to allow updating the environment.
  82. //
  83. //create a new /NewEnvironment subtree, locked for read/write access for self and entire subtree; delete on disconnect
  84. //
  85. StringBuffer newName("/New");
  86. newName.append(constEnv->getPath());
  87. const unsigned int mode = RTM_CREATE | RTM_CREATE_QUERY | RTM_LOCK_READ | RTM_LOCK_WRITE |
  88. RTM_LOCK_SUB | RTM_DELETE_ON_DISCONNECT;
  89. Owned<IRemoteConnection> conn = querySDS().connect(newName.str(), myProcessSession(), mode, SDS_LOCK_TIMEOUT);
  90. if (conn == NULL)
  91. {
  92. if (environmentTraceLevel > 0)
  93. PrintLog("Failed to create locked environment %s", newName.str());
  94. throw MakeStringException(-1, "Failed to get a lock on environment /%s", newName.str());
  95. }
  96. //save the locked environment
  97. env.setown(new CLocalEnvironment(conn, NULL, newName.str()));
  98. //get a lock on the const environment
  99. const unsigned int mode2 = RTM_CREATE_QUERY | RTM_LOCK_READ | RTM_LOCK_WRITE | RTM_LOCK_SUB;
  100. Owned<IRemoteConnection> conn2 = querySDS().connect(constEnv->getPath(), myProcessSession(), mode2, SDS_LOCK_TIMEOUT);
  101. if (conn2 == NULL)
  102. {
  103. if (environmentTraceLevel > 0)
  104. PrintLog("Failed to lock environment %s", constEnv->getPath());
  105. throw MakeStringException(-1, "Failed to get a lock on environment /%s", constEnv->getPath());
  106. }
  107. //copy const environment to our member environment
  108. Owned<IPropertyTree> pSrc = conn2->getRoot();
  109. c.setown( new CLocalEnvironment(NULL, createPTreeFromIPT(pSrc)));
  110. conn2->rollback();
  111. }
  112. else
  113. {
  114. c.set(_c);
  115. }
  116. }
  117. virtual ~CLockedEnvironment()
  118. {
  119. }
  120. virtual IStringVal & getName(IStringVal & str) const
  121. { return c->getName(str); }
  122. virtual IStringVal & getXML(IStringVal & str) const
  123. { return c->getXML(str); }
  124. virtual IPropertyTree & getPTree() const
  125. {
  126. return c->getPTree();
  127. }
  128. virtual IConstDomainInfo * getDomain(const char * name) const
  129. { return c->getDomain(name); }
  130. virtual IConstMachineInfo * getMachine(const char * name) const
  131. { return c->getMachine(name); }
  132. virtual IConstMachineInfo * getMachineByAddress(const char * name) const
  133. { return c->getMachineByAddress(name); }
  134. virtual IConstInstanceInfo * getInstance(const char *type, const char *version, const char *domain) const
  135. { return c->getInstance(type, version, domain); }
  136. virtual bool getRunInfo(IStringVal & path, IStringVal & dir, const char *type, const char *version, const char *machineaddr,const char *defprogname) const
  137. { return c->getRunInfo(path, dir, type, version, machineaddr, defprogname); }
  138. virtual IConstComputerTypeInfo * getComputerType(const char * name) const
  139. { return c->getComputerType(name); }
  140. virtual IEnvironment & lock() const
  141. { ((CInterface*)this)->Link(); return *(IEnvironment*)this; }
  142. virtual void commit();
  143. virtual void rollback();
  144. virtual void setXML(const char * pstr)
  145. { c->setXML(pstr); }
  146. virtual void preload()
  147. { c->preload(); }
  148. virtual bool isConstEnvironment() const { return false; }
  149. virtual void clearCache() { c->clearCache(); }
  150. };
  151. void CLockedEnvironment::commit()
  152. {
  153. if (constEnv)
  154. {
  155. //get a lock on const environment momentarily
  156. const unsigned int mode2 = RTM_CREATE_QUERY | RTM_LOCK_READ | RTM_LOCK_WRITE | RTM_LOCK_SUB;
  157. Owned<IRemoteConnection> conn2 = querySDS().connect(constEnv->getPath(), myProcessSession(), mode2, SDS_LOCK_TIMEOUT);
  158. if (conn2 == NULL)
  159. {
  160. if (environmentTraceLevel > 0)
  161. PrintLog("Failed to lock environment %s", constEnv->getPath());
  162. throw MakeStringException(-1, "Failed to get a lock on environment /%s", constEnv->getPath());
  163. }
  164. //copy locked environment to const environment
  165. Owned<IPropertyTree> pSrc = &getPTree();
  166. Owned<IPropertyTree> pDst = conn2->queryRoot()->getBranch(NULL);
  167. // JCS - I think it could (and would be more efficient if it had kept the original read lock connection to Env
  168. // - instead of using NewEnv as lock point, still work on copy, then changeMode of original connect
  169. // - as opposed to current scheme, where it recoonects in write mode and has to lazy fetch original env to update.
  170. // ensures pDst is equal to pSrc, whilst minimizing changes to pDst
  171. try { synchronizePTree(pDst, pSrc); }
  172. catch (IException *) { conn2->rollback(); throw; }
  173. conn2->commit();
  174. }
  175. else
  176. {
  177. Owned<IRemoteConnection> conn = c->getConnection();
  178. conn->commit();
  179. }
  180. }
  181. void CLockedEnvironment::rollback()
  182. {
  183. if (constEnv)
  184. {
  185. //get a lock on const environment momentarily
  186. const unsigned int mode2 = RTM_CREATE_QUERY | RTM_LOCK_READ | RTM_LOCK_WRITE | RTM_LOCK_SUB;
  187. Owned<IRemoteConnection> conn2 = querySDS().connect(constEnv->getPath(), myProcessSession(), mode2, SDS_LOCK_TIMEOUT);
  188. if (conn2 == NULL)
  189. {
  190. if (environmentTraceLevel > 0)
  191. PrintLog("Failed to lock environment %s", constEnv->getPath());
  192. throw MakeStringException(-1, "Failed to get a lock on environment /%s", constEnv->getPath());
  193. }
  194. //copy const environment to locked environment (as it stands now) again losing any changes we made
  195. Owned<IPropertyTree> pSrc = conn2->getRoot();
  196. Owned<IPropertyTree> pDst = &getPTree();
  197. pDst->removeTree( pDst->queryPropTree("Hardware") );
  198. pDst->removeTree( pDst->queryPropTree("Software") );
  199. pDst->removeTree( pDst->queryPropTree("Programs") );
  200. pDst->removeTree( pDst->queryPropTree("Data") );
  201. mergePTree(pDst, pSrc);
  202. conn2->rollback();
  203. }
  204. else
  205. {
  206. Owned<IRemoteConnection> conn = c->getConnection();
  207. conn->rollback();
  208. }
  209. }
  210. //==========================================================================================
  211. // the following class implements notification handler for subscription to dali for environment
  212. // updates by other clients and is used by environment factory below. This also serves as
  213. // a sample self-contained implementation that can be easily tailored for other purposes.
  214. //==========================================================================================
  215. class CSdsSubscription : public CInterface, implements ISDSSubscription
  216. {
  217. public:
  218. CSdsSubscription()
  219. {
  220. m_constEnvUpdated = false;
  221. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory();
  222. sub_id = envFactory->subscribe(this);
  223. }
  224. virtual ~CSdsSubscription()
  225. {
  226. /* note that ideally, we would make this class automatically
  227. unsubscribe in this destructor. However, underlying dali client
  228. layer (CDaliSubscriptionManagerStub) links to this object and so
  229. object would not get destroyed just by an application releasing it.
  230. The application either needs to explicitly unsubscribe or close
  231. the environment which unsubscribes during close down. */
  232. }
  233. void unsubscribe()
  234. {
  235. synchronized block(m_mutexEnv);
  236. if (sub_id)
  237. {
  238. Owned<IEnvironmentFactory> m_envFactory = getEnvironmentFactory();
  239. m_envFactory->unsubscribe(sub_id);
  240. sub_id = 0;
  241. }
  242. }
  243. IMPLEMENT_IINTERFACE;
  244. //another client (like configenv) may have updated the environment and we got notified
  245. //(thanks to our subscription) but don't just reload it yet since this notification is sent on
  246. //another thread asynchronously and we may be actively working with the old environment. Just
  247. //invoke handleEnvironmentChange() when we are ready to invalidate cache in environment factory.
  248. //
  249. void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen=0, const void *valueData=NULL)
  250. {
  251. DBGLOG("Environment was updated by another client of Dali server. Invalidating cache.\n");
  252. synchronized block(m_mutexEnv);
  253. m_constEnvUpdated = true;
  254. }
  255. void handleEnvironmentChange()
  256. {
  257. synchronized block(m_mutexEnv);
  258. if (m_constEnvUpdated)
  259. {
  260. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory();
  261. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  262. constEnv->clearCache();
  263. m_constEnvUpdated = false;
  264. }
  265. }
  266. private:
  267. SubscriptionId sub_id;
  268. Mutex m_mutexEnv;
  269. bool m_constEnvUpdated;
  270. };
  271. //==========================================================================================
  272. class CEnvironmentFactory : public CInterface,
  273. implements IEnvironmentFactory, implements IDaliClientShutdown
  274. {
  275. public:
  276. IMPLEMENT_IINTERFACE;
  277. MAKEValueArray(SubscriptionId, SubscriptionIDs);
  278. SubscriptionIDs subIDs;
  279. Mutex mutex;
  280. Owned<CSdsSubscription> subscription;
  281. CEnvironmentFactory()
  282. {
  283. }
  284. virtual void clientShutdown();
  285. virtual ~CEnvironmentFactory()
  286. {
  287. close(); //just in case it was not explicitly closed
  288. }
  289. virtual IConstEnvironment* openEnvironment()
  290. {
  291. synchronized procedure(mutex);
  292. if (!cache)
  293. {
  294. Owned<IRemoteConnection> conn = querySDS().connect("/Environment", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  295. if (conn)
  296. cache.setown(new CLocalEnvironment(conn));
  297. }
  298. return cache.getLink();
  299. }
  300. virtual IEnvironment* updateEnvironment()
  301. {
  302. Owned<IConstEnvironment> pConstEnv = openEnvironment();
  303. synchronized procedure(mutex);
  304. return &pConstEnv->lock();
  305. }
  306. virtual IEnvironment * loadLocalEnvironmentFile(const char * filename)
  307. {
  308. Owned<IPropertyTree> ptree = createPTreeFromXMLFile(filename);
  309. Owned<CLocalEnvironment> pLocalEnv = new CLocalEnvironment(NULL, ptree);
  310. return new CLockedEnvironment(pLocalEnv);
  311. }
  312. virtual IEnvironment * loadLocalEnvironment(const char * xml)
  313. {
  314. Owned<IPropertyTree> ptree = createPTreeFromXMLString(xml);
  315. Owned<CLocalEnvironment> pLocalEnv = new CLocalEnvironment(NULL, ptree);
  316. return new CLockedEnvironment(pLocalEnv);
  317. }
  318. void close()
  319. {
  320. SubscriptionIDs copySubIDs;
  321. {
  322. synchronized procedure(mutex);
  323. cache.clear();
  324. //save the active subscriptions in another array
  325. //so they can be unsubscribed without causing deadlock
  326. // since ~CSdsSubscription() would ask us to unsubscribe the
  327. //same requiring a mutex lock (copy is a little price for this
  328. //normally small/empty array).
  329. //
  330. ForEachItemIn(i, subIDs)
  331. copySubIDs.append(subIDs.item(i));
  332. subIDs.kill();
  333. }
  334. //now unsubscribe all outstanding subscriptions
  335. //
  336. subscription.clear();
  337. ForEachItemIn(i, copySubIDs)
  338. querySDS().unsubscribe( copySubIDs.item(i) );
  339. }
  340. virtual SubscriptionId subscribe(ISDSSubscription* pSubHandler)
  341. {
  342. SubscriptionId sub_id = querySDS().subscribe("/Environment", *pSubHandler);
  343. synchronized procedure(mutex);
  344. subIDs.append(sub_id);
  345. return sub_id;
  346. }
  347. virtual void unsubscribe(SubscriptionId sub_id)
  348. {
  349. synchronized procedure(mutex);
  350. aindex_t i = subIDs.find(sub_id);
  351. if (i != NotFound)
  352. {
  353. querySDS().unsubscribe(sub_id);
  354. subIDs.remove(i);
  355. }
  356. }
  357. virtual void validateCache()
  358. {
  359. if (!subscription)
  360. subscription.setown( new CSdsSubscription() );
  361. subscription->handleEnvironmentChange();
  362. }
  363. private:
  364. IRemoteConnection* connect(const char *xpath, unsigned flags)
  365. {
  366. return querySDS().connect(xpath, myProcessSession(), flags, SDS_LOCK_TIMEOUT);
  367. }
  368. };
  369. static CEnvironmentFactory *factory=NULL;
  370. void CEnvironmentFactory::clientShutdown()
  371. {
  372. closeEnvironment();
  373. }
  374. MODULE_INIT(INIT_PRIORITY_ENV_ENVIRONMENT)
  375. {
  376. return true;
  377. }
  378. MODULE_EXIT()
  379. {
  380. ::Release(factory);
  381. }
  382. //==========================================================================================
  383. class CConstEnvBase : public CInterface
  384. {
  385. protected:
  386. const CLocalEnvironment* env; // Not linked - would be circular....
  387. // That could cause problems
  388. Linked<IPropertyTree> root;
  389. public:
  390. CConstEnvBase(const CLocalEnvironment* _env, IPropertyTree *_root)
  391. : env(_env), root(_root)
  392. {
  393. }
  394. IStringVal& getXML(IStringVal &str) const
  395. {
  396. StringBuffer x;
  397. toXML(root->queryBranch("."), x);
  398. str.set(x.str());
  399. return str;
  400. };
  401. IStringVal& getName(IStringVal &str) const
  402. {
  403. str.set(root->queryProp("@name"));
  404. return str;
  405. }
  406. IPropertyTree& getPTree() const
  407. {
  408. return *LINK(root);
  409. }
  410. };
  411. #define IMPLEMENT_ICONSTENVBASE \
  412. virtual IStringVal& getXML(IStringVal &str) const { return CConstEnvBase::getXML(str); } \
  413. virtual IStringVal& getName(IStringVal &str) const { return CConstEnvBase::getName(str); } \
  414. virtual IPropertyTree& getPTree() const { return CConstEnvBase::getPTree(); }
  415. //==========================================================================================
  416. class CConstDomainInfo : public CConstEnvBase, implements IConstDomainInfo
  417. {
  418. public:
  419. IMPLEMENT_IINTERFACE;
  420. IMPLEMENT_ICONSTENVBASE;
  421. CConstDomainInfo(CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root) {}
  422. virtual void getAccountInfo(IStringVal &name, IStringVal &pw) const
  423. {
  424. if (root->hasProp("@username"))
  425. name.set(root->queryProp("@username"));
  426. else
  427. name.clear();
  428. if (root->hasProp("@password"))
  429. {
  430. StringBuffer pwd;
  431. decrypt(pwd, root->queryProp("@password"));
  432. pw.set(pwd.str());
  433. }
  434. else
  435. pw.clear();
  436. }
  437. virtual void getSnmpSecurityString(IStringVal & securityString) const
  438. {
  439. if (root->hasProp("@snmpSecurityString"))
  440. {
  441. StringBuffer sec_string;
  442. decrypt(sec_string, root->queryProp("@snmpSecurityString"));
  443. securityString.set(sec_string.str());
  444. }
  445. else
  446. securityString.set("");
  447. }
  448. virtual void getSSHAccountInfo(IStringVal &name, IStringVal &sshKeyFile, IStringVal& sshKeyPassphrase) const
  449. {
  450. if (root->hasProp("@username"))
  451. name.set(root->queryProp("@username"));
  452. else
  453. name.clear();
  454. if (root->hasProp("@sshKeyFile"))
  455. sshKeyFile.set(root->queryProp("@sshKeyFile"));
  456. else
  457. sshKeyFile.clear();
  458. if (root->hasProp("@sshKeyPassphrase"))
  459. sshKeyPassphrase.set(root->queryProp("@sshKeyPassphrase"));
  460. else
  461. sshKeyPassphrase.clear();
  462. }
  463. };
  464. //==========================================================================================
  465. struct mapEnums { EnvMachineOS val; const char *str; };
  466. static EnvMachineOS getEnum(IPropertyTree *p, const char *propname, mapEnums *map)
  467. {
  468. const char *v = p->queryProp(propname);
  469. if (v && *v)
  470. {
  471. while (map->str)
  472. {
  473. if (stricmp(v, map->str)==0)
  474. return map->val;
  475. map++;
  476. }
  477. throw MakeStringException(0, "Unknown operating system: \"%s\"", v);
  478. }
  479. return MachineOsUnknown;
  480. }
  481. struct mapStateEnums { EnvMachineState val; const char *str; };
  482. static EnvMachineState getEnum(IPropertyTree *p, const char *propname, mapStateEnums *map)
  483. {
  484. const char *v = p->queryProp(propname);
  485. if (v && *v)
  486. {
  487. while (map->str)
  488. {
  489. if (stricmp(v, map->str)==0)
  490. return map->val;
  491. map++;
  492. }
  493. assertex(!"Unexpected value in getEnum");
  494. }
  495. return MachineStateUnknown;
  496. }
  497. mapEnums OperatingSystems[] = {
  498. { MachineOsW2K, "W2K" },
  499. { MachineOsSolaris, "solaris" },
  500. { MachineOsLinux, "linux" },
  501. { MachineOsSize, NULL }
  502. };
  503. mapStateEnums MachineStates[] = {
  504. { MachineStateAvailable, "Available" },
  505. { MachineStateUnavailable, "Unavailable" },
  506. { MachineStateUnknown, "Unknown" }
  507. };
  508. //==========================================================================================
  509. class CConstMachineInfo : public CConstEnvBase, implements IConstMachineInfo
  510. {
  511. public:
  512. IMPLEMENT_IINTERFACE;
  513. IMPLEMENT_ICONSTENVBASE;
  514. CConstMachineInfo(CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root) {}
  515. virtual IConstDomainInfo* getDomain() const
  516. {
  517. return env->getDomain(root->queryProp("@domain"));
  518. }
  519. virtual IStringVal& getNetAddress(IStringVal &str) const
  520. {
  521. str.set(root->queryProp("@netAddress"));
  522. return str;
  523. }
  524. virtual IStringVal& getDescription(IStringVal &str) const
  525. {
  526. UNIMPLEMENTED;
  527. }
  528. virtual unsigned getNicSpeedMbitSec() const
  529. {
  530. const char * v = root->queryProp("@nicSpeed");
  531. if (v && *v)
  532. return atoi(v);
  533. Owned<IConstComputerTypeInfo> type = env->getComputerType(root->queryProp("@computerType"));
  534. if (type)
  535. return type->getNicSpeedMbitSec();
  536. return 0;
  537. }
  538. virtual EnvMachineOS getOS() const
  539. {
  540. EnvMachineOS os = getEnum(root, "@opSys", OperatingSystems);
  541. if (os != MachineOsUnknown)
  542. return os;
  543. Owned<IConstComputerTypeInfo> type = env->getComputerType(root->queryProp("@computerType"));
  544. if (type)
  545. return type->getOS();
  546. return MachineOsUnknown;
  547. }
  548. virtual EnvMachineState getState() const
  549. {
  550. return getEnum(root, "@state", MachineStates);
  551. }
  552. };
  553. //==========================================================================================
  554. class CConstComputerTypeInfo : public CConstEnvBase, implements IConstComputerTypeInfo
  555. {
  556. public:
  557. IMPLEMENT_IINTERFACE;
  558. IMPLEMENT_ICONSTENVBASE;
  559. CConstComputerTypeInfo(CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root) {}
  560. virtual EnvMachineOS getOS() const
  561. {
  562. EnvMachineOS os = getEnum(root, "@opSys", OperatingSystems);
  563. if (os != MachineOsUnknown)
  564. return os;
  565. Owned<IConstComputerTypeInfo> type = env->getComputerType(root->queryProp("@computerType"));
  566. if (type && (type.get() != this))
  567. return type->getOS();
  568. return MachineOsUnknown;
  569. }
  570. virtual unsigned getNicSpeedMbitSec() const
  571. {
  572. const char * v = root->queryProp("@nicSpeed");
  573. if (v && *v)
  574. return atoi(v);
  575. Owned<IConstComputerTypeInfo> type = env->getComputerType(root->queryProp("@computerType"));
  576. if (type && (type.get() != this))
  577. return type->getNicSpeedMbitSec();
  578. return 0;
  579. }
  580. };
  581. //==========================================================================================
  582. class CConstInstanceInfo : public CConstEnvBase, implements IConstInstanceInfo
  583. {
  584. public:
  585. IMPLEMENT_IINTERFACE;
  586. IMPLEMENT_ICONSTENVBASE;
  587. CConstInstanceInfo(const CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root)
  588. {
  589. }
  590. virtual IConstMachineInfo * getMachine() const
  591. {
  592. return env->getMachine(root->queryProp("@computer"));
  593. }
  594. virtual IStringVal & getEndPoint(IStringVal & str) const
  595. {
  596. SCMStringBuffer ep;
  597. Owned<IConstMachineInfo> machine = getMachine();
  598. if (machine)
  599. {
  600. machine->getNetAddress(ep);
  601. const char *port = root->queryProp("@port");
  602. if (port)
  603. ep.s.append(':').append(port);
  604. }
  605. str.set(ep.str());
  606. return str;
  607. }
  608. virtual IStringVal & getExecutableDirectory(IStringVal & str) const
  609. {
  610. // this is the deploy directory so uses local path separators (I suspect this call is LEGACY now)
  611. SCMStringBuffer ep;
  612. Owned<IConstMachineInfo> machine = getMachine();
  613. if (machine)
  614. {
  615. machine->getNetAddress(ep);
  616. ep.s.insert(0, PATHSEPSTR PATHSEPSTR);
  617. }
  618. ep.s.append(PATHSEPCHAR).append(root->queryProp("@directory"));
  619. str.set(ep.str());
  620. return str;
  621. }
  622. virtual bool doGetRunInfo(IStringVal & progpath, IStringVal & workdir, const char *defprogname, bool useprog) const
  623. {
  624. // this is remote path i.e. path should match *target* nodes format
  625. Owned<IConstMachineInfo> machine = getMachine();
  626. if (!machine)
  627. return false;
  628. char psep;
  629. bool appendexe;
  630. switch (machine->getOS()) {
  631. case MachineOsSolaris:
  632. case MachineOsLinux:
  633. psep = '/';
  634. appendexe = false;
  635. break;
  636. default:
  637. psep = '\\';
  638. appendexe = true;
  639. }
  640. StringBuffer tmp;
  641. const char *program = useprog?root->queryProp("@program"):NULL; // if program specified assume absolute
  642. if (!program||!*program) {
  643. SCMStringBuffer ep;
  644. machine->getNetAddress(ep);
  645. const char *dir = root->queryProp("@directory");
  646. if (dir) {
  647. if (isPathSepChar(*dir))
  648. dir++;
  649. if (!*dir)
  650. return false;
  651. tmp.append(psep).append(psep).append(ep.s).append(psep);
  652. do {
  653. if (isPathSepChar(*dir))
  654. tmp.append(psep);
  655. else
  656. tmp.append(*dir);
  657. dir++;
  658. } while (*dir);
  659. if (!isPathSepChar(tmp.charAt(tmp.length()-1)))
  660. tmp.append(psep);
  661. tmp.append(defprogname);
  662. size32_t l = strlen(defprogname);
  663. if (appendexe&&((l<5)||(stricmp(defprogname+l-4,".exe")!=0)))
  664. tmp.append(".exe");
  665. }
  666. program = tmp.str();
  667. }
  668. progpath.set(program);
  669. const char *workd = root->queryProp("@workdir"); // if program specified assume absolute
  670. workdir.set(workd?workd:"");
  671. return true;
  672. }
  673. virtual bool getRunInfo(IStringVal & progpath, IStringVal & workdir, const char *defprogname) const
  674. {
  675. return doGetRunInfo(progpath,workdir,defprogname,true);
  676. }
  677. virtual unsigned getPort() const
  678. {
  679. return root->getPropInt("@port", 0);
  680. }
  681. };
  682. #if 0
  683. //==========================================================================================
  684. class CConstProcessInfo : public CConstEnvBase, implements IConstProcessInfo
  685. {
  686. IArrayOf<IConstInstanceInfo> w;
  687. CArrayIterator it;
  688. public:
  689. IMPLEMENT_IINTERFACE;
  690. IMPLEMENT_ICONSTENVBASE;
  691. CConstProcessInfo(CLocalEnvironment *env, IPropertyTree *root) : CConstEnvBase(env, root), it(w)
  692. {
  693. Owned<IPropertyTreeIterator> _it = root->getElements("*"); // MORE - should be instance
  694. for (_it->first(); _it->isValid(); _it->next())
  695. {
  696. IPropertyTree *rp = &_it->query();
  697. w.append(*new CConstInstanceInfo(env, rp)); // CConstInstanceInfo will link rp
  698. }
  699. }
  700. bool first() { return it.first(); }
  701. bool isValid() { return it.isValid(); }
  702. bool next() { return it.next(); }
  703. IConstInstanceInfo & query() { return (IConstInstanceInfo &) it.query();}
  704. virtual IConstInstanceInfo * getInstance(const char *domain)
  705. {
  706. for (int pass=0; pass<2; pass++)
  707. ForEachItemIn(idx, w)
  708. {
  709. Owned<IConstMachineInfo> m = w.item(idx).getMachine();
  710. if (m)
  711. {
  712. Owned<IConstDomainInfo> dm = m->getDomain();
  713. if (dm)
  714. {
  715. StringBuffer thisdomain;
  716. //dm->getName(StringBufferAdaptor(thisdomain)); // confuses g++
  717. StringBufferAdaptor strval(thisdomain);
  718. dm->getName(strval);
  719. if (thisdomain.length() && strcmp(domain, thisdomain.str())==0)
  720. return LINK(&w.item(idx));
  721. }
  722. }
  723. }
  724. return NULL;
  725. }
  726. };
  727. #endif
  728. //==========================================================================================
  729. CLocalEnvironment::CLocalEnvironment(const char* environmentFile)
  730. {
  731. if (environmentFile && *environmentFile)
  732. {
  733. IPropertyTree* root = createPTreeFromXMLFile(environmentFile);
  734. if (root)
  735. p.set(root);
  736. }
  737. machineCacheBuilt = false;
  738. }
  739. CLocalEnvironment::CLocalEnvironment(IRemoteConnection *_conn, IPropertyTree* root/*=NULL*/,
  740. const char* path/*="/Environment"*/)
  741. : xPath(path)
  742. {
  743. conn.set(_conn);
  744. if (root)
  745. p.set(root);
  746. else
  747. p.setown(conn->getRoot());
  748. machineCacheBuilt = false;
  749. }
  750. CLocalEnvironment::~CLocalEnvironment()
  751. {
  752. if (conn)
  753. conn->rollback();
  754. }
  755. IEnvironment& CLocalEnvironment::lock() const
  756. {
  757. return *new CLockedEnvironment((CLocalEnvironment*)this);
  758. }
  759. IStringVal & CLocalEnvironment::getName(IStringVal & str) const
  760. {
  761. synchronized procedure(safeCache);
  762. str.set(p->queryProp("@name"));
  763. return str;
  764. }
  765. IStringVal & CLocalEnvironment::getXML(IStringVal & str) const
  766. {
  767. StringBuffer xml;
  768. {
  769. synchronized procedure(safeCache);
  770. toXML(p->queryBranch("."), xml);
  771. }
  772. str.set(xml.str());
  773. return str;
  774. }
  775. IPropertyTree & CLocalEnvironment::getPTree() const
  776. {
  777. synchronized procedure(safeCache);
  778. return *LINK(p);
  779. }
  780. IConstEnvBase * CLocalEnvironment::getCache(const char *path) const
  781. {
  782. IConstEnvBase * ret = cache.getValue(path);
  783. ::Link(ret);
  784. return ret;
  785. }
  786. void CLocalEnvironment::setCache(const char *path, IConstEnvBase *value) const
  787. {
  788. cache.setValue(path, value);
  789. }
  790. IConstDomainInfo * CLocalEnvironment::getDomain(const char * name) const
  791. {
  792. if (!name)
  793. return NULL;
  794. StringBuffer xpath;
  795. xpath.appendf("Hardware/Domain[@name=\"%s\"]", name);
  796. synchronized procedure(safeCache);
  797. IConstEnvBase *cached = getCache(xpath.str());
  798. if (!cached)
  799. {
  800. IPropertyTree *d = p->queryPropTree(xpath.str());
  801. if (!d)
  802. return NULL;
  803. cached = new CConstDomainInfo((CLocalEnvironment *) this, d);
  804. setCache(xpath.str(), cached);
  805. }
  806. return (IConstDomainInfo *) cached;
  807. }
  808. void CLocalEnvironment::buildMachineCache() const
  809. {
  810. synchronized procedure(safeCache);
  811. if (!machineCacheBuilt)
  812. {
  813. Owned<IPropertyTreeIterator> it = p->getElements("Hardware/Computer");
  814. ForEach(*it)
  815. {
  816. const char *name = it->query().queryProp("@name");
  817. if (name)
  818. {
  819. StringBuffer x("Hardware/Computer[@name=\"");
  820. x.append(name).append("\"]");
  821. Owned<IConstEnvBase> cached = new CConstMachineInfo((CLocalEnvironment *) this, &it->query());
  822. cache.setValue(x.str(), cached);
  823. }
  824. name = it->query().queryProp("@netAddress");
  825. if (name)
  826. {
  827. StringBuffer x("Hardware/Computer[@netAddress=\"");
  828. x.append(name).append("\"]");
  829. Owned<IConstEnvBase> cached = new CConstMachineInfo((CLocalEnvironment *) this, &it->query());
  830. cache.setValue(x.str(), cached);
  831. }
  832. }
  833. machineCacheBuilt = true;
  834. }
  835. }
  836. IConstComputerTypeInfo * CLocalEnvironment::getComputerType(const char * name) const
  837. {
  838. if (!name)
  839. return NULL;
  840. StringBuffer xpath;
  841. xpath.appendf("Hardware/ComputerType[@name=\"%s\"]", name);
  842. synchronized procedure(safeCache);
  843. IConstEnvBase *cached = getCache(xpath.str());
  844. if (!cached)
  845. {
  846. IPropertyTree *d = p->queryPropTree(xpath.str());
  847. if (!d)
  848. return NULL;
  849. cached = new CConstComputerTypeInfo((CLocalEnvironment *) this, d);
  850. setCache(xpath.str(), cached);
  851. }
  852. return (CConstComputerTypeInfo *) cached;
  853. }
  854. IConstMachineInfo * CLocalEnvironment::getMachine(const char * name) const
  855. {
  856. if (!name)
  857. return NULL;
  858. buildMachineCache();
  859. StringBuffer xpath;
  860. xpath.appendf("Hardware/Computer[@name=\"%s\"]", name);
  861. synchronized procedure(safeCache);
  862. IConstEnvBase *cached = getCache(xpath.str());
  863. if (!cached)
  864. {
  865. IPropertyTree *d = p->queryPropTree(xpath.str());
  866. if (!d)
  867. return NULL;
  868. cached = new CConstMachineInfo((CLocalEnvironment *) this, d);
  869. setCache(xpath.str(), cached);
  870. }
  871. return (CConstMachineInfo *) cached;
  872. }
  873. IConstMachineInfo * CLocalEnvironment::getMachineByAddress(const char * name) const
  874. {
  875. if (!name)
  876. return NULL;
  877. buildMachineCache();
  878. Owned<IPropertyTreeIterator> iter;
  879. StringBuffer xpath;
  880. xpath.appendf("Hardware/Computer[@netAddress=\"%s\"]", name);
  881. synchronized procedure(safeCache);
  882. IConstEnvBase *cached = getCache(xpath.str());
  883. if (!cached)
  884. {
  885. IPropertyTree *d = p->queryPropTree(xpath.str());
  886. if (!d) {
  887. // I suspect not in the original spirit of this but look for resolved IP
  888. Owned<IPropertyTreeIterator> iter = p->getElements("Hardware/Computer");
  889. IpAddress ip;
  890. ip.ipset(name);
  891. ForEach(*iter) {
  892. IPropertyTree &computer = iter->query();
  893. IpAddress ip2;
  894. const char *ips = computer.queryProp("@netAddress");
  895. if (ips&&*ips) {
  896. ip2.ipset(ips);
  897. if (ip.ipequals(ip2)) {
  898. d = &computer;
  899. break;
  900. }
  901. }
  902. }
  903. }
  904. if (!d)
  905. return NULL;
  906. StringBuffer xpath1;
  907. xpath1.appendf("Hardware/Computer[@name=\"%s\"]", d->queryProp("@name"));
  908. cached = getCache(xpath1.str());
  909. if (!cached)
  910. {
  911. cached = new CConstMachineInfo((CLocalEnvironment *) this, d);
  912. setCache(xpath1.str(), cached);
  913. setCache(xpath.str(), cached);
  914. }
  915. }
  916. return (CConstMachineInfo *) cached;
  917. }
  918. IConstInstanceInfo * CLocalEnvironment::getInstance(const char *type, const char *version, const char *domain) const
  919. {
  920. StringBuffer xpath("Software/");
  921. xpath.append(type);
  922. if (version)
  923. xpath.append("[@version='").append(version).append("']");
  924. xpath.append("/Instance");
  925. synchronized procedure(safeCache);
  926. Owned<IPropertyTreeIterator> _it = p->getElements(xpath);
  927. for (_it->first(); _it->isValid(); _it->next())
  928. {
  929. IPropertyTree *rp = &_it->query();
  930. Owned<CConstInstanceInfo> inst = new CConstInstanceInfo(this, rp); // CConstInstanceInfo will link rp
  931. Owned<IConstMachineInfo> m = inst->getMachine();
  932. if (m)
  933. {
  934. Owned<IConstDomainInfo> dm = m->getDomain();
  935. if (dm)
  936. {
  937. SCMStringBuffer thisdomain;
  938. dm->getName(thisdomain);
  939. if (thisdomain.length() && strcmp(domain, thisdomain.str())==0)
  940. return inst.getClear();
  941. }
  942. }
  943. }
  944. return NULL;
  945. }
  946. CConstInstanceInfo * CLocalEnvironment::getInstanceByIP(const char *type, const char *version, IpAddress &ip) const
  947. {
  948. StringBuffer xpath("Software/");
  949. xpath.append(type);
  950. if (version)
  951. xpath.append("[@version='").append(version).append("']");
  952. xpath.append("/Instance");
  953. synchronized procedure(safeCache);
  954. assertex(p);
  955. Owned<IPropertyTreeIterator> _it = p->getElements(xpath);
  956. assertex(_it);
  957. for (_it->first(); _it->isValid(); _it->next())
  958. {
  959. IPropertyTree *rp = &_it->query();
  960. assertex(rp);
  961. Owned<CConstInstanceInfo> inst = new CConstInstanceInfo(this, rp); // CConstInstanceInfo will link rp
  962. Owned<IConstMachineInfo> m = inst->getMachine();
  963. if (m)
  964. {
  965. SCMStringBuffer eps;
  966. m->getNetAddress(eps);
  967. SocketEndpoint ep(eps.str());
  968. if (ep.ipequals(ip))
  969. return inst.getClear();
  970. }
  971. }
  972. return NULL;
  973. }
  974. void CLocalEnvironment::unlockRemote()
  975. {
  976. #if 0
  977. conn->commit(true);
  978. conn->changeMode(0, SDS_LOCK_TIMEOUT);
  979. #else
  980. if (conn)
  981. {
  982. synchronized procedure(safeCache);
  983. p.clear();
  984. conn.setown(querySDS().connect(xPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT));
  985. p.setown(conn->getRoot());
  986. }
  987. #endif
  988. }
  989. void CLocalEnvironment::preload()
  990. {
  991. synchronized procedure(safeCache);
  992. p->queryBranch(".");
  993. }
  994. void CLocalEnvironment::setXML(const char *xml)
  995. {
  996. Owned<IPropertyTree> newRoot = createPTreeFromXMLString(xml);
  997. synchronized procedure(safeCache);
  998. Owned<IPropertyTreeIterator> it = p->getElements("*");
  999. ForEach(*it)
  1000. {
  1001. p->removeTree(&it->query());
  1002. }
  1003. it.setown(newRoot->getElements("*"));
  1004. ForEach(*it)
  1005. {
  1006. IPropertyTree *sub = &it->get();
  1007. p->addPropTree(sub->queryName(), sub);
  1008. }
  1009. }
  1010. bool CLocalEnvironment::getRunInfo(IStringVal & path, IStringVal & dir, const char * tag, const char * version, const char *machineaddr, const char *defprogname) const
  1011. {
  1012. try
  1013. {
  1014. // PrintLog("getExecutablePath %s %s %s", tag, version, machineaddr);
  1015. // first see if local machine with deployed on
  1016. SocketEndpoint ep(machineaddr);
  1017. Owned<CConstInstanceInfo> ipinstance = getInstanceByIP(tag, version, ep);
  1018. if (ipinstance)
  1019. {
  1020. StringAttr testpath;
  1021. StringAttrAdaptor teststrval(testpath);
  1022. if (ipinstance->doGetRunInfo(teststrval,dir,defprogname,false)) { // this returns full string
  1023. RemoteFilename rfn;
  1024. rfn.setRemotePath(testpath.get());
  1025. Owned<IFile> file = createIFile(rfn);
  1026. if (file->exists()) {
  1027. StringBuffer tmp;
  1028. rfn.getLocalPath(tmp);
  1029. path.set(tmp.str());
  1030. return true;
  1031. }
  1032. }
  1033. }
  1034. Owned<IConstMachineInfo> machine = getMachineByAddress(machineaddr);
  1035. if (!machine)
  1036. {
  1037. LOG(MCdebugInfo, unknownJob, "Unable to find machine for %s", machineaddr);
  1038. return false;
  1039. }
  1040. StringAttr targetdomain;
  1041. Owned<IConstDomainInfo> domain = machine->getDomain();
  1042. if (!domain)
  1043. {
  1044. LOG(MCdebugInfo, unknownJob, "Unable to find domain for %s", machineaddr);
  1045. return false;
  1046. }
  1047. //domain->getName(StringAttrAdaptor(targetdomain)); // confuses g++
  1048. StringAttrAdaptor strval(targetdomain);
  1049. domain->getName(strval);
  1050. Owned<IConstInstanceInfo> instance = getInstance(tag, version, targetdomain);
  1051. if (!instance)
  1052. {
  1053. LOG(MCdebugInfo, unknownJob, "Unable to find process %s for domain %s", tag, targetdomain.get());
  1054. return false;
  1055. }
  1056. return instance->getRunInfo(path,dir,defprogname);
  1057. }
  1058. catch (IException * e)
  1059. {
  1060. EXCLOG(e, "Extracting slave version");
  1061. e->Release();
  1062. return false;
  1063. }
  1064. }
  1065. void CLocalEnvironment::clearCache()
  1066. {
  1067. synchronized procedure(safeCache);
  1068. if (conn) {
  1069. p.clear();
  1070. conn->reload();
  1071. p.setown(conn->getRoot());
  1072. }
  1073. cache.kill();
  1074. machineCacheBuilt = false;
  1075. resetPasswordsFromSDS();
  1076. }
  1077. //==========================================================================================
  1078. static CriticalSection getEnvSect;
  1079. extern ENVIRONMENT_API IEnvironmentFactory * getEnvironmentFactory()
  1080. {
  1081. CriticalBlock block(getEnvSect);
  1082. if (!factory)
  1083. {
  1084. factory = new CEnvironmentFactory();
  1085. addShutdownHook(*factory);
  1086. }
  1087. return LINK(factory);
  1088. }
  1089. extern ENVIRONMENT_API void closeEnvironment()
  1090. {
  1091. try
  1092. {
  1093. CEnvironmentFactory* pFactory;
  1094. {
  1095. //this method is not meant to be invoked by multiple
  1096. //threads concurrently but just in case...
  1097. CriticalBlock block(getEnvSect);
  1098. pFactory = factory;
  1099. factory = NULL;
  1100. }
  1101. clearPasswordsFromSDS();
  1102. if (pFactory)
  1103. {
  1104. removeShutdownHook(*pFactory);
  1105. pFactory->close();
  1106. pFactory->Release();
  1107. }
  1108. }
  1109. catch (IException *e)
  1110. {
  1111. EXCLOG(e);
  1112. }
  1113. }