forked from googlearchive/gsa-admin-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgsa_feed.py
executable file
·423 lines (351 loc) · 12.8 KB
/
gsa_feed.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#!/usr/bin/env python2
#
# Copyright 2014 Google, Inc.
# All Rights Reserved.
"""gsa_feed.py pushes an xml feed file to the GSA.
1. pushes an XML file to the GSA
2. show examples feed for each feedtype
3. validates GSA XML feed with a DTD
=== 1/3 Push a feed file
~$ gsa_feed.py feed.xml entzo34.hot
The XML file and GSA hostname are given as file arguments , the
order is not important, the feed file must end with .xml.
No need to specify the feedtype and datasource, they are extracted
from the XML feed.
The script shows the minimal required set of "follows URLs".
Make sure, in the case of a web feed, that the content server owner
granted you permission to crawl its content server.
=== 2/3 Show examples feeds
~$ gsa_feed.py --example full
~$ gsa_feed.py --example incremental
~$ gsa_feed.py --example metadata-and-url
~$ gsa_feed.py --example metadata-and-url-base64
~$ gsa_feed.py --example groupsdb
=== 3/3 Validate the feeds against the GSA feed DTD
The DTD can be retrieved from a GSA
~$ gsa_feed.py --dtd gsa_hostname feed.xml
The DTD can be a local file
~$ gsa_feed.py --dtd gsafeed.dtd feed.xml
The DTD filename must end with '.dtd'. It is always available at
http://<gsa hostname>/gsafeed.dtd.
Backward compatible with pushfeed_client.py: the same options are supported.
"""
import optparse
import sys
import urllib2
import urlparse
from xml.etree.ElementTree import iterparse
try:
from lxml import etree
except ImportError:
etree = None
print ('DTD validation is not available as the lxml library is missing.\n'
'To enable this feature, you can install the library, on Linux:\n'
'~$ sudo aptitude install python-lxml')
VERSION = (1, 0)
EXAMPLES = {
'full': """<?xml version="1.0" encoding="UTF8"?>
<!DOCTYPE gsafeed PUBLIC "-//Google//DTD GSA Feeds//EN" "">
<gsafeed>
<header>
<datasource>sample</datasource>
<feedtype>full</feedtype>
</header>
<group>
<record url="http://example.com/hello01" mimetype="text/plain"
last-modified="Tue, 6 Nov 2007 12:45:26 GMT">
<content>This is hello01</content>
</record>
<record url="http://example.com/hello02" mimetype="text/plain"
lock="true">
<content>This is hello02</content>
</record>
<record url="http://example.com/hello03" mimetype="text/html">
<content><![CDATA[
<html>
<title>namaste</title>
<body>
This is hello03
</body>
</html>
]]></content>
</record>
<record url="http://example.com/hello04" mimetype="text/html">
<content encoding="base64binary">Zm9vIGJhcgo</content>
</record>
</group>
</gsafeed>""",
'metadata-and-url-base64': """<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE gsafeed PUBLIC "-//Google//DTD GSA Feeds//EN" ">"
<gsafeed>
<header>
<datasource>example3</datasource>
<feedtype>metadata-and-url</feedtype>
</header>
<group>
<record url="http://example.com/myfeed.html" action="add" mimetype="text/html">
<metadata>
<meta encoding="base64binary" name="cHJvamVjdF9uYW1l" content="Y2lyY2xlZ19yb2Nrcw==">
</metadata>
</record>
</group>
</gsafeed>""",
'incremental': """<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE gsafeed PUBLIC "-//Google//DTD GSA Feeds//EN" "">
<gsafeed>
<header>
<datasource>web</datasource>
<feedtype>incremental</feedtype>
</header>
<group>
<record url="http://example.com/hello02" mimetype="text/plain"></record>
</group>
</gsafeed>""",
'metadata-and-url': """<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE gsafeed PUBLIC "-//Google//DTD GSA Feeds//EN" "">
<gsafeed>
<header>
<datasource>example3</datasource>
<feedtype>metadata-and-url</feedtype>
</header>
<group>
<record url="http://example.com/search/employeesearch.php?q=jwong"
action="add" mimetype="text/html" lock="true">
<metadata>
<meta name="Name" content="Jenny Wong"/>
<meta name="Title" content="Metadata Developer"/>
<meta name="Phone" content="x12345"/>
<meta name="Floor" content="3"/>
<meta name="PhotoURL"
content="http://www/employeedir/engineering/jwong.jpg"/>
<meta name="URL"
content="http://example.com/search/employeesearch.php?q=jwong"/>
</metadata>
</record>
</group>
</gsafeed>""",
'groupsdb': """<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE gsafeed PUBLIC "-//Google//DTD GSA Feeds//EN" "">
<xmlgroups>
<membership>
<principal namespace="Default" case-sensitivity-type="EVERYTHING_CASE_INSENSITIVE" scope="GROUP">
abc.com/group1
</principal>
<members>
<principal namespace="Default" case-sensitivity-type="EVERYTHING_CASE_INSENSITIVE" scope="GROUP">
subgroup1
</principal>
<principal namespace="Default" case-sensitivity-type="EVERYTHING_CASE_INSENSITIVE" scope="USER">
user1
</principal>
</members>
</membership>
<membership>
<principal namespace="Default" case-sensitivity-type="EVERYTHING_CASE_INSENSITIVE" scope="GROUP">
subgroup1
</principal>
<members>
<principal namespace="Default" case-sensitivity-type="EVERYTHING_CASE_INSENSITIVE" scope="USER">
example.com/user2
</principal>
</members>
</membership>
</xmlgroups>"""}
p = optparse.OptionParser(usage=__doc__.strip())
p.add_option(
'--dtd',
help=('A string: either the filename of the dtd in the local directory, or '
'the hostname of a GSA on which the script will fetch the latest '
' dtd. Use this option to validate the feed with the GSA DTD. The '
'DTD is on the GSA, at the '
'address http://<gsa hostname>/gsafeed.dtd.'),
action='store_true',
default=False)
p.add_option(
'--example',
help='can be: %s' % ', '.join(EXAMPLES.keys()),
default=None)
p.add_option(
'-s', '--datasource',
help=('Name of the datasource. Deprecated option, the datasource is now '
'extracted from the XML feed.'),
default=None)
p.add_option(
'--feedtype',
help=('Can be "full", "incremental", or "metadata-and-url". Deprecated '
'option, the feedtype is now extracted from the XML feed. '),
default=None)
p.add_option(
'-u', '--url',
help=('URL of the feed component e.g. '
'http://<gsa address>:19900/xmlfeed. '
'Deprecated option: the GSA host is the positional arg that does not '
'end in ".xml"'),
default=None)
p.add_option(
'--xmlfilename',
help=('The feed xml file you want to feed. '
'Deprecated option: the filename is the positional arg ending '
'in ".xml"'),
default=None)
def ShowExamples(example):
"""Prints the example to the console."""
assert example in EXAMPLES.keys(), (
'The "--example" value must be one of %s' % EXAMPLES.keys())
print EXAMPLES[example]
def SendFeed(xmlfilename=None, url=None, feedtype=None, datasource=None):
"""Sends an HTTP post from the command line flags.
Args:
xmlfilename: the filename of a XML GSA feed
url: the URL of the feed service on the GSA
feedtype: incremental, full, etc (more details in the reference)
datasource: a string label of the user choice
Returns:
None. All side effect.
"""
def EncodeMultipart(fields):
"""Returns input data in multipart/form-data encoding.
Args:
fields: list of 2-strings tuples.
Example: [('feedtype', 'incremental'),
('datasource', 'mydatasource')
('data', '<xml feed string ...')]
Returns:
a 2-tuple of strings:
- the content_type (with the part 'boundary=')
- a multipart/form-data encoding string
"""
boundary = '----------boundary_of_feed_data$'
lines = []
for key, value in fields:
lines.extend(('--' + boundary,
'Content-Disposition: form-data; name="%s"' % key,
'',
value))
lines.extend(('--' + boundary + '--', ''))
return 'multipart/form-data; boundary=%s' % boundary, '\r\n'.join(lines)
parts = [('feedtype', feedtype),
('datasource', datasource),
('data', open(xmlfilename, 'r').read())]
content_type, body = EncodeMultipart(parts)
headers = {'Content-type': content_type,
'Content-length': str(len(body))}
try:
print 'Sending the feed to:', url
return urllib2.urlopen(urllib2.Request(
url, body, headers)).read()
except urllib2.URLError:
url = url.replace(
'http', 'https').replace('19900', '19902')
print 'Trying sending the feed to:', url
return urllib2.urlopen(urllib2.Request(
url, body, headers)).read()
def Validate(dtd_filename_or_url, xmlfilename):
"""Validate the input file against a GSA feed DTD.
Args:
dtd_filename_or_url: string either a .dtd file in the current directory,
or the hostname of a GSA on which to fetch the DTD.
Returns:
True if validation passed, otherwise an exception is raised.
Raises:
ImportError: A DTD validation exception or an error when the hostname
set is not reachable on the port 80, on the URL
http://<ip address>/gsafeed.dtd.
"""
if not etree:
raise ImportError(
'As the lxml module not available, feed validation is not '
'available, please check http://lxml.de/installation.html\n'
'On Linux, "sudo aptitude install python-lxml"')
if dtd_filename_or_url.endswith('.dtd'):
f = open(dtd_filename_or_url)
else:
try:
dtd_url = 'http://%s/gsafeed.dtd' % dtd_filename_or_url
print 'Trying to fetch the dtd from:', dtd_url
f = urllib2.urlopen(dtd_url)
except urllib2.URLError:
try:
dtd_url = dtd_url.replace('http', 'https').replace('19900', '19902')
print 'Trying to fetch the dtd from:', dtd_url
except:
raise Exception(
'Could not download the dtd from %s. '
'Is this GSA reachable, is the port 80 or 443 open and reachable?'
% dtd_url)
etree.DTD(f).validate(etree.parse(xmlfilename))
return True
def ExtractFeedtypeAndDatasource(filename):
"""Extracts the feed type and the datasource.
Args:
filename: string filename of a XML GSA feed document.
Returns:
A tuple of string: (feedtype, datasource)
Raises:
ValueError: when the datasource and feedtype are missing from the XML file.
"""
feedtype, datasource = None, None
for event, elem in iterparse(filename):
if event == 'end':
if elem.tag == 'feedtype':
feedtype = elem.text
elif elem.tag == 'datasource':
datasource = elem.text
if feedtype and datasource:
return feedtype, datasource
raise ValueError(
'Could not find the feed type and datasource in the XML file')
def ExtractFollowUrls(filename):
"""Returns a minimal set of hostnames matching the URLs in the feed."""
follow_urls = set()
for event, elem in iterparse(filename):
if event == 'end':
if elem.tag == 'record':
if 'url' in elem.attrib:
url = urlparse.urlparse(elem.attrib['url'])
follow_urls.add('%s://%s/' % (url.scheme, url.netloc))
return follow_urls
def main(options):
if options.example:
ShowExamples(options.example)
elif options.dtd:
if not options.xmlfilename:
print 'Provide a document to validate'
if Validate(options.host, options.xmlfilename):
print 'Valid XML document, valid GSA feed.'
else:
if not options.url or not options.xmlfilename:
print ('No hostname or no feed file:'
'\n gsa_feed.py feed.xml gsa.company.com')
sys.exit(1)
# If the datasource or the feedtype is empty extract it from the feed file.
if options.feedtype is None or options.datasource is None:
feedtype, datasource = ExtractFeedtypeAndDatasource(options.xmlfilename)
if options.feedtype is None:
options.feedtype = feedtype
if options.datasource is None:
o.datasource = datasource
response = SendFeed(
options.xmlfilename, options.url, options.feedtype, options.datasource)
print 'Feed service responded:', response
if response == 'Success':
print ('\nMake sure the GSA is configured in "Content Sources > Feeds" '
'for receiving feeds from this workstation IP address. ')
print ('Make sure the URLs you push are matching a "follow URL". '
'See below for minimal set of matching follow URLs:')
for l in ExtractFollowUrls(options.xmlfilename):
print l
if __name__ == '__main__':
if len(sys.argv) == 1:
p.print_help()
sys.exit(1)
o, a = p.parse_args()
o.host = None
# sets the positional args to the 'xmlfilename' and 'host' depending on the
# term suffix: it is an XML filename iff ends with .xml
for option in a:
setattr(o, 'xmlfilename' if option.endswith('.xml') else 'host', option)
# Sets the full URL from the host shortcut
if o.host:
o.url = 'http://%s:19900/xmlfeed' % o.host
main(o)