During a chat with friends about getting a better performance of SQL Server, the following question emerge... which other optimization apply to SQL server, apart from Best Practices at the Operating System and Application level? Optimizations at the hardware level are also necessary, especially at the Storage level.
With this, we begin to explain the issues of SAN but focusing it to Database Administrators.
There are many factors that affect the proper performance of I / O disks, factors such as shared or dedicated disks, RAID levels, bus speed, HBA configurations; an important point that is often overlooked is alignment in the disk partitions.
Some of the non-disk factors which can present bottlenecks are:
- HBA (Host Bus Adapters) or network interface cards
- Processing capacity of FC (Fibre Channel) or iSCSI ports
- Switch
- Number of paths between the server and storage.
It is important to consider and understand the limits of the components involved in the architecture, some of the limits that are established in the market are:
Component
Limits
SAS cable
Theoretical: 1.5 gigabytes per second (GB/s)
Typical: 1.2 GB/s
PCI-X v1 bus
X4 slot: 750 MB/s
X8 slot: 1.5 GB/s
X16 slot: roughly 3 GB/s
PCI-X v2 bus
X4 slot: 1.5 – 1.8 GB/s
X8 slot: 3 GB/s
Note: Be aware that a PCI-X bus can be v2 compliant but still run at v1 speeds.
Fibre Channel HBAs, switch ports and front end Fibre Channel array ports
4 gigabits per second (Gbps): 360-400 MB/s
8 Gbps: Double the speed of 4 Gbps
Note: Make sure to consider the limits of the PCI bus. An 8-Gbps card requires a PCI-X4 v2 slot or faster.
But how all this is linked with SQL Server? The fundamental unit of data storage in SQL Server is the page (8KB), the space allocated to a data file (mdf or ndf) of a database is logically divided into pages numbered continuously from 0 to n. The operation of I / O disk is provided on a page.
The hard drives are composed of thin plates, circular disks on the surface of which are electronic media that store information. Each side of each plate has thousands of tracks, the set of tracks with the same diameter of the entire surface of the plate form a cylinder (For new devices the cylinder concept is not relevant, since they are not arranged in concentric circles, however it is helpful to understand the origin of terms). Each disk surface has a head dedicated I / O. The tracks are divided into sectors. A sector is the minimum fragment of data that can be read from or write to a hard disk. The new units can offer 1KB sectors, 3KB or 4 KB.
With RAID technology, data is striped across an array of physical disks. This data distribution scheme complements the way that the operating system requests data. The granularity at which data is stored on one disk of the array before subsequent data is stored on the next disk of the array is called the stripe-unit size. The collection of stripe units, from the first disk of the array to the last disk of the array, is called a stripe
But with all this that is the alignment of the partitions? That the effect on the performance of SQL Server? The diagram explains it... The vertical black dotted lines overlaying a red gradient correspond to the boundary between separate physical disks of a RAID group. Versions of Windows preceding Windows Server 2008 displayed the 63 reserved sectors reported by the disk hardware, immediately after which the remainder of the partition was exposed to the user. In these figures, the common sector size of 512 bytes is used, the stripe unit size in the example is 64 KB, And the default 4 KB NTFS cluster size, appropriate for, say, a file server. In the absence of disk alignment forces the eighth 4-KB cluster of user data to be laid across two stripe units, starting with the last empty 512-byte sector of the first stripe unit and continuing on to the second stripe unit. In this default configuration, every eighth cluster is written across two stripe units. This situation is perpetuated throughout the rest of the partition; because every nth cluster crosses stripe unit boundaries, two I/Os are required to perform a read or write.
The file allocation unit size (cluster size) recommended for SQL Server is 64 KB; the preferred 64 KB cluster size for SQL Server combined with the default partition misalignment forces the user data to be laid across two stripe units, starting with the first available sectors of the first stripe unit and continuing on to the second stripe unit. This situation is perpetuated throughout the rest of the partition. In this configuration, every subsequent cluster is written across two tracks or two stripe units—each and every read and write is affected.
The following is an experiment in which we examined the performance of disk, the test was Windows Server 2003 and SQL Server 2005. Executed a query to extract information from SQL Server, for each run DBCC DROPCLEANBUFFERS applied to clean the SQL Server buffer cache with this get satisfactory evidence. Performance counters that were monitored were counter Avg. Disk Transfer/sec objects LogicalDisk and PhysicalDisk objects which are used to measure the latency of the disk. The results show significant improvement compared discs alignment; metrics show improvement greater than 30% between latency and duration.
For review of correct alignment of disks, you should be clear about several concepts:
Starting Partition Offset: is the starting offset in the partition of the volume to ensure the default mapping n data pages in hidden sectors in the early volumes.
Stripe Unit Size: The granularity at which data is stored on one disk of the array before subsequent data is stored on the next disk of the array. This value is provided by your SAN administrator
File Allocation Unit Size: Also known as cluster size, represents the smallest amount of disk space which can be allocated to hold a file and is determined when the partition is formatted by the operating system.
There are two rules, which hold for correct alignment of disks. The results of the following calculations should be an integer value.
Partition_Offset / Stripe_Unit_Size
Stripe_Unit_Size / File_Allocation_Unit_size
Of the two previous rules, the first is the most important for optimal performance.
Examples of Scenarios with misalignment on disks
Given a partition with Partition Starting Offset 32,256 bytes (31.5 Mb) and a Stripe Unit Size size of 65,536 bytes (64 Kb), the result for Partition_Offset ÷ Stripe_Unit_Size is 0.4921875, which is not an integer, so considering that the disks are not aligned.
Example of Scenario with alignment on disks
Given a partition with Partition Starting Offset of 1048576 bytes (1Kb) and with a size of Stripe Unit Size of 65,536 bytes (64 Kb), the result is exactly Partition_Offset÷ Stripe_Unit_Size 8, an exact integer, so we can say that alignment is correct.
After the above is explained, the question we need answered is ... how can I see the current status of the disks?
To review the Starting Offset on a basic disk, we can use the command WMIC (Windows Management Instrumentation Command-line) to obtain data on the disk, the syntax is:
wmic partition get BlockSize, BootPartition, DeviceID, DiskIndex, HiddenSectors, NumberOfBlocks, StartingOffset, Name, Index
The value to check with the previous command is StartingOffset, in this example is aligned to 1024 kb.
You can also get the Starting Offset via DISKPART, selecting the drive to analyze and execute the list partition command, which will get the offset.
To review the Starting Offset of a dynamic disk you will need to use the dmdiag utility with the –v switch
If you want to review the File_Allocation_Unit_Size can run the command
fsutil fsinfo ntfsinfo [drive]
The following example shows the execution of all commands above written.
Summary
Many factors contribute to an optimal disk performance. For disk partitions created with Windows Server 2003, is crucial to validate the correct correlation between the Stripe Unit Size and File Allocation Unit Size as best practice. Windows Server 2008 creates partitions aligned by default. When the servers are updated Windows Server 2003 to Windows Server 2008, existing partitions are not aligned automatically, you should rebuild them for optimal performance.
Saludos comunidad, Esta vez no vamos a atormentarlos con más temas técnicos, esta vez los estamos invitando a que asistan al Sexto Simposio Latinoamericano de SharePoint que se estará llevando a cabo en las oficinas de Microsoft en la Ciudad de México. En esta clase de eventos ustedes podrán estar en contacto con los especialistas de la tecnología para poder preguntar lo que ustedes quieran, y este año habrá charlas con gente de Seguridad, Directorio Activo y Base de datos entre otras, solo tienen que registrarse y listo, un lugar estará reservado para ustedes.
Sólo tienes que hacer clic en: Sexto Simposio Latinoamericano de SharePoint para poder registrarte y reservar tu lugar.
Los esperamos en:
Av. Vasco de Quiroga 1700 PH
Col. Santa Fe, C.P. 01210, México D.F.
Hey there community,
Today we will learn how to create and use WMA or MP3 files as ringtones in our powerfull Windows Phone 7.
Since Microsoft released its Mobile operating system we wished to use our old ringtones from other companies or inclusive from our Windows Mobile phone, today is official we can use WMA and/or MP3 files as ringtones in our phone, but first we need to acomplish some pre-requisites:
Pre-requisites
Procedure:
Enjoy, for more information about please review http://www.microsoft.com/windowsphone/en-us/howto/wp7/start/create-ringtones.aspx
In the last 6 months I have faced two cases of linked servers between a SQL Server 2008 R2 Instance running on Windows Server 2008 R2 and a SQL Server 2000 instance running on Windows 2003 were distributed transactions were not working correctly.
The root cause of the problem is still under investigation, however, trying to understand problem I verified that everything is correctly configured and did some tests.
I review the following points:
- Name resolution was working correctly
- Security setting of the DTC correctly configured
- The linked server without distributed transaction working correctly
- DTCPing worked
- As far as I remember the DTCTester also worked.
After all this points the distributed transactions were still failing. In my tests, I tried creating a Clustered DTC in the SQL Server Group and the distributed transactions continue failing.
Later, without much hope, I tried deleting all the clustered DTC’s and configuring the local DTC, to my surprise, it worked.
At this point the question changed to What disadvantages do I have if I use the local DTC instead of a clustered DTC?, so I had to research and test this point.
The first point is, What is the reason to use a clustered DTC?, before Windows 2008, the reason was that it was the only way we could use the DTC on clustered environment, however, in Windows 2008 the number of options increased and now we can create more than one clustered DTC and also use the local DTC on each node. What are the advantages of a clustered DTC and what are the limitations of using the local?
The short answer (based in my knowledge and tests) is that in some scenarios it is better to use the clustered DTC but in most cases the difference is so small that using the local DTC instead of the clustered DTC doesn’t add a significant risk.
When is preferable to use the clustered DTC instead of the local DTC? , One scenario is when you have multiple instances of SQL Server in each node. In this case, multiple instances of SQL Server will use a single DTC which, in extreme cases, could cause bottleneck, if you want more scalability then you need multiple clustered DTC’s.
Another scenario is when the local DTC fails, in that case, the SQL instances won’t failover automatically. If you need more high availability for the distributed transactions it is better to use the clustered DTC.
In summary, it is recommended to use clustered DTC’s, however , if you are having problems with the clustered DTC, you can try with the local DTC.
“The opinions and views expressed in this blog are those of the author and do not necessarily state or reflect those of Microsoft”
¿Qué es Integration Services?
Es una herramienta que permite obtener datos de diversas fuentes, transformarlos y cargarlos a bases de datos, hojas de trabajo, archivos de texto u otro destino que sea compatible con OLE-DB.
Historia
En las versiones SQL Server 7 y 2000, las capacidades de ETL (Extracción, Transformación y Carga) eran provistas por Data Transformation Services (DTS)
A partir de SQL Server 2005, Microsoft decidió que la gran variedad de innovaciones implementadas en la nueva versión justificaban el nuevo nombre. Como resultado surgió SQL Server Integration Services (SSIS)
Mejoras en la versión 2012 de SSIS
Cambios generales en la interfaz
1. Caja de herramientas de SSIS
La caja de herramientas de SSIS te permite agregar treas y componentes del flujo de data a un paquete, en vez de usar la caja de herramientas de Visual Studio, que se utiliza en versiones anteriores. Además incluye una descripción para el ítem que está seleccionado. También incluye dos categorías: Favoritos y Común.
2. Parámetros
El diseñador del paquete incluye una nueva lengüeta para abrir la ventana de los parámetros para un paquete. Los parámetros permiten que usted especifique los valores en tiempo de ejecución para el paquete, el contenedor, y las propiedades de la tarea o las variables.
3. Botón de variable
Este nuevo botón en la barra de herramientas del diseñador del paquete proporciona el acceso rápido a la ventana de las variables.
4. Botón de Caja de herramientas de SSIS
Este botón permite que usted abra la caja de herramientas de SSIS cuando no es visible.
5. Comenzando (Getting Started)
Proporciona el acceso a los enlaces de los vídeos y los ejemplos que usted puede utilizar para aprender a trabajar con Integration Services.
6. Control de Acercamiento (Zoom control)
Usted puede acercar o alejar a un tamaño máximo de 500 por ciento de la visión normal o a un tamaño mínimo del 10 por ciento, respectivamente.
7. Administrador de Conexiones Compartidas (Shared Connection Managers)
La carpeta Administrador de Conexiones es un nuevo contenedor que puede ser compartido entre múltiples paquetes. Para crear un nuevo Administrador de Conexiones compartidas siga los siguientes pasos:
8. Deshacer y Rehacer (Undo / Redo)
Estas opciones fueron añadidas como parte de las herramientas de datos de SQL Server. A través de esta opción se puede editar el control de flujo o flujo de datos y revertir o reaplicar los cambios. Estas opciones también funcionan en la ventana de variables, en el manejador de eventos y parámetros. Se puede utilizar Ctrl+Z para Deshacer o Ctrl+Y para reaplicar.
9. Paquetes ordenados por Nombre
Los paquetes pueden ser ordenados por nombre al presionar el botón de la derecha del ratón sobre la carpeta Paquetes de SSIS.
10. Indicador de estatus
La interfaz del usuario ahora presenta íconos en la esquina superior derecha de cada ítem para indicar si la ejecución fue exitosa o fallida.
Control de flujo
1. Tarea de Expresión
El propósito de esta tarea es el facilitar la asignación de un valor dinámico a una variable.
2. Tarea de Ejecución de Paquete
Esta tarea incluye una nueva propiedad llamada Tipo de Referencia que permite especificar la localización del paquete a ser ejecutado. Si se selecciona Referencia del Proyecto, usted podrá seleccionar el paquete hijo desde una lista. Si se selecciona Referencia Externa, usted podrá configurar la ruta del paquete hijo como se hacía en versiones anteriores.
Flujo de Datos
Entre las mejoras se encuentran:
1. Los Asistentes para la selección de fuentes y destinos.
2. Transformaciones de Merge y Merge Join
Estas transformaciones permiten recolectar datos de dos fuentes y producir una sola salida de los resultados combinados. La versión actual se ajusta automáticamente a las presiones de memoria.
3. Transformación de Limpieza de Datos para DQS
Es un nuevo componente que se usa en conjunto con Data Quality Services (DQS)El propósito es ayudar a mejorar la calidad de los datos a través de reglas establecidas para el dominio de los datos. Se pueden crear reglas para hacer pruebas a los datos por errores comunes como errores de escritura en un campo tipo texto o asegurar que el largo de una columna cumple con las especificaciones.
4. Grupo que puede ser Colapsado
Permite consolidar los componentes del flujo de datos en grupos que pueden expandir o colapsar. Para crear un grupo, siga los siguientes pasos:
Transferencia del Proyecto (Deployment)
En SSIS 2012 se utiliza un proyecto el cual es almacenado en un archivo con la extensión ISPAC. El proyecto es una colección de paquetes y parámetros. Usted puede transferir el proyecto a un catálogo de Integration Services. A diferencia de versiones anteriores donde se utilizaban configuraciones, en esta versión se utilizan parámetros para asignar valores a las propiedades del proyecto en tiempo de ejecución. Antes de ejecutar un paquete, se debe crear un objeto de ejecución en el catálogo y opcionalmente asignarle valores a los parámetros o hacer referencia al ambiente del objeto de ejecución.
El catálogo de SSIS esencialmente es una aplicación de SQL (una base de datos del usuario en una instancia de SQL con un conjunto de procedimientos almacenados y un API de T-SQL.
Creación del catálogo
El instalar Integration Services no crea automáticamente el catálogo. Para crear el catálogo hay que realizar los siguientes pasos:
1) En SQL Server Management Studio, conéctese a la instancia, presione el botón de la derecha del ratón sobre la carpeta de Integration Services en el Explorador de Objetos y seleccione Crear el Catálogo.
2) En la pantalla de Creación del Catálogo, seleccione la opción de habilitar la integración CLR. Esta opción es requerida para administrar la funcionalidad de Integration Services.
3) Opcionalmente se puede seleccionar la opción de Ejecución automática de Procedimientos Almacenados de Integration Services. Este procedimiento almacenado realiza una operación de limpieza cuando el servicio se ejecuta y ajusta el estatus de los paquetes que fueron ejecutados cuando el servicio es detenido.
4) El nombre de la base de datos no puede ser cambiado (SSISDB) así que como paso final se requiere proveer una contraseña compleja y presionar OK. La contraseña crea una llave maestra a nivel de base de datos que es utilizada por Integration Services para cifrar los datos sensitivos que han sido almacenados en el catálogo.
Herramientas para detección de fallas y bitácoras
Los reportes de Integration Services localizados en SQL Server Management Studio proveen información a cerca de los resultados de ejecución de los paquetes en las últimas 24 horas. Estos incluyen información de rendimiento y mensajes de error para el caso de los paquetes fallidos.
Cambios en el formato de los paquetes
La meta de estos cambios fue el facilitar la lectura e identificar más fácilmente las diferencias cuando se trabaja con sistemas de control de fuentes.
Formato de SSIS 2008
Formato de SSIS 2012
Resumen
Unos de los cambios mayores es la introducción del modelo de proyecto para simplificar los cambios a los valores del paquete en tiempo de ejecución. Un beneficio de este modelo es el catálogo. El catálogo almacena información a cerca de paquetes, validaciones, y resultados de ejecución en tablas que pueden ser consultadas a través de vistas o de reportes. El acceso a la información nos provee de una gran visibilidad de Integration Services lo cual no era posible realizar fácilmente en versiones anteriores.
“Las opiniones e ideas expresadas en este blog son las de los Autores y no necesariamente declaran o reflejan la opinión de Microsoft”
Este material tambien lo podras acceder en http://blogs.technet.com/b/sql_pfe_latam/
What is Integration Services?
SQL Server Integration Services (SSIS) is a tool to allow for gathering of data from diverse sources, scrubbing and homogenizing the data into a format for unified use, and loading that data into databases, spreadsheets, text files, or any other OLE-DB compliant destination.
History
In SQL Server 7.0 and 2000, ETL capabilities have been provided by Data Transformation Services (DTS). With the advent of SQL Server 2005, Microsoft decided that a wide range of ETL related innovations implemented in the new version justified its re-branding, resulting in the introduction of SQL Server Integration Services (SSIS).
SQL 2012 SSIS Enhancements
General Interface Changes
SSIS Toolbox: The SSIS Toolbox add tasks and data flow components to a package, rather than the Visual Studio toolbox that you use in earlier versions of Integration Services.
Parameters: The package designer includes a new tab to open the Parameters window for a package. Parameters allow you to specify run-time values for package, container, and task properties or for variables.
Variables button: This new button on the package designer toolbar provides quick access to the Variables window.
SSIS Toolbox button: This button allows you to open the SSIS Toolbox when it is not visible.
Getting Started: Provides access to links to videos and samples that you can use to learn how to work with Integration Services.
Zoom control: You can zoom in or out to a maximum size of 500 percent of the normal view or to a minimum size of 10 percent, respectively.
Shared Connection Managers: The Connections Manager folder is the new container for connection managers that you want to share among multiple packages. To create a shared connection manager, follow these steps:
Undo and Redo: Is the newly added ability to use Undo and Redo while developing packages in the SQL Server Data Tools.You can now make edits in either the control flow or data flow designer surface, and use Undo to reverse a change or Redo to restore a change that you had just reversed. This capability also works in the Variables window, and on the Event Handlers and Parameters tabs. You can also use Undo and Redo when working with project parameters. You can also use Ctrl+Z for Undo or Ctrl+Y for Redo
Package Sort By Name: Sort the list of packages without closing the project by right-clicking the SSIS Packages folder, and selecting Sort By Name.
Status Indicators: The user interface now displays icons in the upper-right corner of each item to indicate success or failure
Control Flow
Apart from the general enhancements to the package designer interface, there are two notable updates for the control flow.
Expression Task: The purpose of this task is to make it easier to assign a dynamic value to a variable.
Execute Package task: Include a new property, ReferenceType, which you use to specify the location of the package to execute. If you select Project Reference, you then choose the child package from the drop-down list. If you select External Reference, you configure the path to the child package just as you do in earlier versions of Integration Services.
Dataflow
The data flow also has some significant updates. Some user interface changes have also been made to simplify the process and help you get your job done faster when designing the data flow.
Source and Destination Assistants: Add the Source Assistant to the data flow design surface by using drag-and-drop or by double-clicking the item in the SSIS Toolbox, which opens the Add New Source dialog box
Merge and Merge Join Transformations: Allow you to collect data from two inputs and produce a single output of combined results. Integration Services introduce a mechanism to better manage memory pressure. This memory management mechanism operates automatically with no additional configuration of the transformation necessary.
DQS Cleansing transformation: Is a new data flow component that you use in conjunction with Data Quality Services (DQS). Its purpose is to help you improve the quality of data by using rules that are established for the applicable knowledge domain. You can create rules to test data for common misspellings in a text field or to ensure that the column length conforms to a standard specification.
Collapsible Grouping: Consolidate data flow components into groups and expand or collapse the groups. To create a group, follow these steps:
Deployment
With this deployment model type, the unit of deployment is a project, stored as an ISPAC file, which in turn is a collection of packages and parameters. You deploy the project to the Integration Services Catalog. Instead of configurations, you use parameters to assign values to package properties at run-time. Before executing a package, you must create an execution object in the catalog and optionally assign parameter values or environment references to the execution object.
This catalog is essentially a SQL application - a user database on a SQL instance (SSISDB) with a set of stored procedures and a T-SQL API.
Catalog Creation: Installation of Integration Services on a server does not automatically create the catalog. To do this, follow these steps:
1. In SQL Server Management Studio, connect to the SQL Server instance, right-click the Integration Services folder in Object Explorer, and select Create Catalog.
2. In the Create Catalog dialog box, select the Enable CLR Integration checkbox. This feature is required to manage Integration Services functionality.
3. Optionally, you can select the Scan For Automatic Execution Of Integration Services Stored Procedure At SQL Server Startup checkbox. This stored procedure performs a cleanup operation when the service restarts and adjusts the status of packages that were executing when the service stopped.
4. Notice that the catalog database name cannot be changed from SSISDB, so the final step is to provide a strong password, and then click OK. The password creates a database master key that Integration Services uses to encrypt sensitive data stored in the catalog.
Logging and Troubleshooting Tools
The built-in reports in SQL Server Management Studio for Integration Services provide information on package execution results for the past 24 hours, performance, and error messages from failed package executions. Hyperlinks in each report allow you to drill through from summary to detailed information to help you diagnose package execution problems.
Package Format Changes
The goal of these changes was to make the SSIS package format easier to read, and easier to diff when working with source control systems.
SSIS 2008
SSIS 2012
One of the biggest changes is the introduction of the project deployment model to simplify changes to package values at run-time. A side benefit of the project deployment model is the catalog which captures information about packages, validations, and execution results in tables that you can query through views or by using built-in reports. This access to information gives you greater visibility into Integration Services than was not possible in previous versions without extensive customization.
Durante una plática con amigos sobre cómo obtener un mejor performance de SQL Server, me hicieron la siguiente pregunta… ¿Existe alguna otra optimización para aplicar a un servidor de SQL Server, aparte de aplicación de Best Practice a nivel de sistema operativo y Aplicación? A lo cual les indique que también se podrían hacer optimizaciones a nivel Hardware, en este caso a nivel Storage.
Con lo anterior, empezamos a explicar el tema de SAN pero enfocándolo a Administradores de Base de Datos.
Son muchos factores los que afectan el buen rendimiento de I/O de los discos, factores como el Discos compartidos o dedicados, niveles de RAID, la velocidad del bus, configuraciones de adaptadores HBA, un punto muy importante que frecuentemente se pasa por alto es la alineación en las particiones de disco.
Algunos de los factores no-disco en los que se puede observar cuellos de botella son:
- HBA (Host Bus Adapters) o tarjetas de interface de red
- Capacidad de procesamiento de FC (Fibre Channel) o puertos iSCSI
- Numero de paths entre el servidor y el storage.
Es importante considerar y entender los límites de los componentes envueltos en la arquitectura, algunos de los límites que se tienen establecidos en el mercado son:
Pero, ¿Cómo se liga todo lo anterior con SQL Server? La unidad fundamental de almacenamiento de datos en SQL Server es la página (8KB), el espacio asignado a un archivo de datos (mdf o ndf) de una base de datos se divide lógicamente en páginas enumeradas de forma continua de 0 a n. La operación de I/O de disco se realiza a nivel página.
Los Discos duros están conformados por platos finos y circulares, en su superficie poseen medios de comunicación electrónicos que almacenan información. Cada lado de cada plato cuenta con miles de pistas o tracks, un set de tracks con el mismo diámetro en toda la superficie del plato conforman un cilindro (Para los nuevos dispositivos el concepto de cilindro no es relevante, ya que no están dispuestas en círculos concéntricos, sin embargo es útil entender el origen de los términos). Cada superficie de disco tiene dedicada una cabeza de I/O. Las pistas o tracks se dividen en sectores. Un sector es el fragmento mínimo de datos que se pueden leer o escribir en un disco duro. Las nuevas unidades pueden ofrecer sectores de 1KB, 3KB o 4 KB.
Con la tecnología RAID, la data es repartida a través de un grupo de discos físicos. El esquema de distribución de la data determina como el sistema operativo hace las operaciones de I/O de los datos. La granularidad con la cual la data es almacenada en un disco antes de que la data se almacena en otro de los discos del grupo de llama stripe unit size. La colección de stripe units, desde el primer disco al último del grupo se conoce como stripe.
Pero con todo esto que es la Alineación de las particiones? Y que efecto tiene en el performance de SQL Server??? En el siguiente diagrama se explica.. La línea verticl punteada negra que se superponen a un a la línea de color rojo corresponden a los límites entre diferentes discos físicos de un RAID. Las versiones anteriores a Windows Server 2008 nuestra los 63 sectores reservados reportados por el hardware del disco, inmediatamente después de lo cual el resto de la partición son expuestas al usuario. En la figura, el tamaño común del sector que se utiliza es de 512 bytes. El tamaño del Stripe unit en el ejemplos es de 64 KB, y 4KB para el tamaño de clúster NTFS, adecuado para, un file server. La falta de alineación de discos obliga a que el octavo clúster de 4KB de data se establezca a través de dos stripe units. Iniciando con el último sector vacío de 512 bytes del primer stripe unit y continuando con el segundo stripe unit. Esta situación se perpetua en el resto de la partición, ya que cada cierto numero el clúster de data se establecerá en dos stripe unit, por lo tanto dos I/O son requeridos para realizar una Lectura o Escritura.
El file allocation Unit size (Clúster size) recomendado para SQL Server es de 64KB; esta mejor practica en combinación con la desalineación de disco que existe por defecto fuerza que la data se establezca en dos stripe units, iniciando con el primer sector disponible del primer stripe unit y continuando con el segundo stripe unit. Esta situación es perpetuada en el resto de la partición. En esta configuración, cada clúster es escrito en dos stripe units, esto significa que todas las escrituras y lecturas se ven afectadas
El siguiente es un experimento en el cual se analizó el performance de disco, la prueba se realizó Windows Server 2003 y SQL Server 2005. Se ejecutó un query para extraer la información de SQL Server, durante cada ejecución se aplicó DBCC DROPCLEANBUFFERS para limpiar el buffer cache de SQL Server, con esto obtener pruebas satisfactorias. Los contadores de performance que se monitorearon fueron Avg. Disk Transfer/sec de los objetos PhysicalDisk y LogicalDisk los cuales son utilizados para la métrica de la latencia del disco. Los resultados muestran una mejoría significante comparando la alineación de discos, las métricas muestran una mejoría mayor al 30% entre latencia y duración.
Para la revisión de una correcta alineación de discos, es recomendable tener claro varios conceptos:
- Starting Partition Offset: Es el punto inicial en la partición del volumen que garantiza la omisión de asignación de páginas de datos en n sectores ocultos al principio de los volúmenes.
- Stripe Unit Size: Es la granularidad a la que la data se almacena en un disco del arreglo antes de que la data subsiguiente sea almacenada en otro disco del arreglo. Este valor es proporcionado por su administrador de la SAN
- File Allocation Unit Size: Es conocido también como Clúster Size, y representa la cantidad mínima de espacio de disco que puede ser suministrado para contener un archivo y se determina cuando la partición es formateada por el sistema operativo.
Existen dos reglas, que se deben cumplir para una correcta alineación de discos. Los resultados de los cálculos siguientes han de dar un valor entero.
De las dos reglas anteriores, la primera es la más importante para conseguir un rendimiento óptimo.
Ejemplos de Escenarios con desalineación en los discos
Dada una partición con Starting Partition Offset de 32.256 bytes (31,5Kb) y con un tamaño en Stripe Unit Size de 65.536 bytes (64 Kb), el resultado de Partition_Offset ÷ Stripe_Unit_Size es de 0.4921875, no es un número entero, por lo que se consideran que los discos no están alineados.
Ejemplo de escenario con alineación en los discos
Dada una partición con Starting Partition Offset de 1048576 bytes (1Kb) y con un tamaño de Stripe Unit Size de 65.536 bytes (64 Kb), el resultado de Partition_Offset ÷ Stripe_Unit_Size es exactamente 8, un numero entero exacto, lo cual se puede decir que la alineación es correcta.
Después de todo lo anterior explicado, la pregunta que hace falta contestar es… ¿Y como puedo consultar el estado actual de los discos?
Para revisar el valor del Starting Offset en discos basicos, podemos utilizar el comando WMIC (Windows Management Instrumentation Command-line) para obtener los datos del disco, la sintaxis es la siguiente:
El valor a verificar con el commando anterior es StartingOffset, en este ejemplo está alineado a 1024 kb.
También se puede obtener el resultado a través de DISKPART, seleccionando el disco a analizar y ejecutando el comando list partition, en el cual se obtendrá el Offset.
Para revisar el Starting Offset en discos básicos se deberá utilizar la utilidad dmdiag con el switch -v
Si se desea revisar el valor del File_Allocation_Unit_Size se puede ejecutar el comando
El siguiente ejemplo muestra la ejecución de todos los comandos anteriormente escritos.
Conclusión
Muchos factores contribuyen para un óptimo performance de disco. Para las particiones de disco creadas con Windows Server 2003, es adecuado validar la correcta correlación entre el Stripe Unit Size y File Allocation Unit Size como best practice. Windows Server 2008 crea particiones alineadas por default y aunque para la mayoría de los casos es adecuada, es importante siempre preguntar y seguir las mejores practicas del Vendor de discos. Cuando los servidores son actualizados de Windows Server 2003 a Windows Server 2008, las particiones preexistentes no se alinean automáticamente, es recomendable reconstruirlas para un rendimiento óptimo.
Uno de los clientes para los que labore posee una base de datos central completamente transaccional. Esta base de datos es leída por una aplicación web, la cual posee una capa intermedia de servidores de aplicación los cuales se conectan directamente a las bases de datos.
En este punto podemos diferenciar 3 niveles: web, aplicación y bases de datos. Las correctas practicas de programación nos llevarían a mantener la mayor parte del código dentro de la base de datos para de esta forma obtener un mejor performance disminuyendo la cantidad de información que viaja por la red, en este caso a través de los 3 niveles ya explicados anteriormente.
Sin embargo por una serie de antiguas practicas de programación incorrectas los desarrolladores mantienen mas del 70% de código fuente en las rutinas de .NET en los servidores de aplicación.
Esto no se convirtió en un problema real en cuanto el nivel de transacciones no era tan alto como lo ha llegado a ser, al igual como el tamaño y la complejidad de las bases de datos ha alcanzado atreves del tiempo.
Una de las políticas de la compañía es no hacer cambios en el código y en las bases de datos de Producción fuera de los “Service Packs” o cambios de versión de las aplicaciones, por lo que podrán suponer que cada “Service Pack” conlleva una gran serie de actualizaciones que son liberadas en el ambiente de Producción al mismo tiempo.
Habiendo aclarado el tipo de ambiente, practicas de programación y alguna de las políticas para los deployments podre llegar al punto que deseo exponer en este blog; una vez, un día después de la liberación de uno de los “Service Packs”, un lunes, los clientes comenzaron a contactar a servicio al cliente quejándose que nadie podía ingresar a ninguna de las aplicaciones, al aparecer la pantalla de LOGIN y darle aceptar, nada sucedía hasta obtener un time-out como respuesta.
Inmediatamente tuve que ingresar a los servidores de bases de datos y me lleve la desagradable sorpresa que el CPU de uno de ellos estaba al 100% de utilización, solo me preguntaba que cambio pudo venir con el Service Pack que estuviera ocasionando este extraño comportamiento!!
Después de un tiempo capturando traces, obteniendo información de las DMV’s entre otras herramientas llegamos a la conclusión que el nivel de compilamiento era muy superior al mostrado históricamente antes del cambio de versión, pero entre tantos cambios que vinieron con este Service Pack hubiéramos tenido que tener la aplicación abajo por demasiado tiempo hasta encontrar los statements responsables de semejante horror.
Dos cosas se hicieron para solucionar este problema, primero; por medio del análisis de los traces llegamos a la conclusión que había que crear índices en un par de tablas que los necesitaban desesperadamente y segundo; al saber que la mayoría de las ejecuciones eran tipo BATCH, ya que las llamadas del código están en los servidores de aplicación cambiamos el tipo de PARAMETERIZATION de simple a forced.
Comando:
ALTER DATABASE <DB_NAME> SET PARAMETERIZATION FORCED
Que es lo que esta opción de base de datos realiza?
Parametriza todos los valores que vienen con los selects, updates, deletes e inserts que sean tipo batch, individualmente, para que estos no sean recompilados cada vez que son ejecutados. O sea los mantiene a nivel de memoria.
Lógicamente esta opción no aplica para todos los statements que estén dentro de los procedimientos almacenados ya que estos son compilados efectivamente por el motor de base de datos.
También hay otras situaciones donde la parametrizacion no aplica, pueden acceder a estas ingresando al siguiente link.
http://technet.microsoft.com/en-us/library/ms175037.aspx
Al aplicar estos cambios el grado de recompilamiento bajo significativamente y junto a los índices creados el CPU volvió a niveles normales de entre 20% y 30%, y todos los usuarios pudieron felizmente ingresar de nuevo a las aplicaciones.
Antes de finalizar este tema sugiero siempre recomendar a los desarrolladores mantener todo el código posible siempre dentro del motor de base de datos y cuando nos topamos con ambientes como el expuesto aquí recomiendo hacer el cambio de la parametrizacion a “FORCED” antes de que ocurran los desastres.
One of the clients that I worked for has a fully transactional core database. This database is accessed by a web application, which has an intermediate layer of application servers which connect directly to databases.
Here we can distinguish 3 different levels: web, application and database. The right programming practices lead us to keep most of the code within the database in order to obtain a better performance by decreasing the amount of information that goes over the network, in this case through the 3 levels explained before.
However a big number of old wrong programming practices maintain over 70% of source code routines within the application servers.
This did not become a real problem until the transaction level was increasing over time, as well as size and complexity of the database had reached.
One of the company policies is not to make code changes to databases production outside the "service packs" or application version upgrades, so you can assume that each "Service Pack" carries a large number of changes that are released into the Production environment at the same time.
Having clarified the environment, programming practices and deployments policy I can expose the case I had to face to at that time in this blog. Once, a day after a "Service Packs" release, Monday, customers began to contact customer service complaining that no one could enter to any of the applications, after the LOGIN screen appears, nothing happened until a time-out pop up in response.
Immediately I had to go through the database servers and I got the unpleasant surprise that in one server the CPU was 100% of usage; just wondering what change might come with the service pack that was causing this strange behavior!
After a while, some SQL traces were captured, and obtaining information from the DMV's and other tools, we conclude that the compiling level was much higher than historically shown before the version upgrade, but among so many changes that were pushed with the service pack we would have had the application down for too long in order to find the statement(s) responsible for such horror.
Two things were done in order to solve this issues, first, by analyzing the traces we conclude that we had to two indexes on a couple of tables that were desperately needed them, and second, by knowing that most of the executions were BATCH type, we came out with the possibility of changing the PARAMETERIZATION database option from SIMPLE to FORCED.
Command:
ALTER DATABASE <db_name> SET PARAMETERIZATION FORCED
What does this option do to a database?
Parameterizes all the values which come with selects, updates, deletes and inserts that are BATCH type, individually, this way they won’t need to be recompiled each time they are executed. The execution plan is kept at memory level.
Obviously, this option does not apply to all statements that are within stored procedures as these are compiled by the database engine instead.
There are other situations where the parameterization is not applicable, you can see all the cases by entering the following link.
By implementing these changes, the degree of recompiling decreased significantly and the CPU returned to normal levels between 20% and 30% of usage; this way all users could happily accessed the applications.
Conclusion
Before concluding this post I want to suggest recommending to developers to keep most of the code within the database engine as much as possible and if you came across with environments like the exposed here, I recommend changing the parameterization database option to "FOCED" before the disasters occurred.
Un cordial saludo comunidad Technet.
Hoy tengo el privilegio de comenzar a publicar ( y retribuir un poco tanto conocimiento que he podido consultar tanto de Technet como MSDN) en este medio, y aprovecho el reciente lanzamiento de SQL 2012 ( http://www.microsoft.com/es-es/sqlserver/default.aspx) para hacer una breve y precisa referencia a la documentación que nos permitirá explorar algunas de sus nuevas características de BI desde SharePoint 2010
Particularmente en Venezuela, la semana pasada se reunieron en el Hotel Renaissance de Caracas, socios de negocio y clientes para conocer de primera mano la propuesta de valor que MIcrosoft ofrece para gestionar la información de organizaciones tanto con fines de lucro como de desarrollo social, con necesidades de análisis y generación de repotes de forma rápida, simple ("Power View"), sobre altos volúmenes de datos ("Parallel Datawarehouse"), en cualquier ubicación (On Premise, Nube o mixto) y con alto porcentaje de disponibilidad ("Always On")
SQL 2012 está aquí para fortalecer con nuevas características su compromiso con la misión crítica de la információn transaccional, espacial y multidimensional.
Desde el punto de vista de colaboración e Insights, Este compromiso se traduce en la capacidad para:
- Soportar las bases de datos SharePoint 2010 con Service Pack 1 (SP1).
- La edición y publicación en sitios SharePoint, de reportes en cualquier formato Office, utilizando "Power View", una nueva característica de complemento de SQL Server Reporting Services para SharePoint.
- Fortalecer la alta disponibilidad para las bases de datos SharePoint 2010 (con SP1), mediante "Always On"
Si bien hasta el momento no se menciona SQL 2012 en la documentación de requerimientos de software para SharePoint 2010, tenemos disponible la guía para utilizar las características de BI de SQL 2012 en una granja SharePoint 2010: http://technet.microsoft.com/en-us/library/hh231680(v=SQL.110).aspx Esta guía describe la posibilidad de desplegar una granja SharePoint sobre SQL 2012, previamente actualizada con el Service Pack 1.
Espero que esta referencia sea una razón más para promover la actualización de su granja SharePoint 2010 (sí aún no lo ha hecho) y así poder comenzar a familiarizarse con las nuevas caracterísitcas de BI en SQL 2012.
En los últimos 6 meses me encontré con 2 casos de linked servers entre una instancia de SQL Server 2008 R2 64 bits en un Cluster de Windows 2008 R2 y una instancia standalone de SQL Server 2000 32 bits en los cuáles los cuáles las transacciones distribuidas no estaban funcionando.
La causa raíz del problema sigue en investigación, sin embargo, tratando de entender el problema verifiqué que todo estuviera bien configurado y realicé algunas pruebas.
Revisé lo siguiente:
- Que la resolución de nombres funcionara bien
- Que el DTC estuviera bien configurado en cuanto a la sección de seguridad
- Se probó el linked server sin transacción distribuida y funcionaba
- El DTCPing dio resultado correcto
- Hasta donde recuerdo el DTCTester también dio resultado correcto.
Aún cuando todos los puntos anteriores fueron exitosos, las transacciones distribuidas seguían fallando. En las pruebas que hice, probé creando un DTC Clusterizado en el grupo de SQL Server 2008 y siguió fallando.
Después, sin muchas esperanzas, probé borrando todos los DTC Clusterizados y configurando los DTC locales y, para mi sorpresa, funcionó.
En éste punto la pregunta se convirtió en, ¿Que desventajas tengo en utilizar los local DTC’s en lugar de los DTC’s clusterizados?, así que tuve que investigar y probar éste punto.
Antes que nada, ¿Cuál es la razón de tener DTC’s clusterizados?, antes de Windows Server 2008, la razón era que en Windows Cluster la única forma de utilizar el MSDTC era clusterizándolo, sin embargo en Windows Server 2008 el número de opciones aumentó. Ahora es posible tener más de un DTC clusterizado y también es posible utilizar el DTC no clusterizado de cada nodo. Entonces, ¿Sigue siendo necesario clusterizar el DTC?, ¿Cuáles son los beneficios de clusterizarlo y cuáles son las limitantes de solo utilizar el local DTC?
La respuesta corta (basado en mi conocimiento y pruebas) es que hay algunos escenarios por los que el ambiente clusterizado tiene beneficios, pero en muchos casos la diferencia es muy pequeña y puedes usar el local DTC en lugar del DTC clusterizado con muy poco riesgo.
¿Cuándo es preferible usar el DTC Clusterizado en lugar del local?, Un escenario es cuando tienes múltiples instancias de SQL Server en cada nodo. En ese caso con local DTC todas las instancias usarán el único DTC disponible en la instancia, si quieres mayor escalabilidad y disponibilidad entonces es recomendable configurar múltiples DTC’s clusterizados, uno para cada instancia.
Otro escenario sería cuando el DTC local falla, en ese caso, las instancias no van a hacer failover automático, en cambio, si estuviéramos utilizando un DTC Clusterizado, el failover del DTC es automático y solo las transacciones distribuidas activas hacen rollback, las nuevas transacciones distribuidas corren sin problema.
En resumen, es recomendable tener los DTC clusterizados, sin embargo, si estás teniendo problemas prueba con los DTC locales para ver si eso soluciona tu problema.
Hi Technet community.
Today I have the privilege to start write in this blog (and a little reward the knowledge I've gained in Technet and MSDN). A few weeks ago it was the launch of SQL 2012 (http://www.microsoft.com/es-es/sqlserver/default.aspx) and I would like to make a brief reference to the current documentation that will allow us to explore some of its new BI features from SharePoint 2010 perspective.
A few weeks ago in Caracas-Venezuela, business partners and customers met at the Renaissance Hotel, to see first hand the value proposition offered by MIcrosoft to help companies and NGOs in the information management: analysis, reporting fast and simple ("Power View"), over huge data ("Parallel Datawarehouse"), in any location (On Premise, cloud or mix) with high availability ("Always On"). SQL 2012 is here with new features in order to strengthen their commitment with the transactional, spatial, multidimensional and critical information.
From the point of view of collaboration and Insights, this commitment translates into the ability to: - Support SharePoint 2010 with Service Pack 1 (SP1) databases.- Editing and publishing in SharePoint sites, reports in any format Office, using "Power View", a new feature of SQL Server Reporting Services for SharePoint.- Strengthen the high availability databases, SharePoint 2010 (with SP1), by "Always On"
At this moment, SQL 2012 is not mentioned in software requirements documentation for SharePoint 2010, However, We have the following Guide for use SQL 2012 BI features in a SharePoint 2010 farm: http://technet.microsoft.com/en-us/library/hh231680(v=SQL.110).aspx This guide describes the possibility of deploying a farm SharePoint on SQL 2012, previously updated with Service Pack 1.
I hope this reference help you to promote the updating of your SharePoint 2010 farm and start to familiarize with the new features of BI in SQL 2012.
Una vez más trayendo para ustedes algo que pueda ser de utilidad.
Desde que Microsoft liberó la nueva y más reciente versión de su sistema operativo para dispositivos móviles, todos deseamos que el hardware nos permitiera hacer lo que se hace con la competencia (iPhone) relacionado a la personalización de nuestro teléfono y contactos sobre todo. Cuando intentábamos usar un archivo wma como timbre simplemente no era posible.
Pero esto se acabo, ahora podemos usar archivos no protegidos como MP3 o WMA como timbres personalizados y poder usarlos en la configuración de nuestro teléfono, solo debemos cumplir ciertas condiciones y seguir los siguientes pasos:
Requisitos
Procedimiento
Y listo a disfrutar, si tienes dudas o deseas información más detallada y oficial sobre este tema consulta: http://www.microsoft.com/windowsphone/en-us/howto/wp7/start/create-ringtones.aspx