Xerces 3 revisions.
[shibboleth/cpp-xmltooling.git] / xmltooling / util / ReloadableXMLFile.cpp
1 /*\r
2  *  Copyright 2001-2007 Internet2\r
3  * \r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 /**\r
18  * @file ReloadableXMLFile.cpp\r
19  * \r
20  * Base class for file-based XML configuration.\r
21  */\r
22 \r
23 #include "internal.h"\r
24 #include "util/NDC.h"\r
25 #include "util/PathResolver.h"\r
26 #include "util/ReloadableXMLFile.h"\r
27 #include "util/XMLConstants.h"\r
28 #include "util/XMLHelper.h"\r
29 \r
30 #include <fstream>\r
31 #include <sys/types.h>\r
32 #include <sys/stat.h>\r
33 \r
34 #include <xercesc/framework/LocalFileInputSource.hpp>\r
35 #include <xercesc/framework/Wrapper4InputSource.hpp>\r
36 #include <xercesc/framework/URLInputSource.hpp>\r
37 #include <xercesc/util/XMLUniDefs.hpp>\r
38 \r
39 using namespace xmltooling::logging;\r
40 using namespace xmltooling;\r
41 using namespace xercesc;\r
42 using namespace std;\r
43 \r
44 static const XMLCh uri[] =              UNICODE_LITERAL_3(u,r,i);\r
45 static const XMLCh url[] =              UNICODE_LITERAL_3(u,r,l);\r
46 static const XMLCh path[] =             UNICODE_LITERAL_4(p,a,t,h);\r
47 static const XMLCh pathname[] =         UNICODE_LITERAL_8(p,a,t,h,n,a,m,e);\r
48 static const XMLCh file[] =             UNICODE_LITERAL_4(f,i,l,e);\r
49 static const XMLCh filename[] =         UNICODE_LITERAL_8(f,i,l,e,n,a,m,e);\r
50 static const XMLCh validate[] =         UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);\r
51 static const XMLCh reloadChanges[] =    UNICODE_LITERAL_13(r,e,l,o,a,d,C,h,a,n,g,e,s);\r
52 static const XMLCh reloadInterval[] =   UNICODE_LITERAL_14(r,e,l,o,a,d,I,n,t,e,r,v,a,l);\r
53 static const XMLCh backingFilePath[] =  UNICODE_LITERAL_15(b,a,c,k,i,n,g,F,i,l,e,P,a,t,h);\r
54 \r
55 ReloadableXMLFile::ReloadableXMLFile(const DOMElement* e, Category& log)\r
56     : m_root(e), m_local(true), m_validate(false), m_filestamp(0), m_reloadInterval(0), m_lock(NULL), m_log(log)\r
57 {\r
58 #ifdef _DEBUG\r
59     NDC ndc("ReloadableXMLFile");\r
60 #endif\r
61 \r
62     // Establish source of data...\r
63     const XMLCh* source=e->getAttributeNS(NULL,uri);\r
64     if (!source || !*source) {\r
65         source=e->getAttributeNS(NULL,url);\r
66         if (!source || !*source) {\r
67             source=e->getAttributeNS(NULL,path);\r
68             if (!source || !*source) {\r
69                 source=e->getAttributeNS(NULL,pathname);\r
70                 if (!source || !*source) {\r
71                     source=e->getAttributeNS(NULL,file);\r
72                     if (!source || !*source) {\r
73                         source=e->getAttributeNS(NULL,filename);\r
74                     }\r
75                 }\r
76             }\r
77         }\r
78         else\r
79             m_local=false;\r
80     }\r
81     else\r
82         m_local=false;\r
83     \r
84     if (source && *source) {\r
85         const XMLCh* flag=e->getAttributeNS(NULL,validate);\r
86         m_validate=(XMLString::equals(flag,xmlconstants::XML_TRUE) || XMLString::equals(flag,xmlconstants::XML_ONE));\r
87 \r
88         auto_ptr_char temp(source);\r
89         m_source=temp.get();\r
90         \r
91         if (!m_local && !strstr(m_source.c_str(),"://")) {\r
92             log.warn("deprecated usage of uri/url attribute for a local resource, use path instead");\r
93             m_local=true;\r
94         }\r
95 \r
96         if (m_local) {\r
97             XMLToolingConfig::getConfig().getPathResolver()->resolve(m_source, PathResolver::XMLTOOLING_CFG_FILE);\r
98 \r
99             flag=e->getAttributeNS(NULL,reloadChanges);\r
100             if (!XMLString::equals(flag,xmlconstants::XML_FALSE) && !XMLString::equals(flag,xmlconstants::XML_ZERO)) {\r
101 #ifdef WIN32\r
102                 struct _stat stat_buf;\r
103                 if (_stat(m_source.c_str(), &stat_buf) == 0)\r
104 #else\r
105                 struct stat stat_buf;\r
106                 if (stat(m_source.c_str(), &stat_buf) == 0)\r
107 #endif\r
108                     m_filestamp=stat_buf.st_mtime;\r
109                 else\r
110                     throw IOException("Unable to access local file ($1)", params(1,m_source.c_str()));\r
111                 m_lock=RWLock::create();\r
112             }\r
113             log.debug("using local resource (%s), will %smonitor for changes", m_source.c_str(), m_lock ? "" : "not ");\r
114         }\r
115         else {\r
116             log.debug("using remote resource (%s)", m_source.c_str());\r
117             source = e->getAttributeNS(NULL,backingFilePath);\r
118             if (source && *source) {\r
119                 auto_ptr_char temp2(source);\r
120                 m_backing=temp2.get();\r
121                 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_backing, PathResolver::XMLTOOLING_RUN_FILE);\r
122                 log.debug("backup remote resource with (%s)", m_backing.c_str());\r
123             }\r
124             source = e->getAttributeNS(NULL,reloadInterval);\r
125             if (source && *source) {\r
126                 m_reloadInterval = XMLString::parseInt(source);\r
127                 if (m_reloadInterval > 0) {\r
128                     m_log.debug("will reload remote resource at most every %d seconds", m_reloadInterval);\r
129                     m_lock=RWLock::create();\r
130                 }\r
131             }\r
132             m_filestamp = time(NULL);   // assume it gets loaded initially\r
133         }\r
134     }\r
135     else {\r
136         log.debug("no resource uri/path/name supplied, will load inline configuration");\r
137     }\r
138 }\r
139 \r
140 pair<bool,DOMElement*> ReloadableXMLFile::load(bool backup)\r
141 {\r
142 #ifdef _DEBUG\r
143     NDC ndc("init");\r
144 #endif\r
145 \r
146     try {\r
147         if (m_source.empty()) {\r
148             // Data comes from the DOM we were handed.\r
149             m_log.debug("loading inline configuration...");\r
150             return make_pair(false,XMLHelper::getFirstChildElement(m_root));\r
151         }\r
152         else {\r
153             // Data comes from a file we have to parse.\r
154             if (backup)\r
155                 m_log.warn("using local backup of remote resource");\r
156             else\r
157                 m_log.debug("loading configuration from external resource...");\r
158 \r
159             DOMDocument* doc=NULL;\r
160             auto_ptr_XMLCh widenit(backup ? m_backing.c_str() : m_source.c_str());\r
161             if (m_local || backup) {\r
162                 LocalFileInputSource src(widenit.get());\r
163                 Wrapper4InputSource dsrc(&src,false);\r
164                 if (m_validate)\r
165                     doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);\r
166                 else\r
167                     doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
168             }\r
169             else {\r
170                 URLInputSource src(widenit.get());\r
171                 Wrapper4InputSource dsrc(&src,false);\r
172                 if (m_validate)\r
173                     doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);\r
174                 else\r
175                     doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
176             }\r
177 \r
178             m_log.infoStream() << "loaded XML resource (" << (backup ? m_backing : m_source) << ")" << logging::eol;\r
179 \r
180             if (!backup && !m_backing.empty()) {\r
181                 m_log.debug("backing up remote resource to (%s)", m_backing.c_str());\r
182                 try {\r
183                     ofstream backer(m_backing.c_str());\r
184                     backer << *(doc->getDocumentElement());\r
185                 }\r
186                 catch (exception& ex) {\r
187                     m_log.crit("exception while backing up resource: %s", ex.what());\r
188                 }\r
189             }\r
190 \r
191             return make_pair(true,doc->getDocumentElement());\r
192         }\r
193     }\r
194     catch (XMLException& e) {\r
195         auto_ptr_char msg(e.getMessage());\r
196         m_log.errorStream() << "Xerces error while loading resource (" << (backup ? m_backing : m_source) << "): "\r
197             << msg.get() << logging::eol;\r
198         if (!backup && !m_backing.empty())\r
199             return load(true);\r
200         throw XMLParserException(msg.get());\r
201     }\r
202     catch (exception& e) {\r
203         m_log.errorStream() << "error while loading configuration from ("\r
204             << (m_source.empty() ? "inline" : (backup ? m_backing : m_source)) << "): " << e.what() << logging::eol;\r
205         if (!backup && !m_backing.empty())\r
206             return load(true);\r
207         throw;\r
208     }\r
209 }\r
210 \r
211 Lockable* ReloadableXMLFile::lock()\r
212 {\r
213     if (!m_lock)\r
214         return this;\r
215         \r
216     m_lock->rdlock();\r
217 \r
218     // Check if we need to refresh.\r
219     if (m_local) {\r
220 #ifdef WIN32\r
221         struct _stat stat_buf;\r
222         if (_stat(m_source.c_str(), &stat_buf) != 0)\r
223             return this;\r
224 #else\r
225         struct stat stat_buf;\r
226         if (stat(m_source.c_str(), &stat_buf) != 0)\r
227             return this;\r
228 #endif\r
229         if (m_filestamp>=stat_buf.st_mtime)\r
230             return this;\r
231         \r
232         // Elevate lock and recheck.\r
233         m_log.debug("timestamp of local resource changed, elevating to a write lock");\r
234         m_lock->unlock();\r
235         m_lock->wrlock();\r
236         if (m_filestamp>=stat_buf.st_mtime) {\r
237             // Somebody else handled it, just downgrade.\r
238             m_log.debug("update of local resource handled by another thread, downgrading lock");\r
239             m_lock->unlock();\r
240             m_lock->rdlock();\r
241             return this;\r
242         }\r
243 \r
244         // Update the timestamp regardless. No point in repeatedly trying.\r
245         m_filestamp=stat_buf.st_mtime;\r
246         m_log.info("change detected, reloading local resource...");\r
247     }\r
248     else {\r
249         time_t now = time(NULL);\r
250 \r
251         // Time to reload? If we have no data, filestamp is zero\r
252         // and there's no way current time is less than the interval.\r
253         if (now - m_filestamp < m_reloadInterval)\r
254             return this;\r
255 \r
256         // Elevate lock and recheck.\r
257         m_log.debug("reload interval for remote resource elapsed, elevating to a write lock");\r
258         m_lock->unlock();\r
259         m_lock->wrlock();\r
260         if (now - m_filestamp < m_reloadInterval) {\r
261             // Somebody else handled it, just downgrade.\r
262             m_log.debug("update of remote resource handled by another thread, downgrading lock");\r
263             m_lock->unlock();\r
264             m_lock->rdlock();\r
265             return this;\r
266         }\r
267 \r
268         m_filestamp = now;\r
269         m_log.info("reloading remote resource...");\r
270     }\r
271     \r
272     // Do this once...\r
273     try {\r
274         // At this point we're holding the write lock, so make sure we pop it.\r
275         SharedLock lockwrap(m_lock,false);\r
276         pair<bool,DOMElement*> ret=load();\r
277         if (ret.first)\r
278             ret.second->getOwnerDocument()->release();\r
279     } catch (exception& ex) {\r
280         m_log.crit("maintaining existing configuration, error reloading resource (%s): %s", m_source.c_str(), ex.what());\r
281     }\r
282     \r
283     // If we made it here, the swap may or may not have worked, but we need to relock.\r
284     m_log.debug("attempt to update resource complete, relocking");\r
285     m_lock->rdlock();\r
286     return this;\r
287 }\r