陈陈 陈陈 [email protected] 陈陈陈陈陈陈陈陈陈陈 陈陈陈陈陈陈陈陈陈陈 Server Management Group Server Management Group Microsoft Corporation Microsoft Corporation IIS6.0 IIS6.0 陈陈 陈陈 陈陈陈陈陈陈陈陈陈陈陈陈 陈陈陈陈陈陈陈陈陈陈陈陈 Web Web 陈陈陈陈 陈陈陈陈 Win301/315 Win301/315
Jan 13, 2016
陈硕陈硕[email protected]软件开发及测试工程师软件开发及测试工程师Server Management GroupServer Management GroupMicrosoft CorporationMicrosoft Corporation
IIS6.0IIS6.0 综述综述及在其基础上建立高性能的及在其基础上建立高性能的WebWeb 应用程序应用程序Win301/315Win301/315
讲座内容浏览:讲座内容浏览: 介绍介绍 IIS6.0 IIS6.0 新的体系结构新的体系结构 ::
PerformancePerformance Reliability Reliability SecuritySecurity ManageabilityManageability
程序设计环境程序设计环境 ASP .NETASP .NET ASPASP ISAPIISAPI
利用利用 Windows .NET Server Windows .NET Server 新特新特色色
IIS6.0IIS6.0 体系结构的改善体系结构的改善 ::
Performance, security, reliability & Performance, security, reliability & manageabilitymanageability
IIS5.0 and IIS6.0 IIS5.0 and IIS6.0 内部设计对照内部设计对照::Windows 2000Windows 2000
Windows .NET ServerWindows .NET Server
DLLHOST.exeDLLHOST.exe
ISAPIISAPIExtensionsExtensions(ASP, etc.)(ASP, etc.)
ISAPI FiltersISAPI Filters
metabasemetabase
IIS 6.0 ArchitectureIIS 6.0 ArchitectureThe transition from IIS5 to IIS6The transition from IIS5 to IIS6
TCP/IPTCP/IP
INETINFOINETINFO
ASP.NETASP.NETISAPIISAPI
Aspnet_wp.exeAspnet_wp.exe
CLR App DomainCLR App Domain
CLR App DomainCLR App Domain
CLR App DomainCLR App Domainmetabasemetabase
INETINFOINETINFO W3WP.EXEW3WP.EXE
Application Pool 1
ASP.NET ISAPIASP.NET ISAPI
CLR App DomainCLR App Domain
CLR App DomainCLR App Domain
W3WP.EXEW3WP.EXE
ISAPIISAPIExtensionsExtensions(ASP, etc.)(ASP, etc.)
ISAPI FiltersISAPI Filters
Application Pool 2
W3WP.EXEW3WP.EXE
ASP.NET ISAPIASP.NET ISAPI
CLR App DomainCLR App Domain
CLR App DomainCLR App Domain
W3WP.EXEW3WP.EXE
ASP.NET ISAPIASP.NET ISAPI
CLR App DomainCLR App Domain
CLR App DomainCLR App Domain
W3WP.EXEW3WP.EXE
ASP.NET ISAPIASP.NET ISAPI
CLR App DomainCLR App Domain
CLR App DomainCLR App Domain
Web Garden
W3WP.EXEW3WP.EXE
ISAPIISAPIExtensionsExtensions(ASP, etc.)(ASP, etc.)
ISAPI FiltersISAPI Filters
WASWAS
Co
nfi
g M
gr
Co
nfi
g M
gr
Pro
ce
ss
Mg
rP
roc
es
s M
gr
HTTP.SYSHTTP.SYS Namespace MapperNamespace Mapper
HTTP EngineHTTP Engine
ResponseResponseCacheCache
Req
Qu
eue
Req
Qu
eue
Req
Qu
eue
Req
Qu
eue
Req
Qu
eue
Req
Qu
eue
Send ResponseSend Response
运行可靠新的增强:运行可靠新的增强:应用程序隔离 应用程序隔离 – – 新处理模型新处理模型
完全进程完全进程 (process)(process) 隔离隔离 1 or more processes 1 or more processes
talking directly to the talking directly to the kernelkernel
Independent from Independent from other processes other processes
Kernel-mode queuingKernel-mode queuing
Application PoolsApplication Pools Web GardensWeb Gardens
HTTP.sysHTTP.sys
WASWAS
Worker Worker ProcessProcess
ISAPI FiltersISAPI Filters
ISAPIISAPIExtensionsExtensions
Worker Worker ProcessProcess
ISAPI FiltersISAPI Filters
ISAPIISAPIExtensionsExtensions
Application PoolApplication Pool Application PoolApplication Pool
纵向伸展纵向伸展特色特色 ::
Processor Affinity:Processor Affinity: 极少的资源竞争极少的资源竞争
(locks)(locks) 处理器关系处理器关系
减小处理器缓存失误数减小处理器缓存失误数 分区负荷分区负荷
拆开网站或应用程序的拆开网站或应用程序的负荷; 将其限制与系负荷; 将其限制与系统特定资源之中统特定资源之中
KernelKernel
UserUser
ISR
DPC
HTTP
W3WP
ISR
DPC
HTTP
W3WP
<IIsApplicationPool Location ="/LM/W3SVC/AppPools/FinanceAppPool" AppPoolFriendlyName="Finance Applications" AutoShutdownAppPoolExe="nlb.exe" AutoShutdownAppPoolParams="drain 173.45.23.41" LoadBalancerCapabilities="1"
SMPAffinitized="TRUE" SMPProcessorAffinityMask="4026531840" .</IIsApplicationPool>
实例对照实例对照NILE appNILE app (商务程序)(商务程序) E-commerce benchmark from Doculabs; Measures the overall performance of E-commerce benchmark from Doculabs; Measures the overall performance of
some scenarios that are commonly used by e-commerce sitessome scenarios that are commonly used by e-commerce sites Logon, browse items, search, shopping cart operations, check outLogon, browse items, search, shopping cart operations, check out Static file caching, data-base operations, session state managementStatic file caching, data-base operations, session state management
W2K - ASP .NET Server -ASP
W2K - ASP.NET .NET Server -ASP.NET
1P4P8P
4P: +15%8P: +25%
运行可靠性运行可靠性 (Reliability)(Reliability) 一览:一览:
新处理模式解决应用程序的隔离新处理模式解决应用程序的隔离(Worker process for application (Worker process for application
isolation)isolation)
回收功能回收功能 (recycling)(recycling) 及健康测试及健康测试(Health detection)(Health detection)
更完善的调试及进程管理更完善的调试及进程管理
Hosting Hosting Site isolation and resource useSite isolation and resource use
Application Pool resource Application Pool resource usage is “virtual”usage is “virtual” HTTP.SYS listens to site HTTP.SYS listens to site
endpoints (IP/Port/Header)endpoints (IP/Port/Header) User-mode system User-mode system
resources consumed only resources consumed only when a site receives when a site receives requestsrequests
If active site does not get a If active site does not get a request for 20 minutes, request for 20 minutes, worker process is idled outworker process is idled out
Increased IIS worker Increased IIS worker process limit on process limit on Windows .NETWindows .NET
Making Applications More ReliableMaking Applications More ReliableApplication PoolsApplication Pools Can create 1 or more Can create 1 or more
application poolsapplication pools Each served by 1 or Each served by 1 or
more W3WP.exe’s.more W3WP.exe’s. Each W3WP.exe Each W3WP.exe
serves only 1 pool.serves only 1 pool. Reqs routed directly Reqs routed directly
to pool by HTTP.systo pool by HTTP.sys
Isolate apps based Isolate apps based on:on: Site/CustomerSite/Customer FunctionalityFunctionality ReliabilityReliability
Making Applications More ReliableMaking Applications More ReliablePeriodic Process RecyclingPeriodic Process Recycling
What is it?What is it? Periodically restart Periodically restart
applications based applications based on:on: UptimeUptime # of requests# of requests Scheduled timeScheduled time Memory consumptionMemory consumption On-demandOn-demand
Why use it?Why use it? Refresh apps to Refresh apps to
ensure availabilityensure availability Prevent bad apps Prevent bad apps
from taking over the from taking over the systemsystem
demodemo
Application Pool and Application Pool and RecyclingRecycling
SSLSSL(( 安全套接字层安全套接字层 )) 的拓展的拓展 SSL StreamFilter can be hosted in LSASS.EXE SSL StreamFilter can be hosted in LSASS.EXE
process (can give up to 25% throughput gains in process (can give up to 25% throughput gains in SSL loads)SSL loads) Reduction of cross-process marshalling and context Reduction of cross-process marshalling and context
switching for SSL interactionsswitching for SSL interactions Not hosted by default as could force service packs to Not hosted by default as could force service packs to
require rebootsrequire reboots No application change – just configure through No application change – just configure through
registry switchregistry switch
Progressive SSL thread poolProgressive SSL thread pool Load-aware and adjusts parallelism depending on loadLoad-aware and adjusts parallelism depending on load
Significant performance work on MP machinesSignificant performance work on MP machines (increases up to 2X for some workloads on 8P machines)(increases up to 2X for some workloads on 8P machines)
Securing ApplicationsSecuring ApplicationsLocked Down by DefaultLocked Down by Default
IIS not installed on a clean install by defaultIIS not installed on a clean install by default And disabled on upgradesAnd disabled on upgrades
IIS serves static files by defaultIIS serves static files by default 404’s for disabled application extensions (404.2)404’s for disabled application extensions (404.2)
Substatus codes logged in W3C logs by default nowSubstatus codes logged in W3C logs by default now Only 404 sent to clientOnly 404 sent to client
ASP.NET, FPSE, & FTP not installed by default ASP.NET, FPSE, & FTP not installed by default ASP.NET enabled when installed ASP.NET enabled when installed
Only Known extensions servedOnly Known extensions served Unknown extension = 404.3Unknown extension = 404.3
New Security Console used to enable app extensions:New Security Console used to enable app extensions: Individual ISAPI extensions and CGI’sIndividual ISAPI extensions and CGI’s
Example: Enable FPSE & ASP.NET to publish via VS.NET for Intranet or Example: Enable FPSE & ASP.NET to publish via VS.NET for Intranet or Dev serverDev server
Or just enable ASP.NET to allow ASP.NET apps to be served.Or just enable ASP.NET to allow ASP.NET apps to be served.
Demo:Demo:
Web Service Extensions Web Service Extensions ConsoleConsole
Making .NET Applications Making .NET Applications More ManageableMore ManageableMetabase improvementsMetabase improvements
XML MetabaseXML Metabase Metabase now stored Metabase now stored
in XMLin XML Auto-versioning: Like an Auto-versioning: Like an
automatic backupautomatic backup Edit while runningEdit while running
Make changes directly to Make changes directly to the metabase.xml file the metabase.xml file while IIS is runningwhile IIS is running
Any editor can be used – Any editor can be used – Notepad.NET, PERL, etc.Notepad.NET, PERL, etc.
Admin Base ObjectsAdmin Base Objects
ADSIADSI UIUI
Metabase.xmlMetabase.xml MBSchema.xmlMBSchema.xml
Making .NET Applications Making .NET Applications More ManageableMore ManageableMetabase improvements – Import/exportMetabase improvements – Import/export
Export/import metabase config Export/import metabase config to/from XMLto/from XML
Options includeOptions include Export/Import inherited propertiesExport/Import inherited properties Export/Import node only (or entire Export/Import node only (or entire
subtree)subtree) Password encrypt exported filePassword encrypt exported file
Use w/ASP .NET XCOPY Use w/ASP .NET XCOPY deployment of appsdeployment of apps1.1. Export IIS6 metabase config Export IIS6 metabase config
for .NET appfor .NET app
2.2. store in .NET app directorystore in .NET app directory
3.3. Import app metabase config file Import app metabase config file after XCOPYafter XCOPY
Admin Base ObjectsAdmin Base Objects
ADSIADSI UIUI
Metabase.xmlMetabase.xml MBSchema.xmlMBSchema.xml
demodemo
运行中更改运行中更改配置除据库配置除据库 (metabase)(metabase)
IIS6.0 IIS6.0 程序设计环境程序设计环境 ::
WebWeb 应用程序的可伸缩性应用程序的可伸缩性(Scalability)(Scalability)
StatelessStateless Application code and components can be restarted cheaply; Application code and components can be restarted cheaply;
Session state is managed externally in some sort of state storeSession state is managed externally in some sort of state store Low initialization costsLow initialization costs
Applications should avoid doing heavy processing at startup Applications should avoid doing heavy processing at startup or assume that they will run for a long time;or assume that they will run for a long time;
Multi-instance-ableMulti-instance-able All the components / classes of an application should be happy All the components / classes of an application should be happy
to have multiple instances in separate processes without to have multiple instances in separate processes without namespace or locking issuesnamespace or locking issues
Expect administrator imposed limitsExpect administrator imposed limits Your application is likely to haveYour application is likely to have
CPU limits;CPU limits; Memory Limits;Memory Limits; Processor affinity imposedProcessor affinity imposed
Dynamic Kernel CachingDynamic Kernel CachingGET http://www.acme.com/store/sproketcatalog.aspxGET http://www.acme.com/store/sproketcatalog.aspx
Cache
Network Stack
HTTP.SYS
W3WP.EXE (IIS6.0)
ASP.NET/CLR
User Application
UserKernel
Database
RequestRequest ResponseResponse
WithoutWithoutCacheCache
Cache
Network Stack
HTTP.SYS
W3WP.EXE (IIS6.0)
ASP.NET/CLR
User Application
UserKernel
Database
WithWithCacheCache
RequestRequest ResponseResponse
<%@ OutputCache Duration="10" VaryByParam="none" %>
Increasing .NET Scale Increasing .NET Scale And PerformanceAnd PerformanceCaching responses in HTTP.SYSCaching responses in HTTP.SYS
ASP .NET is able to cache complete responses in ASP .NET is able to cache complete responses in HTTP.SYSHTTP.SYS Responses marked as Location=“Server”Responses marked as Location=“Server”
Cached responses served straight from HTTP.SYSCached responses served straight from HTTP.SYS Much faster when served from kernel – no Much faster when served from kernel – no
user-mode transitionuser-mode transition Your apps won’t see requests if served from cache Your apps won’t see requests if served from cache
Invalidation of cached complete responses (Server) Invalidation of cached complete responses (Server) same as in IIS5same as in IIS5
<%@ OutputCache Location=“<%@ OutputCache Location=“ServerServer” … %>” … %>
WorkerWorker
processprocess
ISAPIISAPIExtensionExtension
ISAPI filterISAPI filter
WorkerWorker
processprocess
ISAPIISAPIExtensionExtension
ISAPI filterISAPI filter
Increasing .NET Scale Increasing .NET Scale And PerformanceAnd PerformanceIIS 6 Web Gardens and Processor AffinityIIS 6 Web Gardens and Processor Affinity
Web GardensWeb Gardens App Pool with > 1 worker App Pool with > 1 worker
processprocess Connection-based Connection-based
routing w/in Gardenrouting w/in Garden
Processor AffinitizationProcessor Affinitization Bind app pool Bind app pool
process/es to 1 or process/es to 1 or more CPUsmore CPUs
Mask-based configMask-based config HTTP.SYSHTTP.SYS
WorkerWorker
processprocess
ISAPIISAPIExtensionExtension
ISAPI filterISAPI filter
WorkerWorker
processprocess
ASP .NETASP .NET
ISAPI filterISAPI filter
Web Garden Web Garden application poolapplication pool
WASWAS
ASP ConsiderationsASP Considerations Run ASP in COM+ MTA for sites Run ASP in COM+ MTA for sites
that have “Both” and “Free” that have “Both” and “Free” threaded componentsthreaded components
Cache adjustments – avoid ASP Cache adjustments – avoid ASP page compilationpage compilation Template cache should be big Template cache should be big
enough to hold “hot” pagesenough to hold “hot” pages Script engine cache should also hold Script engine cache should also hold
“hot” pages“hot” pages
Intrinsic improvements for ASPIntrinsic improvements for ASP ASP does asynchronous writes to ASP does asynchronous writes to
the network (more efficient in terms the network (more efficient in terms of number of threads of number of threads in the OS)in the OS)
ASP uses VectorSend() under ASP uses VectorSend() under the coversthe covers
Win2K Win.NET
1P
4P
8P
~50%~50%
ASP .NET ASP .NET 应用指南应用指南 内核模式内核模式 (kernel)(kernel) 控制输出缓存控制输出缓存
Better performance than current output cache Better performance than current output cache (kernel served)(kernel served)
Should consider what information needs to be Should consider what information needs to be absolutely current and what information can be absolutely current and what information can be a little stalea little stale
缓存粹片(缓存粹片( Fragment cacheFragment cache )) Use for expensive-to-construct portions of pages Use for expensive-to-construct portions of pages
(PartialCaching attribute)(PartialCaching attribute)
进程内运行(进程内运行( in-processin-process )) All processing done in-processAll processing done in-process Default on Windows 2000 involved a Default on Windows 2000 involved a
process hopprocess hop Try to stay in managed code – avoid Try to stay in managed code – avoid
Interop if possibleInterop if possible If you are running Interop scenarios run If you are running Interop scenarios run
COM object in processCOM object in process
ASP .NET ASP .NET 在 在 .NET Server .NET Server 上的内在收益上的内在收益 ASP .NET leverages new ISAPI featuresASP .NET leverages new ISAPI features ASP .NET/IIS implement a fast path for common case ASP .NET/IIS implement a fast path for common case
response headersresponse headers
W3WP.EXE
ISAPIISAPI
内核模式内核模式用户模式用户模式
HTTP.SYSHTTP.SYS
ASP .NET / ASP .NET / CLRCLR
APIAPI(( 处理应用程序接口处理应用程序接口 )/)/ 技术选择技术选择托管代码托管代码 ((Managed Code)Managed Code) 与非托管代码与非托管代码 (Unmanaged (Unmanaged Code)Code)
ManagedManaged Very high level of Very high level of
functionalityfunctionality Great performanceGreat performance Rapid application Rapid application
developmentdevelopment Wide variety of languages Wide variety of languages
to choose fromto choose from Familiar to VB and script Familiar to VB and script
writerswriters
UnmanagedUnmanaged More control over the More control over the
requestrequest Highest potential Highest potential
performanceperformance Complete control over Complete control over
processing chainprocessing chain C and C++C and C++
ISAPI ISAPI 应用指南应用指南 C++/native code through ISAPI C++/native code through ISAPI
Do NOT do your processing on the Do NOT do your processing on the ISAPI threadISAPI thread
Always send using asynchronous Always send using asynchronous send APIssend APIs; ISAPI on Windows .NET ; ISAPI on Windows .NET Server is no longer tolerant of Server is no longer tolerant of synchronous writes – performance synchronous writes – performance will sufferwill suffer
Use VectorSend/FinalSend Use VectorSend/FinalSend combinationcombination
Where possible cache responsesWhere possible cache responses Cleanup in TerminateExtension() Cleanup in TerminateExtension()
calls – they will be called frequentlycalls – they will be called frequently Review use of ISAPI Filters and if Review use of ISAPI Filters and if
possible try and removepossible try and remove
W3WP.EXE
ISAPIISAPINativeNative
kernelkernel
useruser
HTTP.SYSHTTP.SYS
利用利用 Windows .NET Windows .NET 新特色新特色
Applications Architecture On Applications Architecture On Multiprocessor MachinesMultiprocessor Machines Application Locks are the Application Locks are the
scalability killerscalability killer for managed and for managed and unmanaged codeunmanaged code Look at usage of synchronization primitives Look at usage of synchronization primitives
Monitors, WaitHandle class (Mutex, Monitors, WaitHandle class (Mutex, AutoReset Events, ReaderWriter locks, etc.)AutoReset Events, ReaderWriter locks, etc.)
Consider partitioned data structures Consider partitioned data structures for applicationsfor applications Should every request lock and traverse a long Should every request lock and traverse a long
linked list?linked list? Can request data be instanced on a Can request data be instanced on a
per request basis per request basis How is my global data referenced?How is my global data referenced? C
onnection State D
ata
Request 1Request 1 Request 2Request 2
如何编写更好的程序?如何编写更好的程序? GeneralGeneral
Stateless applications (manage Stateless applications (manage state separately)state separately)
Low initialization cost/processingLow initialization cost/processing Applications should be able to be Applications should be able to be
multi-instancedmulti-instanced Expect limitationsExpect limitations
CPUCPU Memory and othersMemory and others
如何编写更好的程序?如何编写更好的程序? ASP .NETASP .NET
Use intrinsic response cachingUse intrinsic response caching Avoid COM+ Interop – if have to try to minimize Avoid COM+ Interop – if have to try to minimize
the number of transitions between managed and the number of transitions between managed and unmanaged code (marshalling cost)unmanaged code (marshalling cost)
Run everything in-processRun everything in-process
ASPASP Setting cache appropriatelySetting cache appropriately Check if COM+ components are “Free” or “Both” Check if COM+ components are “Free” or “Both”
threaded; Run in the MTAthreaded; Run in the MTA When on .NET Server: Run COM+ components in When on .NET Server: Run COM+ components in
process (Local Server)process (Local Server)
如何编写更好的程序?如何编写更好的程序? ISAPIISAPI
Review for best practicesReview for best practices Don’t execute on the IIS thread, maintain small threadpoolDon’t execute on the IIS thread, maintain small threadpool Use Async IO wherever possible (that includes using Use Async IO wherever possible (that includes using
Async version of VectorSend and WriteClient()Async version of VectorSend and WriteClient()
Re-architect ISAPI filters into extensionsRe-architect ISAPI filters into extensions Consider changing WriteClient calls to VectorSend Consider changing WriteClient calls to VectorSend
and specify FinalSend flag when completeand specify FinalSend flag when complete Determine if certain dynamic responses can be Determine if certain dynamic responses can be
stale; If true, cache themstale; If true, cache them
阅读参考:阅读参考: Internet Information Server (IIS) 6 OverviewInternet Information Server (IIS) 6 Overview
http://www.microsoft.com/TechNet/prodtechnol/iis/evaluate/iis6http://www.microsoft.com/TechNet/prodtechnol/iis/evaluate/iis6ovw.asp?frame=trueovw.asp?frame=true
ASP .NET Performance TipsASP .NET Performance Tips http://www.gotdotnet.com/team/asp/ASP.NET%20Performance%http://www.gotdotnet.com/team/asp/ASP.NET%20Performance%
20Tips%20and%20Tricks.aspx20Tips%20and%20Tricks.aspx
Managed Code Analysis ToolsManaged Code Analysis Tools Intel’s VTune Intel’s VTune
http://www.intel.com/software/products/vtune/vtune60/index.hthttp://www.intel.com/software/products/vtune/vtune60/index.htmm
Numega’s TrueTime Numega’s TrueTime www.numega.comwww.numega.com
Sessions Sessions DEV330: ASP .NET: Performance Tuning and CachingDEV330: ASP .NET: Performance Tuning and Caching