23
 Arquiteturas usando Pipes and Filters Por  Sergio Crespo Email: [email protected] http://www.inf.unisinos.br/~crespo © Prof. Dr. Sergio Crespo C S Pinto – 2010/02

Arquiteturas usando Pipes and Filters

Embed Size (px)

Citation preview

Page 1: Arquiteturas usando Pipes and Filters

   

Arquiteturas usando Pipes and Filters

Por  Sergio CrespoEmail: [email protected]

http://www.inf.unisinos.br/~crespo

© Prof. Dr. Sergio Crespo C S Pinto – 2010/02

Page 2: Arquiteturas usando Pipes and Filters

   

Introdução

O Padrão arquitetural Pipes and Filters oferece uma estrutura para processamento de stream de dados.

Cada passo do processamento é encapsulado em um componente filtro. Os dados são transportados por meio de tubos (pipes) que estão entre filtros.

Page 3: Arquiteturas usando Pipes and Filters

   

Pipes and Filters

Contexto: Processamento de Stream de dadosProblema: Imagine que você está construindo um sistema 

de software que deve processar ou transformar uma stream de dados de entrada. 

Implementar isto como um único componentes pode não ser flexível.

O projeto do sistema, em especial, a interconexão entre as fases de cada estágio do processamento, deve considerar alguns pontos:

• Futuras atualizações do sistema devem ser possíveis substituindo­se ou recombinando­se fases.

• Processamento em pequena escala deve ser prioritário, pois é mais fácil de manter e reutilizar.

• Processamento não adjacente não deve compartilhar informação.• Deve ser possível armazenar a informação em vários formatos.

Page 4: Arquiteturas usando Pipes and Filters

   

Pipes and Filters

Estrutura:Filter: Componentes Filter (filtro) são unidades de 

processamento de um pipeline. Um filtro enriquece, redefine, sincroniza ou transforma os dados de entrada.

Pipes: São as conexões entre os filtros, entre o data source (a origem dos dados) e o 1º filtro e entre o último filtro e o data sink.

Data source: representa a entrada dos dados.Data sink: Coleta o resultado do fim de um 

pipeline.

Page 5: Arquiteturas usando Pipes and Filters

   

Cards: Pipes and FiltersClassFilter

ClassPipe

ClassData Source

ClassData Sink

ResponsabilidadeRecebe os dados de entrada.Executa uma função sob os dados de entrada.Abastece a saída de dados.

ResponsabilidadeTransferência dos dados.Buffers data.Sincronização com visinhos.

ResponsabilidadeEntrega o stream de input para o processamento no pipeline.

ResponsabilidadeConsome o Output.

ColaboradoresPipe

ColaboradoresPipe

ColaboradoresData SourceData SinkFilter

ColaboradoresPipe

Page 6: Arquiteturas usando Pipes and Filters

   

Pipes and Filters – exemplo 1

Page 7: Arquiteturas usando Pipes and Filters

   

Pipes and Filters – exemplo 2

Contexto:Você deve prover uma solução de integração para várias 

aplicações financeiras. A aplicação utiliza uma grande variedades de formatos tais como Interactive Financial Exchange (IFX), Open Financial Exchange formato (OCX) e o formato Electronic Data Interchange (EDI) para as mensagens que correspondem a pagamentos, retiradas, depósitos e transferências.

Page 8: Arquiteturas usando Pipes and Filters

   

Pipes and Filters – exemplo 2

Integrar estas aplicações requer o processamento de mensagens de diferentes maneiras. 

Por exemplo, converter uma mensagem XML­like para outra XML­like usando transformações XSLT.

Converter uma mensagem padrão EDI para um formato XML­like envolve o uso de regras e processamento.

Verificar a identidade do emissor envolve verificar a sua assinatura digital que veio anexada na mensagem. 

Page 9: Arquiteturas usando Pipes and Filters

   

Pipes and Filters – exemplo 2

Contexto: Você deve prover uma solução de  integração para várias aplicações financeiras. A aplicação utiliza 

uma grande variedades de formatos tais como  Interactive Financial Exchange  (IFX), Open Financial Exchange  formato  (OCX)  e  o  formato  Electronic  Data  Interchange  (EDI)  para  as  mensagens  que correspondem a pagamentos, retiradas, depósitos e transferências.

Problema: Como implementar uma sequência de 

transformações de tal forma que você possa combinar e reusar elas de forma independe?

Page 10: Arquiteturas usando Pipes and Filters

   

Pipes and Filters – exemplo 2

Implementar transformações que possam ser combinadas e reusadas em diferentes aplicações envolve o balanceamento das seguintes forças:

Muitas aplicações processam grandes volumes de dados em formato similares.

O processamento dos dados pode ser dividido em uma sequencia de transformações individuais. Por exemplo, processar mensagens XML envolve tipicamente uma série de transformações XSLT. Isto ajuda a diminuir o overhead e a latência de uma transformação.

Page 11: Arquiteturas usando Pipes and Filters

   

Pipes and Filters – exemplo 2 solução

Solução:

Implemente as transformações usando uma sequência de componentes filters, onde cada filtro recebe uma mensagem de entrada, aplica uma simples transformação e envia a mensagem modificada para o próximo componente. A mensagem é conduzida através de um pipe que conecta filtros de output / input e mecanismos de buferização entre eles.

Page 12: Arquiteturas usando Pipes and Filters

   

Pipes and Filters – exemplo 2 soluçãoO lado esquerdo apresenta uma configuração com 2 

filtros.  Uma  aplicação  de  origem  envia  mensagens 

através de um pipe.  O  filtro  transforma  cada  mensagem  e  envia  a 

mensagem  transformada  como  output  dentro  do próximo pipe.

O pipe carrega a mensagem transformada para o filtro  2.  O  pipe  também  buferiza  qualquer mensagem que filtro 1 envia a filtro 2.

O  segundo  filtro  aplica  novas  transformações  e envia  por  meio  de  um  pipe  para  uma  aplicação Sink.

A  aplicação  Sink  coleta  a  mensagem transformada.

Esta configuração requer: (1)  que  a  saída  dos  dados  deve  ser  compatível 

com o input do filtro 1. (2)  a  saída  dos  dados  do  filtro  1  deve  ser 

compatível com o input do filtro 2. (3)  a  saída  dos  dados  do  filtro  2  deve  ser 

compatível com o input do Sink.

Page 13: Arquiteturas usando Pipes and Filters

   

Pipes and Filters – exemplo 3 Consider  a  Web  service  for  printing  insurance  policies.  The  service  accepts  XML 

messages from agency management systems. Incoming messages are based on the ACORD  XML  specification,  an  insurance  industry  standard.  However,  each  agency has  added  proprietary  extensions  to  the  standard  ACORD  transactions.  A  print request  message  specifies  the  type  of  document  to  be  generated,  for  example,  an HTML document or a Portable Document Format (PDF) document. The request also includes  policy  data  such  as  client  information,  coverage,  and  endorsements.  The Web service processes  the proprietary extensions and adds  the  jurisdiction­specific information  that  should appear on  the printed documents,  such as  local or  regional requirements and restrictions. The Web service then generates the documents in the requested format and returns them to the agency management system. 

You  could  implement  these  processing  steps  as  a  single  transformation  within  the Web service. Although viable, this solution does not let you reuse the transformation in a different context. In addition, to accommodate new requirements, you would have to change several components of the Web service. For example, you would have to change several components if a new requirement calls for decrypting some elements of  the  incoming  messages.  An  implementation  that  is  based  on Pipes  and Filters provides an elegant alternative for the printing Web service. 

Page 14: Arquiteturas usando Pipes and Filters

   

Pipes and Filters – exemplo 3 solução

In this example, the Pipes and Filters implementation of the printing Web service has the following benefits that make it preferable to implementing the Web service as a single monolithic transformation:

Separation of concerns. Each filter solves a different problem.

Division of labor. ACORD XML experts implement the conversion of the proprietary extensions into an internal vendor­independent format. People who specialize in dealing with the intricacies of each jurisdiction assist with the implementation of the filter that handles those aspects. Formatters and layout experts implement document generation.

Specialization. Document­rendering is CPU intensive and, in the case of a PDF document, uses floating point operations. You can deploy the rendering to hardware that meets these requirements.

Reuse. Each filter encapsulates fewer context­specific assumptions. For example, the document generator takes messages that conform to some schema and generates an HTML or PDF document. Other applications can reuse this filter.

Page 15: Arquiteturas usando Pipes and Filters

   

BizTalk Pipeline Designer

The allows developers to connect and to configure these filters within the pipeline. The Figure shows a pipeline that consists of Pre­Assemble, Assemble, and Encode filters. The toolbox shows the filters than can be dropped into this configuration. 

Page 16: Arquiteturas usando Pipes and Filters

   

Pipes and Filters : Related Patterns

For more information about Pipes and Filters, see the following related patterns:

Implementing Pipes and Filters with BizTalk Server 2004. This pattern uses the Global Bank scenario to show how you can use BizTalk Server 2004 to implement Pipes and Filters.

Pipes and Filters [Shaw96, Buschmann96, Hohpe03].

Intercepting Filter [Trowbridge03]. This version of Intercepting Filter discusses the pattern in the context of Web applications built using the Microsoft .NET Framework. Developers can chain filters to implement preprocessing and post­processing tasks such as extracting header information and rewriting URLs.

In­band and Out­of­band Partitions [Manolescu97]. This pattern remedies the lack of a component that has a global context in Pipes and Filters systems. The out­of­band partition is context­aware; therefore, it can configure the filters and handle errors.

http://msdn.microsoft.com/en­us/library/ms978599.aspx 

Page 17: Arquiteturas usando Pipes and Filters

   

(1) Pipes and Filters : Intercepting Filter

Context Anyone who has built a Web application from scratch realizes that it requires bit more 

housekeeping work than building an internal clientserver application. First, you have to deal with the HTTP and all its quirks such as HTTP headers, multi­part forms, the statelessness of HTTP, character set encoding schemes, Multipurpose Internet Mail Extensions  (MIME)  types, and URL  rewriting. On  top of  that,  you have  to deal with security measures such as Secure Sockets Layer (SSL) and user authentication.  In many  situations,  the  list  continues  on  to  include  such  items  as  client  browser detection or user activity  logging. Web application server  frameworks perform many of  these  tasks  for  you,  but  sometimes  you  need  additional  control,  or  you  need  to insert your own processing steps before or after the application processes the Web page request.

Problem How do you implement common pre­ and post­processing steps around Web page 

requests?

Related Patterns Decorator [Gamma95].  Intercepting  filters  can  be  considered  decorators  around  a 

front controller. 

http://msdn.microsoft.com/en­us/library/ms978727.aspx 

Page 18: Arquiteturas usando Pipes and Filters

   

(2) Pipes and Filters : Front Controller Context You have decided to use the Model­View­Controller(MVC) pattern to 

separate  the  user  interface  logic  from  the  business  logic  of  your dynamic  Web  application.  You  have  reviewed  the Page Controller pattern,  but  your  page  controller  classes  have complicated logic, are part of a deep inheritance hierarchy, or your application  determines  the  navigation  between  pages  dynamically based on configurable rules.

Problem How do you best structure the controller for very complex Web 

applications  so  that  you  can  achieve  reuse  and  flexibility  while avoiding code duplication?

http://msdn.microsoft.com/en­us/library/ms978723.aspx 

Page 19: Arquiteturas usando Pipes and Filters

   

(3) A Data Flow Pattern Language

A Data Flow Pattern LanguageDragos­Anton Manolescuy

Pattern: Data flow architecturePattern: PayloadsPattern: Module data protocolPattern: Out­of­band and in­band partitions

http://citeseer.ist.psu.edu/cache/papers/cs/3493/http:zSzzSzst­www.cs.uiuc.eduzSz~hanmerzSzPLoP­97zSzProceedingszSzmanolescu.pdf/a­data­flow­pattern.pdf 

Page 20: Arquiteturas usando Pipes and Filters

   

(4) DataLaViSTA : A Packet­based Pipes and Filters Architecture for Data Handling in Virtual Environments

Ingo Assenmacher, Bernd Hentschel, Marc Wolter, Torsten KuhlenVirtual Reality Group

RWTH Aachen University52062 Aachen

Tel.: +49 (0)241 80 29210Fax: +49 (0)241 80 629210

E­Mail: {assenmacher,hentschel,wolter,kuhlen}@rz.rwth­aachen.de

Abstract: Modern Virtual Reality applications are  integrated  in distributed environments and use concurrent programming models to enable virtual environments for real time interaction. A suitable model  for many sub problems can be  found  in  the pipes and filters  architecture,  where  data  is  processed  in  a  stream­like  way  using  filters  to transform or aggregate data. This paper describes a terminology that can be used to decompose  a  problem  domain  according  to  such  an  architecture  and  presents DataLaViSTA as an implementation of this model. As results, two issues common to Virtual Reality setups, namely the data synchronization in a PC cluster setup and the coupling  of  external  systems  to  this  configuration  are  implemented  using  the DataLaViSTA module.

http://www.rz.rwth­aachen.de/global/show_document.asp?id=aaaaaaaaaaberru 

Page 21: Arquiteturas usando Pipes and Filters

   

(5) Composite Filter Pattern

Sherif M. YacoubHewlett­Packard Labs

1501 Page Mill Rd., MS 1126Palo Alto, CA 94304

[email protected]

ContextYou are designing a system that processes digital media, streams of data, or digital 

content.ProblemA  part  of  the  overall  structure  of  a  digital  media  processing  system  is  a  filtering 

subsystem that transforms/manipulates streams of digital media. The functionality of that  subsystem  is  achieved  by  integrating  several  processing  modules  (filters) together. The way you integrate and connect these filters together controls the format of output (processed) digital media. There are several ways of combining these filters. A flexible design structure is required for modeling the complex combination of these filters,  which  could  be  hierarchical  in  nature.  The  problem  is  how  do  you  design your  filtering  subsystem  to  support  the  complex  hierarchical  combination  of filters?

http://hillside.net/europlop/HillsideEurope/Papers/EuroPLoP2001/2001_Yacoub_CompositeFilterPattern.pdf 

Page 22: Arquiteturas usando Pipes and Filters

   

(6) Software Architecture for Computer Vision:Beyond Pipes and Filters

Alexandre R.J. Fran»coisInstitute for Robotics and Intelligent Systems

University of Southern [email protected]

July 2003

This document highlights and addresses architecture level software development issues facing  researchers  and  practitioners  in  the  field  of  Computer  Vision.  A  new framework, or architectural style, called SAI, is introduced. It provides a formalism for the  design,  implementation  and  analysis  of  software  systems  that  perform distributed parallel processing of generic data streams. Architectural patterns are illustrated  with  a  number  of  demonstration  projects  ranging  from  single  stream automatic real­time video processing to fully integrated distributed interactive systems mixing  live  video,  graphics  and  sound.  SAI  is  supported  by  an  open  source architectural middleware called MFSM.

http://pollux.usc.edu/~afrancoi/pdf/sacv­tr.pdf 

Page 23: Arquiteturas usando Pipes and Filters

   

Pipes and Filters

Para a próxima aula:Em  grupo  de  2  alunos,  fazer  uma  apresentação  sobre 

um dos padrões listados:(1) Blackboard(2) Broker(3) Microkernel(4) Presentation­abstraction­control(5) Scripted components