-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserviceData.py
537 lines (447 loc) · 23.2 KB
/
serviceData.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
#-------------------------------------------------------------------------------
# Name: ArcGIS REST Service Metadata Extraction
# Purpose: Capture critical data about your REST services to include data
# sources, publishing docs, and more.
#
# Author: John Spence
#
# Created: December 9, 2022
# Modified:
# Modification Purpose:
#
#
#
#-------------------------------------------------------------------------------
# 888888888888888888888888888888888888888888888888888888888888888888888888888888
# ------------------------------- Configuration --------------------------------
# Set the data store location for all your MAPXs below.
# ShareLevel options include PUBLIC or PRIVATE.
# ShareOrg options include SHARE_ORGANIZATION or NO_SHARE_ORGANIZATION
# ShareGroups options are to place the name of a group in there.
#
# ------------------------------- Dependencies ---------------------------------
#
#
# 888888888888888888888888888888888888888888888888888888888888888888888888888888
# Script Type
scriptType = 'Missing REST Service Asset(s)'
# Signin Config
serverURL = r'https://yourinternalfacingurl.com/arcgis' #Internal facing URL that can reach the admin side of things.
serverPubURLSub = r'https://yourexternalfacingurl/arcgis'
serverTokenURL = r'https://yourinternalfacingurl.com/arcgis/tokens/' #URL for getting an auth token.
serverUSR = r'youradminusername'
serverPAS = r'youradminpassword'
serverTokenExpire = r'90'
serverTokenClient = r'requestip'
serverTokenClient = r''
# Where the Output will reside from the search
inCsv = r'\\whereyoustoreyourfiles\GISPublished\Production'
# File Name Pre-Fix for the Output
fileprefix = 'PROD_'
# Expected GDB Connection File
dbConnection = [('YourEnterpriseDB', r'C:\Users\yourusername\AppData\Roaming\Esri\YourDBConnectionFile.sde')]
# Find Services To Change
affectedFeatureClassName = r'' # Format Database.Owner.FeatureClassName
# Send confirmation of rebuild to
adminNotify = '[email protected]'
deptAdminNotify = '[email protected]'
# Configure the e-mail server and other info here.
mail_server = 'smtp-relay.google.com'
mail_from = 'GIS REST Services <[email protected]>'
mail_subject = '{} Notification: '.format(scriptType)
# Test User Override
testUser = ''
# ------------------------------------------------------------------------------
# DO NOT UPDATE BELOW THIS LINE OR RISK DOOM AND DISPAIR! Have a nice day!
# ------------------------------------------------------------------------------
# Import Python Libraries
import arcpy
import os
import csv
import sys
import datetime
import time
import requests
import string
import re
import base64
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import base64
import concurrent.futures
from tqdm import tqdm
from xml.etree import ElementTree
#-------------------------------------------------------------------------------
#
#
# Function
#
#
#-------------------------------------------------------------------------------
def main(inCsv, dbConnection):
#-------------------------------------------------------------------------------
# Name: Function - main
# Purpose: Starts the whole thing.
#-------------------------------------------------------------------------------
starttime = datetime.datetime.now()
print ('88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888')
print ('\nService Configuration Data Capture Started: {}'.format(starttime))
print (' * Getting Security Token...')
securityToken = getToken(serverUSR, serverPAS, serverTokenURL, serverTokenExpire, serverTokenClient, serverTokenClient)
if securityToken != '':
print (' - Security Token Received.')
else:
print (' ! No security token received. Stopping process.')
sys.exit()
print ('\n * Capturing Service Data...')
adminURL = serverURL + '/admin'
publicURL = serverURL + '/rest/services'
inCsv = inCsv + '\\' + fileprefix + 'SVCSources_' + str(datetime.datetime.now().date()) + '.csv'
dbAssets = findServicesData(adminURL, publicURL, securityToken, affectedFeatureClassName, inCsv, fileprefix)
print ('\n * Reviewing Data Sources...')
print (' -- Found {} items to check.'.format(len(dbAssets)))
missingData = checkIfMissingAssets(dbAssets)
if len(missingData) > 0:
print ('\n * Sending Missing Data Source Notice...')
sendMissingNotice(missingData)
print ('\n Missing data. Looks like you have work to do.')
else:
print ('\n Huzzah! Not missing data sources. My work is complete!')
print ('88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888')
return ()
def getToken(userName, password, tokenURL, tokenExpiry, tokenClient, tokenReferer):
#-------------------------------------------------------------------------------
# Name: Function - getToken
# Purpose: Captures the security token needed to access secure data/config
#-------------------------------------------------------------------------------
tokenParams = {'username': userName, 'password': password, 'expiration': tokenExpiry, 'client': tokenClient, 'referer': tokenReferer, 'f': 'json'}
r = requests.post(tokenURL, data=tokenParams)
if r.status_code == requests.codes.ok:
result = r.json()
return result['token']
else:
return ''
def listFolders(adminURL, securityToken):
#-------------------------------------------------------------------------------
# Name: Function - listFolders
# Purpose: Get your folders and ignore a few specific ones.
#-------------------------------------------------------------------------------
servicesURL = adminURL + '/services'
servicesParams = {'detail': 'false', 'f': 'json'}
servicesHeader = {'Content-Type': 'application/json', 'X-Esri-Authorization': 'Bearer {}'.format(securityToken)}
servicesResponse = requests.get(servicesURL, params=servicesParams, headers=servicesHeader)
if servicesResponse.status_code == requests.codes.ok:
servicesJson = servicesResponse.json()
gisFolders = servicesJson['folders']
gisFolders.remove('System')
gisFolders.remove('Utilities')
gisFolders.append('')
gisFolders.sort(key=str.lower)
return gisFolders
else:
return ()
def listServices(adminURL, folder, securityToken):
#-------------------------------------------------------------------------------
# Name: Function - listServices
# Purpose: Get your list of services to capture data from.
#-------------------------------------------------------------------------------
servicesURL = adminURL + '/services'
servicesParams = {'detail': 'false', 'f': 'json'}
servicesHeader = {'Content-Type': 'application/json', 'X-Esri-Authorization': 'Bearer {}'.format(securityToken)}
if folder:
servicesListURL = "{}/{}".format(servicesURL, folder)
else:
servicesListURL = servicesURL
servicesResponse = requests.get(servicesListURL, params=servicesParams, headers=servicesHeader)
if servicesResponse.status_code == requests.codes.ok:
servicesJson = servicesResponse.json()
return servicesJson['services']
else:
return ()
def findServicesData(adminURL, publicURL, securityToken, affectedFeatureClassName, inCsv, fileprefix):
#-------------------------------------------------------------------------------
# Name: Function - findServiceData
# Purpose: Get data behind your services and write it to CSV.
#-------------------------------------------------------------------------------
servicesHeader = {'Content-Type': 'application/json', 'X-Esri-Authorization': 'Bearer {}'.format(securityToken)}
manifestSuffix = 'iteminfo/manifest/manifest.xml'
dbAssetPayload = []
servicesFolders = listFolders(adminURL, securityToken)
for folder in servicesFolders:
gisServices = listServices(adminURL, folder, securityToken)
for gisService in gisServices:
if gisService['type'] in ['MapServer', 'ImageServer', 'FeatureServer']:
if folder:
thisServiceURL = '{}/{}/{}'.format(publicURL, folder, gisService['serviceName'])
manifestURL = '{}/services/{}/{}.{}/{}'.format(adminURL, folder, gisService['serviceName'], gisService['type'], manifestSuffix)
updatedInfoURL = '{}/services/{}/{}.{}/lifecycleinfos?f=pjson'.format(adminURL, folder, gisService['serviceName'], gisService['type'])
else:
thisServiceURL = '{}/{}'.format(publicURL, gisService['serviceName'])
manifestURL = '{}/services/{}.{}/{}'.format(adminURL, gisService['serviceName'], gisService['type'], manifestSuffix)
updatedInfoURL = '{}/services/{}.{}/lifecycleinfos?f=pjson'.format(adminURL, gisService['serviceName'], gisService['type'])
updateResponse = requests.get (updatedInfoURL, headers=servicesHeader)
updatePayload = updateResponse.json()
if updateResponse.status_code == requests.codes.ok:
lastUpdatedDTRAW = updatePayload['lastmodified']
lastUpdatedDTSTG = datetime.datetime.fromtimestamp(lastUpdatedDTRAW/1000)
lastUpdatedDT = lastUpdatedDTSTG.strftime('%m/%d/%Y %H:%M:%S')
#if gisService['serviceName'] == 'FEMAFloodplainComparison':
manifestResponse = requests.get(manifestURL, headers=servicesHeader)
if manifestResponse.status_code == requests.codes.ok:
payload = ElementTree.fromstring(manifestResponse.content)
for data in payload.iter('SVCResource'):
sourceDocRAW = data[3].text
if '.aprx' in sourceDocRAW or '.mxd' in sourceDocRAW:
sourceDoc = sourceDocRAW.rsplit('\\', 1)[1]
sourceDocLoc = sourceDocRAW.rsplit('\\', 1)[:1][0]
else:
sourceDoc = sourceDocRAW
sourceDocLoc = ''
for item in payload.iter('OnPremiseConnectionString'):
dbData = item.text.split(';')
if len(dbData) == 1 and 'DATABASE' in dbData[0] and '.gdb' in dbData[0]:
dbInstance = '**File Geodatabase**'
dbName = dbData[0].replace('DATABASE=', '')
for item in payload.iter('SVCDataset'):
if '.gdb\\' in item[2].text:
layerID = item[0].text
layerName = item[1].text
layerPathRAW = item[2].text
layerPath = layerPathRAW[layerPathRAW.find('.gdb\\'):]
layerPath = layerPath.replace('.gdb\\','')
layerSVRPath = item[3].text
layerPCKGPath = item[4].text
layerSVRName = item[5].text
layerDataType = item[6].text
if '(query layer)' in layerName:
layerQLPositive = 'Yes'
else:
layerQLPositive = 'No'
layerServiceURL = thisServiceURL.replace(serverURL, serverPubURLSub)
print (' Service: {} | {}'.format(folder, gisService['serviceName']))
print (' -- Last Updated: {}'.format(lastUpdatedDT))
print (' -- Service Layer Name: {}'.format(layerSVRName))
print (' -- DB Instance: {}'.format(dbInstance))
print (' -- DB Name: {}'.format(dbName))
print (' -- Feature Class: {}'.format(layerPath))
print (' -- Service URL: {}\n'.format(layerServiceURL))
if not os.path.isfile(inCsv):
csvFile = open(inCsv, 'w', newline='')
try:
writer = csv.writer(csvFile)
writer.writerow(('Folder', 'Service Name', 'Last Updated', 'Layer Name', 'Query Layer', 'Layer Source', 'DB Instance', 'DB Name', 'Source Doc', 'Source Location', 'Service URL'))
writer.writerow((folder, gisService['serviceName'], lastUpdatedDT, layerSVRName, layerQLPositive,
layerPath, dbInstance, dbName, sourceDoc, sourceDocLoc, layerServiceURL))
except:
print ('error writing first row of csv')
else:
csvFile = open(inCsv, 'a', newline='')
try:
writer = csv.writer(csvFile)
writer.writerow((folder, gisService['serviceName'], lastUpdatedDT, layerSVRName, layerQLPositive,
layerPath, dbInstance, dbName, sourceDoc, sourceDocLoc, layerServiceURL))
except Exception as e:
print ('error writing to csv')
print (e)
else:
if 'DB_CONNECTION_PROPERTIES' in dbData[3] and 'DATABASE' in dbData[4]:
dbInstance = dbData[3].replace('DB_CONNECTION_PROPERTIES=', '')
dbName = dbData[4].replace('DATABASE=', '')
for item in payload.iter('SVCDataset'):
if '.sde\\' in item[2].text:
layerID = item[0].text
layerName = item[1].text
layerPathRAW = item[2].text
layerPath = layerPathRAW[layerPathRAW.find('.sde\\'):]
layerPath = layerPath.replace('.sde\\','')
layerSVRPath = item[3].text
layerPCKGPath = item[4].text
layerSVRName = item[5].text
layerDataType = item[6].text
if '(query layer)' in layerName:
layerQLPositive = 'Yes'
else:
layerQLPositive = 'No'
layerServiceURL = thisServiceURL.replace(serverURL, serverPubURLSub)
print (' Service: {} | {}'.format(folder, gisService['serviceName']))
print (' -- Last Updated: {}'.format(lastUpdatedDT))
print (' -- Service Layer Name: {}'.format(layerSVRName))
print (' -- DB Instance: {}'.format(dbInstance))
print (' -- DB Name: {}'.format(dbName))
print (' -- Feature Class: {}'.format(layerPath))
print (' -- Service URL: {}\n'.format(layerServiceURL))
if layerQLPositive != 'Yes':
dbAssetPayload.append(layerPath)
if not os.path.isfile(inCsv):
csvFile = open(inCsv, 'w', newline='')
try:
writer = csv.writer(csvFile)
writer.writerow(('Folder', 'Service Name', 'Last Updated', 'Layer Name', 'Query Layer', 'Layer Source', 'DB Instance', 'DB Name', 'Source Doc', 'Source Location', 'Service URL'))
writer.writerow((folder, gisService['serviceName'], lastUpdatedDT, layerSVRName, layerQLPositive,
layerPath, dbInstance, dbName, sourceDoc, sourceDocLoc, layerServiceURL))
except:
print ('error writing first row of csv')
else:
csvFile = open(inCsv, 'a', newline='')
try:
writer = csv.writer(csvFile)
writer.writerow((folder, gisService['serviceName'], lastUpdatedDT, layerSVRName, layerQLPositive,
layerPath, dbInstance, dbName, sourceDoc, sourceDocLoc, layerServiceURL))
except Exception as e:
print ('error writing to csv')
print (e)
dbAssets = [*set(dbAssetPayload)]
return (dbAssets)
def getDBFeatureClasses(dbConfig):
#-------------------------------------------------------------------------------
# Name: Function - getDBFeatureClasses
# Purpose: Poorly named, but it gets all your SDE database content.
#-------------------------------------------------------------------------------
arcpy.env.workspace = dbConfig
dbFeatureClasses = arcpy.ListFeatureClasses()
dbTables = arcpy.ListTables()
dbDataSets = arcpy.ListDatasets()
dbContentPayload = []
for dbFC in dbFeatureClasses:
dbContentPayload.append(dbFC.upper())
for dbTBL in dbTables:
dbContentPayload.append(dbTBL.upper())
for dataset in dbDataSets:
arcpy.env.workspace = os.path.join(dbConfig, dataset)
dbFeatureClasses = arcpy.ListFeatureClasses()
dbTables = arcpy.ListTables()
for dbFC in dbFeatureClasses:
dbContentPayload.append(dbFC.upper())
for dbTBL in dbTables:
dbContentPayload.append(dbTBL.upper())
return (dbContentPayload)
def checkIfMissingAssets(dbAssets):
#-------------------------------------------------------------------------------
# Name: Function - checkIfMissingAssets
# Purpose: Checks what you have in REST services against what is in the DB.
#-------------------------------------------------------------------------------
missingData = []
for dbConf in dbConnection:
dbConfig = dbConf[1]
db = dbConf[0]
dbResults = getDBFeatureClasses(dbConfig)
for dbData in dbAssets:
if dbData.upper() not in dbResults:
if '\\' in dbData and '"' not in dbData:
dbData = dbData.rsplit('\\', 1)[1]
if dbData.upper() not in dbResults:
print (dbData)
pass
else:
continue
print (' -- Item Missing {}'.format(dbData))
missingData.append(dbData)
return (missingData)
def sendMissingNotice(missingData):
#-------------------------------------------------------------------------------
# Name: Function - sendMissingNotice
# Purpose: Sends a naughty gram telling you what is missing from the DB.
#-------------------------------------------------------------------------------
rowOutput = ''
if len(missingData) != 0:
for item in missingData:
featureClass = item
rowLine = '''
<tr>
<td>{}</td>
</tr>
'''.format(featureClass)
rowOutput = rowOutput + rowLine
notification = 1
else:
print (' !! No missing item notification requried !!')
return()
payLoadHTMLPreStart = '''
<div>
<h3 style="font-family:verdana;">Used in REST Service, but missing from database</h3>
<table>
<tr>
<th>Missing Asset</th>
</tr>
'''
payLoadHTMLData = '''
{}
</table>
</div>
<br>
'''.format(rowOutput)
payLoadHTML = payLoadHTMLPreStart + payLoadHTMLData
print ('\n * Preparing notification...')
payLoadHTMLStart = '''
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<!--<h2 style="font-family:verdana;"><b></b></h2>-->
'''
payLoadHTMLEnd = '''
<br>
<div>
<!--<bold>*Seasonal worker accounts will auto enable when AD user account is enabled.</bold>-->
</div>
<div>
[This is an automated system message. Please contact [email protected] for all questions.]
</div>
</body>
</html>
'''
payLoadHTML = payLoadHTMLStart + payLoadHTML + payLoadHTMLEnd
payLoadTXT = 'HTML Message -- Use HTML Compliant Email'
partTXT = MIMEText(payLoadTXT, 'plain')
partHTML = MIMEText(payLoadHTML, 'html')
msg = MIMEMultipart('alternative')
msg['Subject'] = mail_subject
msg['From'] = mail_from
msg['X-Priority'] = '1' # 1 high, 3 normal, 5 low
if testUser != '':
emailContact = testUser
print (' Sending data to {}'.format(emailContact))
msg['To'] = emailContact
msg.attach(partTXT)
msg.attach(partHTML)
server = smtplib.SMTP(mail_server)
server.sendmail(mail_from, [emailContact], msg.as_string())
server.quit()
else:
emailContact = deptAdminNotify
print (' Sending data to {}'.format(emailContact))
#msg['To'] = emailContact
#msg['Cc'] = adminNotify
msg['To'] = adminNotify
msg.attach(partTXT)
msg.attach(partHTML)
server = smtplib.SMTP(mail_server)
#server.sendmail(mail_from, [emailContact, adminNotify], msg.as_string())
server.sendmail(mail_from, [adminNotify], msg.as_string())
server.quit()
return()
#-------------------------------------------------------------------------------
#
#
# MAIN SCRIPT
#
#
#-------------------------------------------------------------------------------
if __name__ == "__main__":
main(inCsv, dbConnection)