例: フォルダ内の停止しているサービスの確認

このスクリプトは、ArcGIS Server フォルダのすべてのサービスを確認して、サービスが停止しているか開始されているかを判定します。続いて、停止している各サービスに関するメッセージを出力します。このタイプのスクリプトは、状態チェックとして定期的に実行するようにスケジュールし、メッセージを電子メールで送信したりログ ファイルに出力したりすることができます。

ArcGIS Server Administrator API を使用してサービスのステータスを確認する場合は、構成の状態とリアルタイム状況の両方が取得されます。構成の状態は、ArcGIS Server で構成している内容を表します。つまり、通常の状態でのステータスが確認されます。リアルタイム状況は、サービスが実際に機能しているかどうかを表し、停止しているサービスを検出したい場合に確認する内容です。このスクリプトは、リアルタイム状況を確認します。

# Demonstrates how to check a folder for stopped services and print them.
# The messages could alternatively be written to an e-mail or log file.
# This script could be scheduled to run at a regular interval.

# For Http calls
import httplib, urllib, json

# For system tools
import sys, datetime

# For reading passwords without echoing
import getpass

# Defines the entry point into the script
def main(argv=None):
    # Print some info
    print
    print "This tool is a sample script that detects stopped services in a folder."
    print  
    
    # Ask for admin/publisher user name and password
    username = raw_input("Enter user name: ")
    password = getpass.getpass("Enter password: ")
    
    # Ask for server name
    serverName = raw_input("Enter server name: ")
    serverPort = 6080

    folder = raw_input("Enter the folder name or ROOT for the root location: ")

    # Create a list to hold stopped services
    stoppedList = []
    
    # Get a token
    token = getToken(username, password, serverName, serverPort)
    if token == "":
        print "Could not generate a token with the username and password provided."
        return
    
    # Construct URL to read folder
    if str.upper(folder) == "ROOT":
        folder = ""
    else:
        folder += "/"
            
    folderURL = "/arcgis/admin/services/" + folder
    
    # This request only needs the token and the response formatting parameter 
    params = urllib.urlencode({'token': token, 'f': 'json'})
    
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    
    # Connect to URL and post parameters    
    httpConn = httplib.HTTPConnection(serverName, serverPort)
    httpConn.request("POST", folderURL, params, headers)
    
    # Read response
    response = httpConn.getresponse()
    if (response.status != 200):
        httpConn.close()
        print "Could not read folder information."
        return
    else:
        data = response.read()
        
        # Check that data returned is not an error object
        if not assertJsonSuccess(data):          
            print "Error when reading folder information. " + str(data)
        else:
            print "Processed folder information successfully. Now processing services..."

        # Deserialize response into Python object
        dataObj = json.loads(data)
        httpConn.close()

        # Loop through each service in the folder and stop or start it    
        for item in dataObj['services']:

            fullSvcName = item['serviceName'] + "." + item['type']

            # Construct URL to stop or start service, then make the request                
            statusURL = "/arcgis/admin/services/" + folder + fullSvcName + "/status"
            httpConn.request("POST", statusURL, params, headers)
            
            # Read status response
            statusResponse = httpConn.getresponse()
            if (statusResponse.status != 200):
                httpConn.close()
                print "Error while checking status for " + fullSvcName
                return
            else:
                statusData = statusResponse.read()
                              
                # Check that data returned is not an error object
                if not assertJsonSuccess(statusData):
                    print "Error returned when retrieving status information for " + fullSvcName + "."
                    print str(statusData)

                else:
                    # Add the stopped service and the current time to a list
                    statusDataObj = json.loads(statusData)
                    if statusDataObj['realTimeState'] == "STOPPED":
                        stoppedList.append([fullSvcName,str(datetime.datetime.now())])
                                  
            httpConn.close()           

    # Check number of stopped services found
    if len(stoppedList) == 0:
        print "No stopped services detected in folder " + folder.rstrip("/")
    else:
        # Write out all the stopped services found
        # This could alternatively be written to an e-mail or a log file
        for item in stoppedList:
            print "Service " + item[0] + " was detected to be stopped at " + item[1]    

    return


# A function to generate a token given username, password and the adminURL.
def getToken(username, password, serverName, serverPort):
    # Token URL is typically http://server[:port]/arcgis/admin/generateToken
    tokenURL = "/arcgis/admin/generateToken"
    
    params = urllib.urlencode({'username': username, 'password': password, 'client': 'requestip', 'f': 'json'})
    
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    
    # Connect to URL and post parameters
    httpConn = httplib.HTTPConnection(serverName, serverPort)
    httpConn.request("POST", tokenURL, params, headers)
    
    # Read response
    response = httpConn.getresponse()
    if (response.status != 200):
        httpConn.close()
        print "Error while fetching tokens from admin URL. Please check the URL and try again."
        return
    else:
        data = response.read()
        httpConn.close()
        
        # Check that data returned is not an error object
        if not assertJsonSuccess(data):            
            return
        
        # Extract the token from it
        token = json.loads(data)        
        return token['token']            
        

# A function that checks that the input JSON object 
#  is not an error object.
def assertJsonSuccess(data):
    obj = json.loads(data)
    if 'status' in obj and obj['status'] == "error":
        print "Error: JSON object returns an error. " + str(obj)
        return False
    else:
        return True
    
        
# Script start
if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
9/14/2013