Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

Adjustments for RPM deployment

Mike McGann4306ca0e13e9
diff --git a/bin/eventsGeoRssParser.py b/bin/eventsGeoRssParser.py
new file mode 100755
index 000000000..053dbb2d9
--- /dev/null
+++ b/bin/eventsGeoRssParser.py
@@ -0,0 +1,293 @@
+#!/usr/bin/python
+
+import feedparser, logging, logging.config
+import urllib2, shutil, urlparse, os, zipfile, os.path, re, json
+import sys
+from zipfile import ZipFile as zip
+from zipfile import BadZipfile
+from bs4 import BeautifulSoup
+from osgeo import gdal
+
+baseDir = os.path.join(os.path.dirname(__file__), '..')
+
+if len(sys.argv) > 1 and sys.argv[1] == '-d':
+ print 'Development mode'
+ # Log configuration assume working from this directory
+ os.chdir(baseDir)
+ confDir = 'etc/config'
+ libDir = 'src/var/lib/worldview'
+else:
+ confDir = '/etc/worldview'
+ libDir = '/var/lib/worldview'
+
+# ===================================================================
+# Log Configuration
+# ===================================================================
+logConfFile = os.path.join(confDir, 'events_log.conf')
+if not os.path.exists(logConfFile):
+ sys.stderr.write('No such file: %s\n' % logConfFile)
+ sys.exit(1)
+logging.config.fileConfig(logConfFile)
+accessLog = logging.getLogger('eventsAccess')
+errorLog = logging.getLogger('eventsErrors')
+debugLog = logging.getLogger('eventsDebug')
+
+# ===================================================================
+# GeoRSS Processing
+# ===================================================================
+
+# Pulls the GeoRSS feed and returns a list of entries.
+# @param url - the URL of the GeoRSS feed
+# @return - an array of GeoRSS entries
+def pullRss(url):
+ feed = feedparser.parse(url)
+ if feed:
+ accessLog.info('Successful pull: %s', url)
+ return feed["items"]
+ else:
+ accessLog.info('Failed pull: %s', url)
+ return None
+
+# Find the link to the first tif image (if present).
+# @param soup - the content of the entry's story
+# @return - the link to the GeoTif image (if present)
+def findTiff(soup):
+ t = soup.find(href=re.compile("tif"))
+ if t:
+ return t.get("href")
+ else:
+ return None
+
+# Find the link to the first kmz image (if present).
+# @param soup - the content of the entry's story
+# @return - the link to the KMZ image (if present)
+def findKmz(soup):
+ k = soup.find(href=re.compile("kmz"))
+ if k:
+ return k.get("href")
+ else:
+ return None
+
+# Extract the KMZ file with the given file name.
+# @param zipname - the name of the zip file
+# @return - the relative path to the KML file
+def extractKmz(zipname):
+ try:
+ z = zip(zipname)
+ f = z.namelist()[0]
+ if f.endswith('/'):
+ os.makedirs(f)
+ else:
+ z.extract(f)
+ return f
+ except BadZipfile as e:
+ errorLog.error('(extractKmz) Bad Zipfile: %s', zipname)
+ return None
+ except OSError as e:
+ errorLog.error('(extractKmz) %s: %s', e.strerror, e.filename)
+ return None
+ except IOError as e:
+ errorLog.error('(extractKmz) %s: %s', e.strerror, e.filename)
+ return None
+
+# Download a file from the given link.
+# @param url - the link to the file (KMZ or GeoTiff)
+# @param fileName - the filename
+# @return - the filename
+def download(url, fileName=None):
+ def getFileName(url, openUrl):
+ if 'Content-Disposition' in openUrl.info():
+ # If the response has Content-Disposition, try to get the
+ # filename from it
+ cd = dict(map(
+ lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),
+ openUrl.info()['Content-Disposition'].split(';')))
+ if 'filename' in cd:
+ filename = cd['filename'].strip("\"'")
+ if filename: return filename
+
+ # if no filename was found above, parse it out of the final URL
+ filename = os.path.basename(urlparse.urlsplit(openUrl.url)[2])
+ return filename
+
+ r = urllib2.urlopen(urllib2.Request(url))
+ try:
+ fileName = fileName or getFileName(url, r)
+ with open(fileName, 'wb') as f:
+ shutil.copyfileobj(r,f)
+
+ finally:
+ r.close()
+
+
+# Parse the entry and return a JSON representation
+# @param entry - a GeoRSS entry
+# @return - a JSON description of the GeoRss entry
+def processEntry(entry):
+
+ # check satellite/instrument - if not MODIS, skip
+ if not any("tags" in n for n in entry):
+ debugLog.debug('skipping because no tags')
+ return None
+
+ tags = entry["tags"]
+ if len(tags) < 2:
+ debugLog.debug('skipping because too few tags')
+ return None
+
+ parts = tags[1].term.split("/")
+ sat = parts[0]
+ instrument = parts[1]
+ if instrument != "MODIS":
+ debugLog.debug('skipping because of instrument')
+ return None
+
+ # check for KMZ or GeoTiff - if not present, skip
+ story = entry["link"]
+ page = urllib2.urlopen(story)
+ content = BeautifulSoup(page)
+
+ # check for KMZ
+ kmzLink = findKmz(content)
+ kmzSuccess = True
+ if kmzLink:
+ temp_kmz = "temp_kmz"
+ download(kmzLink, temp_kmz)
+ kmlFileName = extractKmz(temp_kmz)
+ if kmlFileName:
+ kmlFile = open(kmlFileName, 'r')
+ content = BeautifulSoup(kmlFile)
+ box = content.find('latlonbox')
+ north = box.find('north').getText()
+ south = box.find('south').getText()
+ east = box.find('east').getText()
+ west = box.find('west').getText()
+
+ # cleanup temp directory
+ try:
+ kmlDir = kmlFileName.rpartition('/')[0]
+ os.remove(kmlFileName)
+ os.removedirs(kmlDir)
+ except OSError as e:
+ errorLog.error('(processEntry) %s: %s', e.strerror, e.filename)
+
+ else:
+ kmzSuccess = False
+
+ try:
+ os.remove(temp_kmz)
+ except OSError as e:
+ errorLog.error('(processEntry) %s: %s', e.strerror, e.filename)
+
+ else:
+ kmzSuccess = False
+
+ # check for GeoTiff
+ if kmzSuccess == False:
+ tiffLink = findTiff(content)
+ if tiffLink:
+ temp_tiff = "temp_tiff"
+ download(tiffLink, temp_tiff)
+ ds = gdal.Open(temp_tiff)
+ width = ds.RasterXSize
+ height = ds.RasterYSize
+ gt = ds.GetGeoTransform()
+ west = gt[0]
+ south = gt[3] + width*gt[4] + height*gt[5]
+ east = gt[0] + width*gt[1] + height*gt[2]
+ north = gt[3]
+
+ # cleanup temp file
+ try:
+ os.remove(temp_tiff)
+ except OSError as e:
+ errorLog.error('(processEntry) %s: %s', e.strerror, e.filename)
+
+ else:
+ debugLog.debug('skipping because lacking image')
+ return None
+
+ # if the entry is kept, parse the rest of the fields
+ date = entry["date"].split("T")[0]
+ title = entry["title"]
+ description = entry["summary_detail"].value
+ thumbnail = entry["media_thumbnail"][0].get("url")
+ keyword = ''
+
+ # if the category is a fire or flood, look for keywords
+ # about the base layer and overlay
+ category = entry["tags"][0].term
+ lowerContent = content.getText().lower()
+ if category == 'Floods':
+ if lowerContent.count('natural-color') > 0:
+ keyword = 'natural-color'
+ if lowerContent.count('natural color') > 0:
+ keyword = 'natural-color'
+ if category == 'Fires':
+ if lowerContent.count('red outlines') > 0:
+ keyword = 'outlines'
+
+ retobj = {
+ 'title':title,
+ 'date':date,
+ 'description':description,
+ 'category':category,
+ 'satellite':sat,
+ 'instrument':instrument,
+ 'thumbnail':thumbnail,
+ 'link':story,
+ 'north':north,
+ 'south':south,
+ 'east':east,
+ 'west':west,
+ 'keyword':keyword}
+
+ return retobj
+
+# Driver
+def main():
+ entries = pullRss("http://www.earthobservatory.nasa.gov/Feeds/rss/nh.rss")
+ num = 0
+ recent_titles = []
+ data = []
+
+ outFileName = os.path.join(libDir, 'events_data.json')
+ # get existing data to make sure we aren't adding duplicates
+ if os.path.exists(outFileName):
+ outfile = open(outFileName, 'r+w')
+ try:
+ data = json.load(outfile)
+ last_len = 0
+ if len(data) < len(entries):
+ last_len = len(data) * -1
+ else:
+ last_len = len(entries) * -1
+ recent_entries = data[last_len:]
+
+ for r in recent_entries:
+ recent_titles.append(r["title"])
+
+ except ValueError:
+ pass
+
+ else:
+ outfile = open(outFileName, 'w+');
+
+
+ for e in entries:
+ obj = processEntry(e)
+
+ if obj:
+ if not obj.title in recent_titles:
+ data.append(obj)
+ num = num + 1
+
+ outfile.seek(0)
+ if len(data) < 100:
+ json.dump(data, outfile)
+ else:
+ json.dump(data[-100:], outfile)
+ outfile.truncate()
+ outfile.close()
+
+main()
diff --git a/build.xml b/build.xml
index b2679e7a8..bbc4a5a58 100644
--- a/build.xml
+++ b/build.xml
@@ -124,6 +124,9 @@
description="Builds minified web site">
<delete dir="${build.web.dir}"/>
<mkdir dir="${build.web.dir}"/>
+
+ <delete dir="${build.bin.dir}"/>
+ <mkdir dir="${build.bin.dir}"/>
<!-- Construct temporary output of the minification here -->
<delete dir="${build.dir}/minify"/>
@@ -145,13 +148,21 @@
<fileset dir="${build.web.dir}/pages" includes="*.html"/>
<fileset dir="${build.web.dir}/js" includes="**/*.js"/>
</replace>
-
+
+ <copy todir="${build.bin.dir}">
+ <fileset dir="bin"/>
+ </copy>
<!-- Debug version that is not minified -->
<delete dir="${build.web-debug.dir}"/>
<mkdir dir="${build.web-debug.dir}"/>
+ <delete dir="${build.bin-debug.dir}"/>
+ <mkdir dir="${build.bin-debug.dir}"/>
<copy todir="${build.web-debug.dir}">
<fileset dir="${build.web.dir}"/>
</copy>
+ <copy todir="${build.bin-debug.dir}">
+ <fileset dir="${build.bin.dir}"/>
+ </copy>
<!-- Configuration file -->
<delete file="${build.web.dir}/data/config"/>
@@ -288,21 +299,31 @@
<tar destfile="${dist.dir}/worldview.tar.bz2" compression="bzip2">
<tarfileset dir="${build.dir}/worldview" prefix="worldview">
<exclude name="**/data/echo.cgi"/>
+ <exclude name="**/bin/eventsGeoRssParser.py"/>
</tarfileset>
- <tarfileset dir="${build.dir}/worldview/data"
- prefix="worldview/data" filemode="755">
+ <tarfileset dir="${build.web.dir}/data"
+ prefix="worldview/web/data" filemode="755">
<include name="echo.cgi"/>
</tarfileset>
+ <tarfileset dir="${build.bin.dir}"
+ prefix="worldview/bin" filemode="755">
+ <include name="eventsGeoRssParser.py"/>
+ </tarfileset>
</tar>
<tar destfile="${dist.dir}/worldview-debug.tar.bz2" compression="bzip2">
<tarfileset dir="${build.dir}/worldview-debug" prefix="worldview-debug">
<exclude name="**/data/echo.cgi"/>
+ <exclude name="**/bin/eventsGeoRssParser.py"/>
</tarfileset>
- <tarfileset dir="${build.dir}/worldview-debug/data"
- prefix="worldview-debug/data" filemode="755">
+ <tarfileset dir="${build.web-debug.dir}/data"
+ prefix="worldview-debug/web/data" filemode="755">
<include name="echo.cgi"/>
</tarfileset>
+ <tarfileset dir="${build.bin-debug.dir}"
+ prefix="worldview-debug/bin" filemode="755">
+ <include name="eventsGeoRssParser.py"/>
+ </tarfileset>
</tar>
<tar destfile="${dist.dir}/worldview-doc.tar.bz2"
@@ -310,19 +331,25 @@
compression="bzip2"/>
</target>
- <target name="rpm" depends="dist">
+ <target name="rpm" depends="dist,rpm-build"/>
+
+ <target name="rpm-build">
<mkdir dir="${user.home}/rpmbuild/SOURCES"/>
<copy file="${dist.dir}/worldview.tar.bz2"
todir="${user.home}/rpmbuild/SOURCES"/>
<copy file="${dist.dir}/worldview-debug.tar.bz2"
todir="${user.home}/rpmbuild/SOURCES"/>
- <copy file="deploy/httpd.worldview.conf"
+ <copy file="etc/deploy/httpd.worldview.conf"
+ todir="${user.home}/rpmbuild/SOURCES"/>
+ <copy file="etc/deploy/httpd.worldview-debug.conf"
+ todir="${user.home}/rpmbuild/SOURCES"/>
+ <copy file="etc/deploy/events_log.conf"
todir="${user.home}/rpmbuild/SOURCES"/>
- <copy file="deploy/httpd.worldview-debug.conf"
+ <copy file="etc/deploy/cron.worldview"
todir="${user.home}/rpmbuild/SOURCES"/>
<exec executable="rpmbuild">
<arg value="-ba"/>
- <arg value="deploy/worldview.spec"/>
+ <arg value="etc/deploy/worldview.spec"/>
</exec>
</target>
diff --git a/etc/config/events_log.conf b/etc/config/events_log.conf
new file mode 100644
index 000000000..24b804e7a
--- /dev/null
+++ b/etc/config/events_log.conf
@@ -0,0 +1,51 @@
+[loggers]
+keys=root,access,error,debug
+
+[handlers]
+keys=access,error,debug
+
+[formatters]
+keys=basicFormatter
+
+[logger_root]
+level=DEBUG
+handlers=""
+
+[logger_access]
+level=DEBUG
+handlers=access
+qualname=eventsAccess
+propagate=0
+
+[logger_error]
+level=DEBUG
+handlers=error
+qualname=eventsErrors
+propagate=0
+
+[logger_debug]
+level=DEBUG
+handlers=debug
+qualname=eventsDebug
+propagate=0
+
+[handler_access]
+class=FileHandler
+level=DEBUG
+formatter=basicFormatter
+args=('src/var/log/worldview/events_access.log','a+')
+
+[handler_error]
+class=FileHandler
+level=DEBUG
+formatter=basicFormatter
+args=('src/var/log/worldview/events_errors.log', 'a+')
+
+[handler_debug]
+class=FileHandler
+level=DEBUG
+formatter=basicFormatter
+args=('src/var/log/worldview/events_debug.log', 'a+')
+
+[formatter_basicFormatter]
+format=%(asctime)s %(message)s
diff --git a/etc/deploy/cron.worldview b/etc/deploy/cron.worldview
new file mode 100644
index 000000000..ad264ea9b
--- /dev/null
+++ b/etc/deploy/cron.worldview
@@ -0,0 +1 @@
+0 * * * * apache /usr/share/worldview/bin/eventsGeoRssParser.py 2>&1 >/dev/null
diff --git a/etc/deploy/events_log.conf b/etc/deploy/events_log.conf
new file mode 100644
index 000000000..94ce12225
--- /dev/null
+++ b/etc/deploy/events_log.conf
@@ -0,0 +1,51 @@
+[loggers]
+keys=root,access,error,debug
+
+[handlers]
+keys=access,error,debug
+
+[formatters]
+keys=basicFormatter
+
+[logger_root]
+level=DEBUG
+handlers=""
+
+[logger_access]
+level=DEBUG
+handlers=access
+qualname=eventsAccess
+propagate=0
+
+[logger_error]
+level=DEBUG
+handlers=error
+qualname=eventsErrors
+propagate=0
+
+[logger_debug]
+level=DEBUG
+handlers=debug
+qualname=eventsDebug
+propagate=0
+
+[handler_access]
+class=FileHandler
+level=DEBUG
+formatter=basicFormatter
+args=('/var/log/worldview/events_access.log','a+')
+
+[handler_error]
+class=FileHandler
+level=DEBUG
+formatter=basicFormatter
+args=('/var/log/worldview/events_errors.log', 'a+')
+
+[handler_debug]
+class=FileHandler
+level=DEBUG
+formatter=basicFormatter
+args=('/var/log/worldview/events_debug.log', 'a+')
+
+[formatter_basicFormatter]
+format=%(asctime)s %(message)s
diff --git a/etc/deploy/httpd.worldview-debug.conf b/etc/deploy/httpd.worldview-debug.conf
index ecac2d6f2..7ca194019 100644
--- a/etc/deploy/httpd.worldview-debug.conf
+++ b/etc/deploy/httpd.worldview-debug.conf
@@ -1,12 +1,13 @@
-Alias /labs/worldview-debug /usr/share/worldview-debug
+Alias /labs/worldview-debug/var /var/lib/worldview
+Alias /labs/worldview-debug /usr/share/worldview-debug/web
-<Directory /usr/share/worldview-debug>
+<Directory /usr/share/worldview-debug/web>
AllowOverride All
Order allow,deny
Allow from all
</Directory>
-<Directory /usr/share/worldview-debug/data>
+<Directory /usr/share/worldview-debug/web/data>
Options ExecCGI
</Directory>
diff --git a/etc/deploy/httpd.worldview.conf b/etc/deploy/httpd.worldview.conf
index d85e2116c..cde9306d9 100644
--- a/etc/deploy/httpd.worldview.conf
+++ b/etc/deploy/httpd.worldview.conf
@@ -1,12 +1,13 @@
-Alias /labs/worldview /usr/share/worldview
+Alias /labs/worldview/var /var/lib/worldview
+Alias /labs/worldview /usr/share/worldview/web
-<Directory /usr/share/worldview>
+<Directory /usr/share/worldview/web>
AllowOverride All
Order allow,deny
Allow from all
</Directory>
-<Directory /usr/share/worldview/data>
+<Directory /usr/share/worldview/web/data>
Options ExecCGI
</Directory>
diff --git a/etc/deploy/worldview.spec b/etc/deploy/worldview.spec
index 55dccc9d9..43ec16545 100644
--- a/etc/deploy/worldview.spec
+++ b/etc/deploy/worldview.spec
@@ -2,8 +2,8 @@
# package has already been made.
Name: worldview
-Version: 0.4.5
-Release: 1%{?dist}
+Version: 0.6.0
+Release: 0.1%{?dist}
Summary: Browse full-resolution, near real-time satellite imagery.
License: Copyright NASA
@@ -12,13 +12,19 @@ Source0: worldview.tar.bz2
Source1: worldview-debug.tar.bz2
Source2: httpd.worldview.conf
Source3: httpd.worldview-debug.conf
+Source4: events_log.conf
+Source5: cron.worldview
BuildArch: noarch
Requires: httpd
Requires: php
+Requires: python-feedparser
+Requires: python-beautifulsoup4
+Requires: gdal
+Requires: gdal-python
%description
-In essence, Worldview* shows the entire Earth as it looks "right now",
+In essence, Worldview shows the entire Earth as it looks "right now",
or at least as it has looked within the past few hours. Worldview
supports time-critical application areas such as wildfire management,
air quality measurements, and weather forecasting.
@@ -33,8 +39,8 @@ several products are also available for a "full globe" perspective.
%package debug
Summary: Non-minified version of Worldview for debugging
-Requires: httpd
-Requires: php
+Requires: %{name} = %{version}-%{release}
+
%description debug
Non-minified version of Worldview for debugging
@@ -43,10 +49,13 @@ Non-minified version of Worldview for debugging
%global httpdconfdir %{_sysconfdir}/httpd/conf.d
%prep
+%setup -c -T
tar xf %{SOURCE0}
tar xf %{SOURCE1}
cp %{SOURCE2} .
cp %{SOURCE3} .
+cp %{SOURCE4} .
+cp %{SOURCE5} .
%build
@@ -67,6 +76,19 @@ cp -r worldview/* %{buildroot}/%{_datadir}/worldview
install -m 755 -d %{buildroot}/%{_datadir}/worldview-debug
cp -r worldview/* %{buildroot}/%{_datadir}/worldview-debug
+install -m 755 -d %{buildroot}/%{_sysconfdir}/worldview
+install -m 644 events_log.conf \
+ %{buildroot}/%{_sysconfdir}/worldview/events_log.conf
+
+install -m 755 -d %{buildroot}/%{_sharedstatedir}/worldview
+touch %{buildroot}/%{_sharedstatedir}/worldview/events_data.json
+install -m 755 -d %{buildroot}/%{_localstatedir}/log/worldview
+touch %{buildroot}/%{_localstatedir}/log/worldview/events_access.log
+touch %{buildroot}/%{_localstatedir}/log/worldview/events_errors.log
+touch %{buildroot}/%{_localstatedir}/log/worldview/events_debug.log
+
+install -m 755 -d %{buildroot}/%{_sysconfdir}/cron.d
+install -m 600 cron.worldview %{buildroot}/%{_sysconfdir}/cron.d/worldview
%clean
rm -rf %{buildroot}
@@ -75,7 +97,18 @@ rm -rf %{buildroot}
%files
%defattr(-,root,root,-)
%{_datadir}/worldview
-%config %{httpdconfdir}/worldview.conf
+%config(noreplace) %{httpdconfdir}/worldview.conf
+%dir %{_sysconfdir}/worldview
+%config(noreplace) %{_sysconfdir}/worldview/events_log.conf
+%{_sysconfdir}/cron.d/worldview
+
+%defattr(600,apache,apache,700)
+%dir %{_sharedstatedir}/worldview
+%ghost %{_sharedstatedir}/worldview/events_data.json
+%dir %{_localstatedir}/log/worldview
+%ghost %{_localstatedir}/log/worldview/events_access.log
+%ghost %{_localstatedir}/log/worldview/events_errors.log
+%ghost %{_localstatedir}/log/worldview/events_debug.log
%files debug
@@ -83,27 +116,9 @@ rm -rf %{buildroot}
%config %{httpdconfdir}/worldview-debug.conf
-%post
-if [ "$1" == 1 ] ; then
- service httpd reload
-fi
-
-%post debug
-if [ "$1" == 1 ] ; then
- service httpd reload
-fi
-
-%postun
-if [ "$1" == 0 ] ; then
- service httpd reload
-fi
-
-%postun debug
-if [ "$1" == 0 ] ; then
- service httpd reload
-fi
-
-
%changelog
-* Thu May 9 2012 Mike McGann <[email protected]> - 0.4.5-1
+* Wed Aug 21 2013 Mike McGann <[email protected]> - 0.6.0-0.1
+- Restructured for events
+
+* Thu May 9 2013 Mike McGann <[email protected]> - 0.4.5-1
- Initial package
diff --git a/src/var/lib/worldview/.gitignore b/src/var/lib/worldview/.gitignore
new file mode 100644
index 000000000..d6b7ef32c
--- /dev/null
+++ b/src/var/lib/worldview/.gitignore
@@ -0,0 +1,2 @@
+*
+!.gitignore
diff --git a/src/var/log/worldview/.gitignore b/src/var/log/worldview/.gitignore
new file mode 100644
index 000000000..a5baada18
--- /dev/null
+++ b/src/var/log/worldview/.gitignore
@@ -0,0 +1,3 @@
+*
+!.gitignore
+