Switch to scoped_ptr/swap pattern
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / XMLMetadataProvider.cpp
index 2f410bd..5273bac 100644 (file)
@@ -1,17 +1,21 @@
-/*
- *  Copyright 2001-2010 Internet2
+/**
+ * Licensed to the University Corporation for Advanced Internet
+ * Development, Inc. (UCAID) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
  *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * UCAID licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the
+ * License at
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific
+ * language governing permissions and limitations under the License.
  */
 
 /**
 #include "saml2/metadata/DiscoverableMetadataProvider.h"
 
 #include <fstream>
+#include <boost/scoped_ptr.hpp>
 #include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/io/HTTPResponse.h>
+#include <xmltooling/util/DateTime.h>
 #include <xmltooling/util/NDC.h>
 #include <xmltooling/util/PathResolver.h>
 #include <xmltooling/util/ReloadableXMLFile.h>
 #include <xmltooling/util/Threads.h>
 #include <xmltooling/validation/ValidatorSuite.h>
 
+#if defined(OPENSAML_LOG4SHIB)
+# include <log4shib/NDC.hh>
+#elif defined(OPENSAML_LOG4CPP)
+# include <log4cpp/NDC.hh>
+#endif
+
 using namespace opensaml::saml2md;
 using namespace xmltooling::logging;
 using namespace xmltooling;
+using namespace boost;
 using namespace std;
 
 #if defined (_MSC_VER)
@@ -57,22 +70,62 @@ namespace opensaml {
 
             virtual ~XMLMetadataProvider() {
                 shutdown();
-                delete m_object;
             }
 
             void init() {
                 try {
+                    if (!m_id.empty()) {
+                        string threadid("[");
+                        threadid += m_id + ']';
+                        logging::NDC::push(threadid);
+                    }
                     background_load();
                     startup();
                 }
                 catch (...) {
                     startup();
+                    if (!m_id.empty()) {
+                        logging::NDC::pop();
+                    }
                     throw;
                 }
+
+                if (!m_id.empty()) {
+                    logging::NDC::pop();
+                }
+            }
+
+            const char* getId() const {
+                return m_id.c_str();
+            }
+
+            void outputStatus(ostream& os) const {
+                os << "<MetadataProvider";
+
+                if (getId() && *getId()) {
+                    os << " id='" << getId() << "'";
+                }
+
+                if (!m_source.empty()) {
+                    os << " source='" << m_source << "'";
+                }
+
+                if (m_lastUpdate > 0) {
+                    DateTime ts(m_lastUpdate);
+                    ts.parseDateTime();
+                    auto_ptr_char timestamp(ts.getFormattedString());
+                    os << " lastUpdate='" << timestamp.get() << "'";
+                }
+
+                if (!m_local && m_reloadInterval > 0) {
+                    os << " reloadInterval='" << m_reloadInterval << "'";
+                }
+
+                os << "/>";
             }
 
             const XMLObject* getMetadata() const {
-                return m_object;
+                return m_object.get();
             }
 
         protected:
@@ -84,7 +137,7 @@ namespace opensaml {
             void index(time_t& validUntil);
             time_t computeNextRefresh();
 
-            XMLObject* m_object;
+            scoped_ptr<XMLObject> m_object;
             bool m_discoveryFeed;
             double m_refreshDelayFactor;
             unsigned int m_backoffFactor;
@@ -107,8 +160,9 @@ namespace opensaml {
 #endif
 
 XMLMetadataProvider::XMLMetadataProvider(const DOMElement* e)
-    : AbstractMetadataProvider(e), DiscoverableMetadataProvider(e), ReloadableXMLFile(e, Category::getInstance(SAML_LOGCAT".MetadataProvider.XML"), false),
-        m_object(nullptr), m_discoveryFeed(XMLHelper::getAttrBool(e, true, discoveryFeed)),
+    : MetadataProvider(e), AbstractMetadataProvider(e), DiscoverableMetadataProvider(e),
+        ReloadableXMLFile(e, Category::getInstance(SAML_LOGCAT".MetadataProvider.XML"), false),
+        m_discoveryFeed(XMLHelper::getAttrBool(e, true, discoveryFeed)),
         m_refreshDelayFactor(0.75), m_backoffFactor(1),
         m_minRefreshDelay(XMLHelper::getAttrInt(e, 600, minRefreshDelay)),
         m_maxRefreshDelay(m_reloadInterval), m_lastValidUntil(SAMLTIME_MAX)
@@ -125,7 +179,7 @@ XMLMetadataProvider::XMLMetadataProvider(const DOMElement* e)
         }
 
         if (m_minRefreshDelay > m_maxRefreshDelay) {
-            m_log.error("minRefreshDelay setting exceeds maxRefreshDelay/refreshInterval setting, lowering to match it");
+            m_log.warn("minRefreshDelay setting exceeds maxRefreshDelay/reloadInterval setting, lowering to match it");
             m_minRefreshDelay = m_maxRefreshDelay;
         }
     }
@@ -133,8 +187,10 @@ XMLMetadataProvider::XMLMetadataProvider(const DOMElement* e)
 
 pair<bool,DOMElement*> XMLMetadataProvider::load(bool backup)
 {
-    // Lower the refresh rate in case of an error.
-    m_reloadInterval = m_minRefreshDelay;
+    if (!backup) {
+        // Lower the refresh rate in case of an error.
+        m_reloadInterval = m_minRefreshDelay;
+    }
 
     // Call the base class to load/parse the appropriate XML resource.
     pair<bool,DOMElement*> raw = ReloadableXMLFile::load(backup);
@@ -143,7 +199,7 @@ pair<bool,DOMElement*> XMLMetadataProvider::load(bool backup)
     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
 
     // Unmarshall objects, binding the document.
-    auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(raw.second, true));
+    scoped_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(raw.second, true));
     docjanitor.release();
 
     if (!dynamic_cast<const EntitiesDescriptor*>(xmlObject.get()) && !dynamic_cast<const EntityDescriptor*>(xmlObject.get()))
@@ -178,7 +234,7 @@ pair<bool,DOMElement*> XMLMetadataProvider::load(bool backup)
     }
 
     try {
-        doFilters(*xmlObject.get());
+        doFilters(*xmlObject);
     }
     catch (exception&) {
         if (!backupKey.empty())
@@ -203,20 +259,20 @@ pair<bool,DOMElement*> XMLMetadataProvider::load(bool backup)
         m_lock->wrlock();
     SharedLock locker(m_lock, false);
     bool changed = m_object!=nullptr;
-    delete m_object;
-    m_object = xmlObject.release();
+    m_object.swap(xmlObject);
     m_lastValidUntil = SAMLTIME_MAX;
     index(m_lastValidUntil);
     if (m_discoveryFeed)
         generateFeed();
     if (changed)
         emitChangeEvent();
+    m_lastUpdate = time(nullptr);
 
     // Tracking cacheUntil through the tree is TBD, but
     // validUntil is the tightest interval amongst the children.
 
-    // If a remote resource, adjust the reload interval.
-    if (!backup && !m_local) {
+    // If a remote resource that's monitored, adjust the reload interval.
+    if (!backup && !m_local && m_lock) {
         m_backoffFactor = 1;
         m_reloadInterval = computeNextRefresh();
         m_log.info("adjusted reload interval to %d seconds", m_reloadInterval);
@@ -272,7 +328,7 @@ time_t XMLMetadataProvider::computeNextRefresh()
     else {
         // Compute the smaller of the validUntil / cacheDuration constraints.
         time_t ret = m_lastValidUntil - now;
-        const CacheableSAMLObject* cacheable = dynamic_cast<const CacheableSAMLObject*>(m_object);
+        const CacheableSAMLObject* cacheable = dynamic_cast<const CacheableSAMLObject*>(m_object.get());
         if (cacheable && cacheable->getCacheDuration())
             ret = min(ret, cacheable->getCacheDurationEpoch());
             
@@ -292,10 +348,10 @@ time_t XMLMetadataProvider::computeNextRefresh()
 void XMLMetadataProvider::index(time_t& validUntil)
 {
     clearDescriptorIndex();
-    EntitiesDescriptor* group=dynamic_cast<EntitiesDescriptor*>(m_object);
+    EntitiesDescriptor* group = dynamic_cast<EntitiesDescriptor*>(m_object.get());
     if (group) {
         indexGroup(group, validUntil);
         return;
     }
-    indexEntity(dynamic_cast<EntityDescriptor*>(m_object), validUntil);
+    indexEntity(dynamic_cast<EntityDescriptor*>(m_object.get()), validUntil);
 }