-
Notifications
You must be signed in to change notification settings - Fork 6
/
StartStopService.py
384 lines (359 loc) · 16.7 KB
/
StartStopService.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
#-------------------------------------------------------------
# Name: Start or Stop Service
# Purpose: Starts or stops a service or services in an
# ArcGIS Enterprise site.
# Author: Shaun Weston ([email protected])
# Date Created: 05/11/2018
# Last Updated: 15/11/2019
# ArcGIS Version: ArcGIS API for Python 1.4.2+
# Python Version: 3.6.5+ (Anaconda Distribution)
#--------------------------------
# Import main modules
import os
import sys
import logging
import smtplib
import time
import shutil
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import email.mime.application
import urllib.request
# Import ArcGIS modules
useArcPy = "true"
useArcGISAPIPython = "false"
if (useArcPy == "true"):
# Import arcpy module
import arcpy
# Enable data to be overwritten
arcpy.env.overwriteOutput = True
if (useArcGISAPIPython == "true"):
# Import arcgis module
import arcgis
import datetime
# Set global variables
# Logging
enableLogging = "true" # Use within code to print and log messages - printMessage("xxx","info"), printMessage("xxx","warning"), printMessage("xxx","error")
logFile = os.path.join(os.path.dirname(__file__), "StartStopService.log") # e.g. os.path.join(os.path.dirname(__file__), "Example.log")
enableLogTable = "false" # Use to log the completion of the process to a geodatabase table
logTable = "" # e.g. "C:\Temp\Scratch.gdb\Logging"
archiveLogFiles = "true"
# Email Use within code to send email - sendEmail(subject,message,attachment)
sendErrorEmail = "false"
emailSubject = "" # Subject in email
emailServerName = "" # e.g. smtp.gmail.com
emailServerPort = None # e.g. 25
emailTo = [] # Address of email sent to e.g. ["[email protected]", "[email protected]"]
emailUser = "" # Address of email sent from e.g. "[email protected]"
emailPassword = ""
# Proxy
enableProxy = "false"
requestProtocol = "http" # http or https
proxyURL = ""
# Output
output = None
# Start of main function
def mainFunction(siteURL,adminUser,adminPassword,servicesFolder,serviceName,serviceAction): # Add parameters sent to the script here e.g. (var1 is 1st parameter,var2 is 2nd parameter,var3 is 3rd parameter)
try:
# --------------------------------------- Start of code --------------------------------------- #
# Connect to GIS site
printMessage("Connecting to GIS site - " + siteURL + "...","info")
gis = arcgis.GIS(url=siteURL, username=adminUser, password=adminPassword, verify_cert=False)
# Get a list of servers in the site
gisServers = gis.admin.servers.list()
# If a service name is set
if (serviceName):
# Set GIS service found to false
gisServiceFound = False
else:
# Set GIS service found to true
gisServiceFound = True
# For each server
for gisServer in gisServers:
# If a folder is set
if (servicesFolder):
# If the folder does not exist
if servicesFolder not in gisServer.services.folders:
printMessage("Services folder does not exist: " + servicesFolder, "error")
# For each service in the root directory
for gisService in gisServer.services.list():
# If no services folder set (Start/stop services in the root directory)
if (servicesFolder is None) or (servicesFolder == ""):
# If no service name set (Start/stop all services)
if (serviceName is None) or (serviceName == ""):
# Function - Start or stop the service
startStopService(gisService, serviceAction)
# Service name set (Just start/stop that service)
else:
# If the service name and type is equal to the one specified
if (serviceName.lower() == gisService.properties.serviceName.lower() + "." + gisService.properties.type.lower()):
# Function - Start or stop the service
startStopService(gisService, serviceAction)
# Set GIS service found to true
gisServiceFound = True
# For each folder
for gisFolder in gisServer.services.folders:
# If the services folder is equal to the one specified
if (servicesFolder.lower() == gisFolder.lower()):
# For each service in the folder
for gisService in gisServer.services.list(folder=gisFolder):
# If no service name set (Start/stop all services)
if (serviceName is None) or (serviceName == ""):
# Function - Start or stop the service
startStopService(gisService, serviceAction)
# Service name set (Just start/stop that service)
else:
# If the service name and type is equal to the one specified
if (serviceName.lower() == gisService.properties.serviceName.lower() + "." + gisService.properties.type.lower()):
# Function - Start or stop the service
startStopService(gisService, serviceAction)
# Set GIS service found to true
gisServiceFound = True
# If a service name was set but not found
if (gisServiceFound == False):
printMessage("Service does not exist: " + serviceName, "error")
# --------------------------------------- End of code --------------------------------------- #
# If called from ArcGIS GP tool
if __name__ == '__main__':
# Return the output if there is any
if output:
# If using ArcPy
if (useArcPy == "true"):
arcpy.SetParameter(1, output)
# ArcGIS desktop not installed
else:
return output
# Otherwise return the result
else:
# Return the output if there is any
if output:
return output
printMessage("Process ended...","info")
if (enableLogTable == "true"):
# Log end message to table
currentDate = datetime.datetime.utcnow().strftime("%d/%m/%Y %H:%M:%S")
logToTable({"Date": currentDate,"Process": os.path.basename(__file__).replace(".py",""),"Status": "Success","Organisation": None,"DataName": None,"Message": "Process ended...","RecordCount":None})
# If error
except Exception as e:
errorMessage = ""
# Build and show the error message
# If many arguments
if (e.args):
for i in range(len(e.args)):
if (i == 0):
errorMessage = str(e.args[i]).encode('utf-8').decode('utf-8')
else:
errorMessage = errorMessage + " " + str(e.args[i]).encode('utf-8').decode('utf-8')
# Else just one argument
else:
errorMessage = e
printMessage(errorMessage,"error")
printMessage("Process ended...","info")
if (sendErrorEmail == "true"):
# Send email
sendEmail(errorMessage,None)
if (enableLogTable == "true"):
# Log end message to table
currentDate = datetime.datetime.utcnow().strftime("%d/%m/%Y %H:%M:%S")
logToTable({"Date": currentDate,"Process": os.path.basename(__file__).replace(".py",""),"Status": "Fail","Organisation": None,"DataName": None,"Message": errorMessage,"RecordCount":None})
# End of main function
# Start of start or stop service function
def startStopService(gisService,serviceAction):
if (serviceAction.lower() == "start"):
printMessage("Starting service: " + gisService.properties.serviceName + "." + gisService.properties.type + "...", "info")
gisService.start()
printMessage(gisService.properties.serviceName + "." + gisService.properties.type + " is now " + gisService.status["realTimeState"].lower() + "...","info")
elif (serviceAction.lower() == "stop"):
printMessage("Stopping service: " + gisService.properties.serviceName + "." + gisService.properties.type + "...", "info")
gisService.stop()
printMessage(gisService.properties.serviceName + "." + gisService.properties.type + " is now " + gisService.status["realTimeState"].lower() + "...","info")
else:
printMessage("Neither start or stop has been set in the parameters...", "warning")
printMessage(gisService.properties.serviceName + "." + gisService.properties.type + " remains " + gisService.status["realTimeState"].lower() + "...","info")
# End of start or stop service function
# Start of print and logging message function
def printMessage(message,type):
if (type.lower() == "warning"):
# If using ArcPy
if (useArcPy == "true"):
arcpy.AddWarning(message)
else:
print(message)
# Logging
if (enableLogging == "true"):
logger.warning(message)
elif (type.lower() == "error"):
# If using ArcPy
if (useArcPy == "true"):
arcpy.AddError(message)
else:
print(message)
# Logging
if (enableLogging == "true"):
logger.error(message)
else:
# If using ArcPy
if (useArcPy == "true"):
arcpy.AddMessage(message)
else:
print(message)
# Logging
if (enableLogging == "true"):
logger.info(message)
# End of print and logging message function
# Start of set logging function
def setLogging(logFile):
# Create a logger
logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.DEBUG)
# Setup log message handler
logMessage = logging.FileHandler(logFile)
# Setup the log formatting
logFormat = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s", "%d/%m/%Y - %H:%M:%S")
# Add formatter to log message handler
logMessage.setFormatter(logFormat)
# Add log message handler to logger
logger.addHandler(logMessage)
return logger, logMessage
# End of set logging function
# Start of log to table function
def logToTable(logData):
try:
# If using ArcPy
if (useArcPy == "true"):
# If table exists
if arcpy.Exists(logTable):
requiredFieldNames = ["Date","Process","Status","Organisation","DataName","Message","RecordCount"]
fieldNames = [f.name.lower() for f in arcpy.ListFields(logTable)]
requiredFieldsNotPresentCount = 0
for requiredFieldName in requiredFieldNames:
if requiredFieldName.lower() not in fieldNames:
printMessage(requiredFieldName + " is required in the log table...","error")
requiredFieldsNotPresentCount += 1
if (requiredFieldsNotPresentCount == 0):
# Check whether all the dictionary values have been provided
value1 = None
if "Date" in logData:
value1 = logData["Date"]
value2 = None
if "Process" in logData:
# If not blank
if (logData["Process"]):
value2 = logData["Process"][:200] # Strip to be below 200 characters
value3 = None
if "Status" in logData:
# If not blank
if (logData["Status"]):
value3 = logData["Status"][:50] # Strip to be below 50 characters
value4 = None
if "Organisation" in logData:
# If not blank
if (logData["Organisation"]):
value4 = logData["Organisation"][:50] # Strip to be below 50 characters
value5 = None
if "DataName" in logData:
# If not blank
if (logData["DataName"]):
value5 = logData["DataName"][:50] # Strip to be below 50 characters
value6 = None
if "Message" in logData:
# If not blank
if (logData["Message"]):
value6 = logData["Message"][:1000] # Strip to be below 1000 characters
value7 = None
if "RecordCount" in logData:
# If not blank
if (str(logData["RecordCount"])):
# If a number
if (str(logData["RecordCount"]).isdigit()):
value7 = logData["RecordCount"]
# Write to table
cursor = arcpy.da.InsertCursor(logTable, requiredFieldNames)
cursor.insertRow([value1,value2,value3,value4,value5,value6,value7])
del cursor
else:
printMessage("Log table does not exist - " + logTable + "...","error")
else:
printMessage("This message will not be logged to table. Table logging is only supported with ArcPy...","warning")
# If error
except Exception as e:
errorMessage = ""
# Build and show the error message
# If many arguments
if (e.args):
for i in range(len(e.args)):
if (i == 0):
errorMessage = str(e.args[i]).encode('utf-8').decode('utf-8')
else:
errorMessage = errorMessage + " " + str(e.args[i]).encode('utf-8').decode('utf-8')
# Else just one argument
else:
errorMessage = str(e)
printMessage("Log to table error...","error")
printMessage(errorMessage,"error")
# End of log to table function
# Start of send email function
def sendEmail(message,attachment):
# Send an email
printMessage("Sending email...","info")
# Server and port information
smtpServer = smtplib.SMTP(emailServerName,emailServerPort)
smtpServer.ehlo()
smtpServer.starttls()
smtpServer.ehlo
# Setup content for email (In html format)
emailMessage = MIMEMultipart('alternative')
emailMessage['Subject'] = emailSubject
emailMessage['From'] = emailUser
emailMessage['To'] = ", ".join(emailTo)
emailText = MIMEText(str(message), 'html')
emailMessage.attach(emailText)
# If there is a file attachment
if (attachment):
fp = open(attachment,'rb')
fileAttachment = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
fileAttachment.add_header('Content-Disposition','attachment',filename=os.path.basename(attachment))
emailMessage.attach(fileAttachment)
# Login with sender email address and password
if (emailUser and emailPassword):
smtpServer.login(emailUser, emailPassword)
# Send the email and close the connection
smtpServer.sendmail(emailUser, emailTo, emailMessage.as_string())
smtpServer.quit()
# End of send email function
# This test allows the script to be used from the operating
# system command prompt (stand-alone), in a Python IDE,
# as a geoprocessing script tool, or as a module imported in
# another script
if __name__ == '__main__':
# If using ArcPy
if (useArcPy == "true"):
argv = tuple(arcpy.GetParameterAsText(i)
for i in range(arcpy.GetArgumentCount()))
else:
argv = sys.argv
# Delete the first argument, which is the script
del argv[0]
# Logging
if (enableLogging == "true"):
# Archive log file
if (archiveLogFiles == "true"):
# If file exists
if (os.path.isfile(logFile)):
# If file is larger than 10MB
if ((os.path.getsize(logFile) / 1048576) > 10):
# Archive file
shutil.move(logFile, os.path.basename(os.path.splitext(logFile)[0]) + "-" + time.strftime("%d%m%Y") + ".log")
# Setup logging
logger, logMessage = setLogging(logFile)
# Log start of process
printMessage("Process started...","info")
# Setup the use of a proxy for requests
if (enableProxy == "true"):
# Setup the proxy
proxy = urllib.request.ProxyHandler({requestProtocol : proxyURL})
openURL = urllib.request.build_opener(proxy)
# Install the proxy
urllib.request.install_opener(openURL)
mainFunction(*argv)