def CreateCache(inputService, cachepath): # List of input variables for map service properties tilingSchemeType = "NEW" scalesType = "CUSTOM" numOfScales = "4" scales = [ 12800000000, 6400000000, 3200000000, 1600000000, 800000000, 420263243 ] #,125000000,32000000 dotsPerInch = "96" tileOrigin = "0 0" tileSize = "256 x 256" cacheTileFormat = "JPEG" tileCompressionQuality = "75" storageFormat = "COMPACT" predefinedTilingScheme = "#" try: starttime = time.clock() result = arcpy.CreateMapServerCache_server( inputService, cachepath, tilingSchemeType, scalesType, numOfScales, dotsPerInch, tileSize, predefinedTilingScheme, tileOrigin, scales, cacheTileFormat, tileCompressionQuality, storageFormat) # print messages to a file while result.status < 4: time.sleep(0.2) resultValue = result.getMessages() print "completed " + str(resultValue) except Exception, e: # If an error occurred, print line number and error message tb = sys.exc_info()[2] print "Failed at step 1 \n" "Line %i" % tb.tb_lineno print e.message
def createCache(inputService, i): # List of input variables for map service properties # connectionFile = r"C:\Users\<username>\AppData\Roaming\ESRI\Desktop10.1\ArcCatalog" # server = "arcgis on MyServer_6080 (publisher)" # serviceName = "Rainfall.MapServer" serviceCacheDirectory = "C:\\arcgisserver\\directories\\arcgiscache" scalesType = "" tileOrigin = "" numOfScales = "5" scales = "64000000,32000000,16000000,8000000,4000000" dotsPerInch = "96" tileSize = "256 x 256" cacheTileFormat = "JPEG" tileCompressionQuality = "75" storageFormat = "COMPACT" tilingSchemeType = "NEW" scalesType = "CUSTOM" predefinedTilingScheme = "" inputService = inputService + ".MapServer" print inputService print "begin cache" + str(i) result = arcpy.CreateMapServerCache_server( inputService, serviceCacheDirectory, tilingSchemeType, scalesType, numOfScales, dotsPerInch, tileSize, predefinedTilingScheme, tileOrigin, scales, cacheTileFormat, tileCompressionQuality, storageFormat) print "cachesuccessfullly" + str(i)
def CreateCache(inputService, cachedir, tilingSchemePath): # List of input variables for map service properties input_service = inputService serviceCacheDirectory = cachedir tilingSchemeType = "PREDEFINED" scalesType = "" tileOrigin = "" scalesType = "" numOfScales = "" scales = "" dotsPerInch = "96" tileSize = "256 x 256" cacheTileFormat = "PNG" # 保存为PNG格式,保证裁剪区域透明;保存为JPEG时不透明。 tileCompressionQuality = "75" storageFormat = "EXPLODED" predefinedTilingScheme = tilingSchemePath currentTime = datetime.datetime.now() arg1 = currentTime.strftime("%H-%M") arg2 = currentTime.strftime("%Y-%m-%d %H:%M") file = 'C:/data/report_%s.txt' % arg1 # print results of the script to a report report = open(file, 'w') try: starttime = time.clock() result = arcpy.CreateMapServerCache_server( input_service, serviceCacheDirectory, tilingSchemeType, scalesType, numOfScales, dotsPerInch, tileSize, predefinedTilingScheme, tileOrigin, scales, cacheTileFormat, tileCompressionQuality, storageFormat) finishtime = time.clock() elapsedtime = finishtime - starttime #print messages to a file while result.status < 4: time.sleep(0.2) resultValue = result.getMessages() report.write("completed " + str(resultValue)) print "Created cache schema using predefined tiling schema for " + "serviceName" + " in " + str(elapsedtime) + " sec \n on " + arg2 except Exception, e: # If an error occurred, print line number and error message tb = sys.exc_info()[2] report.write("Failed at step 1 \n" "Line %i" % tb.tb_lineno) report.write(e.message)
def execute(self, parameters, messages): """The source code of the tool.""" agspath = "C:/Users/Mr.HL/AppData/Roaming/ESRI/Desktop10.2/ArcCatalog/arcgis on localhost_6080 (admin).ags" mxdpath = parameters[0].valueAsText new_mxd = arcpy.mapping.MapDocument(mxdpath) dirname = os.path.dirname(mxdpath) mxdname = os.path.basename(mxdpath) dotindex = mxdname.index('.') servicename = mxdname[0:dotindex] messages.addMessage('service_name {0}'.format(servicename)) sddratf = os.path.abspath(servicename + ".sddraft") sd = os.path.abspath(servicename + ".sd") if os.path.exists(sd): os.remove(sd) arcpy.CreateImageSDDraft(new_mxd, sddratf, servicename, "ARCGIS_SERVER", agspath, False, None, "Ortho Images", "dddkk") analysis = arcpy.mapping.AnalyzeForSD(sddratf) # 打印分析结果 messages.addMessage( "the following information wa returned during analysis of the MXD") for key in ('messages', 'warnings', 'errors'): messages.addMessage('---- {0} ----'.format(key.upper())) vars = analysis[key] for ((message, code), layerlist) in vars.iteritems(): messages.addMessage( ' message (CODE {0}) applies to:'.format(code)) for layer in layerlist: messages.addMessage(layer.name) if analysis['errors'] == {}: try: arcpy.StageService_server(sddratf, sd) arcpy.UploadServiceDefinition_server(sd, agspath) messages.addMessage('service successfully published') # 定义服务器缓存 messages.addMessage("开始定义服务器缓存") # list of input variable for map service properties tiling_scheme_type = "NEW" scale_type = "CUSTOM" num_of_scales = 9 scales = [7688, 7200, 6600, 6000, 5400, 4800, 4200, 3600, 3000] dot_per_inch = 96 tile_origin = "-20037700 30198300" # <X>-20037700</X> <Y>30198300</Y> tile_size = "256 x 256" cache_tile_format = "PNG8" tile_compression_quality = "" storage_format = "EXPLODED" predefined_tile_scheme = "" input_service = 'GIS Servers/arcgis on localhost_6080 (admin)/{0}.MapServer'.format( servicename) cache_path = "D:/arcgisserver/directories-new/arcgiscache" try: start_time = time.clock() result = arcpy.CreateMapServerCache_server( input_service, cache_path, tiling_scheme_type, scale_type, num_of_scales, dot_per_inch, tile_size, predefined_tile_scheme, tile_origin, scales, cache_tile_format, tile_compression_quality, storage_format) # message to a file while result.status < 4: time.sleep(0.2) # result_value = result.getMessage() # messages.addMessage('completed {0}'.format(str(result_value))) except Exception, e: tb = sys.exc_info()[2] messages.addMessage('Failed to stop 1 \n Line {0}'.format( tb.tb_lineno)) messages.addMessage(e.message) # 生成切片 messages.addMessage("开始切片") scales = [7688, 7200, 6600, 6000, 5400, 4800, 4200, 3600, 3000] num_of_caching_service_instance = 2 update_mode = "RECREATE_ALL_TILES" area_of_interest = "" wait_for_job_completion = "WAIT" update_extents = "" input_service = 'C:/Users/Mr.HL/AppData/Roaming/ESRI/Desktop10.2/ArcCatalog/arcgis on localhost_6080 (' \ 'admin)/{0}.MapServer'.format(servicename) try: result = arcpy.ManageMapServerCacheTiles_server( input_service, scales, update_mode, num_of_caching_service_instance, area_of_interest, update_extents, wait_for_job_completion) while result.status < 4: time.sleep(0.2) # result_value = result.getMessage() # messages.addMessage('completed {0}'.format(str(result_value))) messages.addMessage( 'Created cache tiles for given schema successfully') except Exception, e: tb = sys.exc_info()[2] messages.addMessage('Failed at step 1 \n Line {0}'.format( tb.tb_lineno)) messages.addMessage(e.message) messages.addMessage("Created Map Service Cache Tiles")
def processJob(ProjectJob, project, ProjectUID, serverConnectionFile): cache_path = ContourConfig.CACHE_FOLDER projectID = ProjectJob.getProjectID(project) ProjectFolder = ProjectFolders.getProjectFolderFromDBRow( ProjectJob, project) derived_filegdb_path = ProjectFolder.derived.fgdb_path contour_folder = ProjectFolder.derived.contour_path # PublishFolder = ProjectFolder.published.path # contour_file_gdb_path = os.path.join(contour_folder, CONTOUR_GDB_NAME) # contourMerged_file_gdb_path = os.path.join(PublishFolder, CONTOUR_NAME_WM) # @TODO: move all the derived contour stuff to a published location # P:\OK_SugarCreekElaine_2006\DERIVED\CONTOUR\SCRATCH\RESULTS\Results.mxd contourMxd_Name = "Results.mxd" # ContourConfig.CONTOUR_MXD_NAME contourMxd_path = os.path.join(contour_folder, "C02Scratch", "RESULTS", contourMxd_Name) # ContourBoundFC = os.path.join(contourMerged_file_gdb_path, ContourConfig.CONTOUR_BOUND_FC_WEBMERC) ContourBoundFC = A05_C_ConsolidateRasterInfo.getRasterBoundaryPath( derived_filegdb_path, DTM) temp = os.path.join(contour_folder, "temp") if os.path.exists(temp): shutil.rmtree(temp) os.mkdir(temp) # Get input parameters mxd = contourMxd_path #.replace('aiotxftw6na01data', 'aiotxftw6na01') #Added replace method 22 Mar 2019 BJN # arcpy.GetParameterAsText(0) ## 2018051 EI: Switched to using envelope here to create all cache tiles. Use AOI for import in C04 #areaOfInterest = ContourBoundFC # arcpy.GetParameterAsText(1) areaOfInterest = "" updateExtents = ContourBoundFC #.replace('aiotxftw6na01data', 'aiotxftw6na01') #Added replace method 22 Mar 2019 BJN # arcpy.GetParameterAsText(1) localServer = serverConnectionFile # arcpy.GetParameterAsText(2) serviceName = "{}_{}".format( projectID, ContourConfig.CONTOUR_2FT_SERVICE_NAME) # arcpy.GetParameterAsText(3) folder = ProjectJob.getState(project) # arcpy.GetParameterAsText(4) # Using the temp folder to create service definition files sddraft = os.path.join( temp, "{}.sddraft".format(serviceName) ) #.replace('aiotxftw6na01data', 'aiotxftw6na01') #Added replace method 22 Mar 2019 BJN sd = os.path.join( temp, "{}.sd".format(serviceName) ) #.replace('aiotxftw6na01data', 'aiotxftw6na01') #Added replace method 22 Mar 2019 BJN tilingScheme = ContourConfig.TILING_SCHEME #.replace('aiotxftw6na01data', 'aiotxftw6na01') #Added replace method 22 Mar 2019 BJN # cwd + "\\NRCS_tilingScheme.xml" #Cache template file #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # The following paths and values can be modified if needed # Path to the local cache folder where project tiles will be created # cacheFolder = cache_path # r"C:\arcgisserver\directories\arcgiscache" # cacheDir = os.path.join(cache_path, serviceName) # if folder is not None and len(folder) > 0: # cacheDir = os.path.join(cache_path, "{}_{}".format(folder, serviceName)) # if os.path.exists(cacheDir): # now = datetime.datetime.now() # updatedCacheDir = "{}_{}{}{}_{}{}{}".format(cacheDir, # ("0000{}".format(now.year))[-4:], # ("00{}".format(now.month))[-2:], # ("00{}".format(now.day))[-2:], # ("00{}".format(now.hour))[-2:], # ("00{}".format(now.minute))[-2:], # ("00{}".format(now.second))[-2:]) # arcpy.AddMessage("The existing cache folder will be moved to: {0}".format(updatedCacheDir)) # shutil.move(cacheDir, updatedCacheDir) # Other map service properties cachingInstances = ContourConfig.CACHE_INSTANCES # This should be increased based on server resources #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- Utility.printArguments([ "mxd", "areaOfInterest", "updateExtents", "serviceName", "folder", "sddraft", "sd", "tilingScheme", "cache_path" ], [ mxd, areaOfInterest, updateExtents, serviceName, folder, sddraft, sd, tilingScheme, cache_path ], "C03 CreateContourCache") # List of scales to create tiles at. If additional scales are needed, the tiling # scheme file needs to be updated as well as this list scales = ContourConfig.CONTOUR_SCALES_STRING # Other map service properties that should not be modified updateMode = "RECREATE_ALL_TILES" # @TODO: Can we change this to recreate missing? waitForJobCompletion = "WAIT" # @TODO: What if we don't wait?? cache_dir_path = os.path.join(cache_path, "{}_{}".format(folder, serviceName)) if os.path.exists(cache_dir_path): arcpy.AddMessage( "Cache directory already exists, only recreating empty tiles: {0}". format(cache_dir_path)) updateMode = "RECREATE_EMPTY_TILES" waitForJobCompletion = "DO_NOT_WAIT" # Construct path for local cached service inputService = os.path.join(localServer, folder, serviceName + ".MapServer") if localServer.endswith(".ags"): inputService = os.path.join(localServer[:-4], folder, serviceName + ".MapServer") arcpy.AddMessage( "Location of new service will be: {0}".format(inputService)) # Create a MapDocument object from the input MXD mapDoc = arcpy.mapping.MapDocument(mxd) # Create the SDDraft file for the local cached service arcpy.AddMessage("Creating draft service definition: {0}".format(sddraft)) arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, serviceName, "ARCGIS_SERVER", localServer, folder_name=folder) # # Parse the SDDraft file in order to modify service properties before publishing # doc = DOM.parse(sddraft) # # Set the antialiasing mode to 'Fast' # newAntialiasingMode = "Fast" # keys = doc.getElementsByTagName('Key') # for key in keys: # if key.hasChildNodes(): # if key.firstChild.data == 'antialiasingMode': # # Modify the antialiasing mode # arcpy.AddMessage("Updating anti-aliasing to: {}".format(newAntialiasingMode)) # key.nextSibling.firstChild.data = newAntialiasingMode # # # Save a new SDDraft file outsddraft = os.path.join(temp + "\\" + serviceName + "_aa.sddraft") # f = open(outsddraft, 'w') # doc.writexml(f) # f.close() updateSDDraft(sddraft, outsddraft) # Analyze the SDDraft file arcpy.AddMessage( "Analyzing draft service definition: {}".format(outsddraft)) analysis = arcpy.mapping.AnalyzeForSD(outsddraft) # Check for analyzer errors if analysis['errors'] == {}: RunUtil.runTool(r'ngce\pmdm\c\C03_B_StageSD.py', [outsddraft, sd, localServer], bit32=True, log_path=ProjectFolder.derived.path) # # arcpy.AddMessage("Staging service definition {}".format(sd)) # # arcpy.StageService_server(outsddraft, sd) # # arcpy.AddMessage("Uploading service definition {} to server {}".format(sd, localServer)) # # arcpy.UploadServiceDefinition_server(sd, localServer) # # arcpy.AddMessage("Service publishing completed") else: # If the SDDraft analysis contained errors, display them arcpy.AddError( "\nERROR\nErrors encountered during analysis of the MXD: " + str(analysis['errors'])) os.remove(sddraft) os.remove(outsddraft) raise Exception( "\nERROR\nErrors encountered during analysis of the MXD: " + str(analysis['errors'])) try: # Create the cache schema for the local project service arcpy.AddMessage("Creating cache schema for service {} in: {}".format( inputService, cache_path)) arcpy.CreateMapServerCache_server( inputService, cache_path, "PREDEFINED", predefined_tiling_scheme=tilingScheme, scales=scales ) # , scales_type="STANDARD", num_of_scales=len(scales)) arcpy.AddMessage("Cache schema created for local project service") except arcpy.ExecuteError: arcpy.AddWarning(arcpy.GetMessages(2)) # Create the cache tiles for the local project service ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') arcpy.AddMessage("Cache creation started at: {0}".format(st)) Utility.printArguments([ "inputService", "scales", "updateMode", "cachingInstances", "areaOfInterest", "updateExtents", "waitForJobCompletion" ], [ inputService, scales, updateMode, cachingInstances, areaOfInterest, updateExtents, waitForJobCompletion ], 'arcpy.ManageMapServerCasheTiles_server') #Added 16 April 2016 BJN arcpy.ManageMapServerCacheTiles_server(inputService, scales, updateMode, cachingInstances, areaOfInterest, updateExtents, waitForJobCompletion) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') arcpy.AddMessage("Cache creation completed at: {0}".format(st)) # Clean up the Service Definition file from the temp folder os.remove(sd)
def publishContourMaster(deploymentFolderPath, serverConnectionFilePath, serviceName, serviceFolder): serviceName = "{}_{}".format(serviceName, ContourConfig.CONTOUR_2FT_SERVICE_NAME) mpk = ContourConfig.EMPTY_MASTER_MPK cache_dir = ContourConfig.CACHE_FOLDER tilingScheme = ContourConfig.TILING_SCHEME # # Get input parameters # serverConnectionFilePath = arcpy.GetParameterAsText(0) # serviceName = arcpy.GetParameterAsText(1) # serviceFolder = arcpy.GetParameterAsText(2) Utility.printArguments(["deploymentFolderPath", "serverConnectionFilePath", "serviceName", "serviceFolder", "cache_dir", "Template MPK", "tilingScheme"], [deploymentFolderPath, serverConnectionFilePath, serviceName, serviceFolder, cache_dir, mpk, tilingScheme], "B04 PublishContourMaster") # Find the master MPK in the current directory # cwd = os.path.dirname(sys.argv[0]) temp = os.path.join(deploymentFolderPath, "temp") if os.path.exists(temp): try: shutil.rmtree(temp) except: pass if not os.path.exists(temp): try: os.mkdir(temp) except: pass # mpk = os.path.join(cwd + "\\emptyMaster.mpk") #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # The following path can be modified if needed # Path to the cache serviceFolder where project tiles will be stored for this service cacheFolder = cache_dir # r"C:\arcgisserver\directories\arcgiscache" cacheDir = os.path.join(cache_dir, serviceName) if serviceFolder is not None and len(serviceFolder) > 0: cacheDir = os.path.join(cache_dir, "{}_{}".format(serviceFolder, serviceName)) if os.path.exists(cacheDir): now = datetime.datetime.now() updatedCacheDir = "{}_{}{}{}_{}{}{}".format(cacheDir, ("0000{}".format(now.year))[-4:], ("00{}".format(now.month))[-2:], ("00{}".format(now.day))[-2:], ("00{}".format(now.hour))[-2:], ("00{}".format(now.minute))[-2:], ("00{}".format(now.second))[-2:]) arcpy.AddMessage("The existing cache folder will be moved to: {0}".format(updatedCacheDir)) shutil.move(cacheDir, updatedCacheDir) #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # Construct path for master contour service inputService = os.path.join(serverConnectionFilePath, serviceFolder, "{}.MapServer".format(serviceName)) if serverConnectionFilePath.endswith(".ags"): inputService = os.path.join(serverConnectionFilePath[:-4], serviceFolder, "{}.MapServer".format(serviceName)) arcpy.AddMessage("Location of new service will be: {0}".format(inputService)) # Extract the master map package arcpy.ExtractPackage_management(mpk, temp) mapDoc = os.path.join(temp, "v103", "emptyMaster.mxd") sddraft = os.path.join(temp, "{}.sddraft".format(serviceName)) sd = os.path.join(temp, "{}.sd".format(serviceName)) # tilingScheme = os.path.join(cwd + "\\NRCS_tilingScheme.xml") # Cache template file arcpy.AddMessage("Creating Map Service Definition Draft {}".format(sddraft)) # Create the SDDraft file for the empty master contour service analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, serviceName, "ARCGIS_SERVER", serverConnectionFilePath, folder_name=serviceFolder) # Check for analyzer errors if analysis['errors'] == {}: arcpy.AddMessage("Staging Map Service Definition {}".format(sd)) arcpy.StageService_server(sddraft, sd) arcpy.AddMessage("Uploading Map Service Definition {} to {}".format(sd, serverConnectionFilePath)) arcpy.UploadServiceDefinition_server(sd, serverConnectionFilePath) arcpy.AddMessage("Service publishing completed") else: # If the SDDraft analysis contained errors, display them arcpy.AddMessage("\nERROR\nThe following errors were encountered during analysis of the map document: " + str(analysis['errors'])) os.remove(sddraft) # Create the empty cache schema for the master contour service arcpy.AddMessage("Creating map service cache at {}".format(cacheFolder)) # List of input variables for map service properties # tilingSchemeType = "PREDEFINED" # scalesType = "" # tileOrigin = "" # numOfScales = ContourConfig.CONTOUR_SCALES_NUM scales = ContourConfig.CONTOUR_SCALES_STRING # dotsPerInch = "96" # tileSize = "256 x 256" # cacheTileFormat = "PNG" # tileCompressionQuality = "75" # storageFormat = "COMPACT" arcpy.CreateMapServerCache_server(input_service=inputService, service_cache_directory=cacheFolder, tiling_scheme_type="PREDEFINED", predefined_tiling_scheme=tilingScheme, # scales_type=scalesType , # dots_per_inch=dotsPerInch, # num_of_scales=numOfScales, # tile_size=tileSize, # cache_tile_format=cacheTileFormat, # storage_format=storageFormat, # tile_compression_quality=tileCompressionQuality, scales=scales ) # Clean up the Service Definition file from the temp serviceFolder os.remove(sd) arcpy.AddMessage("Operation complete")
def mainFunction( mapService, updateMode, tileScheme ): # Get parameters from ArcGIS Desktop tool by seperating by comma e.g. (var1 is 1st parameter,var2 is 2nd parameter,var3 is 3rd parameter) try: # Log start if logInfo == "true": loggingFunction(logFile, "start", "") # --------------------------------------- Start of code --------------------------------------- # # If new cache if updateMode == "New": # If tile scheme file provided if (len(str(tileScheme)) > 0): arcpy.AddMessage("Creating new cache...") # Create cache folders arcpy.CreateMapServerCache_server(mapService, tileScheme, "PREDEFINED", "", "", "", "", "", "0 0", "", "", "0", "COMPACT") # Start caching process arcpy.ManageMapServerCacheTiles_server(mapService, "", "RECREATE_ALL_TILES", "", "", "", "WAIT") else: arcpy.AddError( "Please provide a tiling scheme file for the cache...") # If existing cache to create all tiles if updateMode == "Existing - Recreate All Tiles": # Rebuild the map cache arcpy.AddMessage("Rebuilding cache...") # Start caching process arcpy.ManageMapServerCacheTiles_server(mapService, "", "RECREATE_ALL_TILES", "", "", "", "WAIT") # If existing cache to create empty tiles if updateMode == "Existing - Recreate Empty Tiles": # Rebuild the map cache arcpy.AddMessage("Rebuilding cache...") # Start caching process arcpy.ManageMapServerCacheTiles_server(mapService, "", "RECREATE_EMPTY_TILES", "", "", "", "WAIT") # --------------------------------------- End of code --------------------------------------- # # If called from gp tool return the arcpy parameter if __name__ == '__main__': # Return the output if there is any if output: arcpy.SetParameterAsText(1, output) # Otherwise return the result else: # Return the output if there is any if output: return output # Log start if logInfo == "true": loggingFunction(logFile, "end", "") pass # If arcpy error except arcpy.ExecuteError: # Show the message arcpy.AddError(arcpy.GetMessages(2)) # Log error if logInfo == "true": loggingFunction(logFile, "error", arcpy.GetMessages(2)) # If python error except Exception as e: # Show the message arcpy.AddError(e.args[0]) # Log error if logInfo == "true": loggingFunction(logFile, "error", e.args[0])