Sistemi Distribuiti Corso di Laurea in Ingegneria
Transcript
Sistemi Distribuiti Corso di Laurea in Ingegneria
Dipartimento di Sistemi e Informatica, University of Florence Distributed Applications Sistemi Distribuiti Corso di Laurea in Ingegneria O Intranet model ♣ ♣ Dr. Davide Rogai, Prof. Paolo Nesi PARTE 11e: .net Remoting O Internet model ♣ ♣ ♣ Department of Systems and Informatics University of Florence Via S. Marta 3, 50139, Firenze, Italy tel: +39-055-4796523, fax: +39-055-4796363 .NET Remoting .NET to .NET Web services HTTP to HTTP Ad hoc services for .NET clients Lab: DISIT, Sistemi Distribuiti e Tecnologie Internet [email protected], [email protected] [email protected] www: http://www.dsi.unifi.it/~nesi Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 1 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 .NET Remoting O CLR Host Set Set of services that enable enable applications to communicate O ♣ Applications can reside on the same computer ♣ On different computers in the same LAN ♣ Across the world in "very" different networks and running on heterogeneous platforms O Enable communication between objects in different AppDomains or processes In order to run managed code, the CLR Host must obtain a pointer to an entity called appapp-domain ♣ Normally, Normally, it is the default domain within the process ♣ Can create extra domains in the process ♣ Different transportation protocols ♣ Different serialization formats ♣ Object lifetime schemes ♣ Modes of object creation Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 The CLR provides an execution environment for code with services like garbage collection, collection, security, security, languagelanguage-neutrality... neutrality... Today, Today, .NET executables require a piece of code to start the CLR up and running ♣ exe stub, stub, ASP.NET ISAPI, IE 5.01+, Yukon O O 2 3 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 4 Sistemi Distribuiti, Paolo Nesi 1 Dipartimento di Sistemi e Informatica, University of Florence AppDomains O O O Isolation Managed code runs in an application domain AppDomains are separate units of processing that the CLR recognizes in a running process AppDomains are separated from one another Managed code must get through a verification process before it can be run ♣ Code that passed passed the test is said to be typetype-safe The certainty to run typetype-safe code allows the CLR to provide a level of isolation as strong as the process boundary, but more costcost-effective The CLR enforces isolation by preventing direct calls between objects in different AppD ppDomains .NET Remoting refers to the set of system services to access objects between domains O O ♣ Similar to process boundaries but more lightweight O dotnet.exe Creates a CLR host and inject code in the default domain Unmanaged Stub O CLR Host Isolation Managed Code Default AppDomain Others domains 5 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Remoting and AppDomains .NET Executable .NET Executable Stub Stub Instantiates the CLR host and inject code in the default AppDomain Instantiates the CLR host and inject code in the default AppDomain Marshaling O Marshal by value ♣ ♣ O Default AppDomain Other AppDomains Object is instantiated on the client and filled with data coming from the server State of the object downloaded Marshal by reference ♣ ♣ Process primary thread 6 The object lives on the server and any calls take place remotely Input parameters and return value travel over the network Process primary thread Remoting (local or remote machine) Default AppDomain Remoting Other AppDomains Remoting Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 7 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 8 Sistemi Distribuiti, Paolo Nesi 2 Dipartimento di Sistemi e Informatica, University of Florence MarshalByRef Server Client Remote Components O Object O O Stub Proxy Stub Proxy O Class derived from MarshalByRef Public methods Work with serializable classes Application Host ♣ ♣ ♣ Object, method, and params Return values IIS, NT service, service, custom app Requires manual activation Publish your components AppDomain AppDomain AppDomain AppDomain Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 9 Client Applications O O ♣ O .NET Remoting Need a reference to the server component Mark the remote type as "wellwell-known" known" ♣ ♣ Application Domain A Tell the runrun-time the type lives remotely JIT compiler adds code onon-thethe-fly to transform local calls into remote calls Everything happens transparently Application Domain B Client Servant Transparent Proxy Real Proxy Instantiated through operator new (if (if client activated) activated) Object Context Sinks Server Context Sinks Envoy Sinks Channels Formatters Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 10 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 11 Channels Network Formatters Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 12 Sistemi Distribuiti, Paolo Nesi 3 Dipartimento di Sistemi e Informatica, University of Florence .NET Remoting O Motivation .NET Remoting provides pluggable transports and formatters O ♣ currently TCP and HTTP transport and ♣ binary and SOAP formatters O Contexts are automatically propagated O Only very simple lifecycle management options for servants (compared to EJB or CORBA) Application domain is a hard boundary ♣ Acts much like a unmanaged process ♣ Also includes process/machine boundaries ♣ No direct access to objects across boundary O Remoting services required to access an object across a hard boundary ♣ Singleton (one (one object for all calls) calls) ♣ SingleCall (new instance on the server for each call) call) ♣ ClientClient-Activated based on leases Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 13 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 NonNon-remotable objects O Remotable objects CLR objects cannot, by default, be used outside their AppDomain O ♣ No way to copy them ♣ No way to reference them O 14 Can request that instances of a class be accessible outside original AppDomain ♣ Should a client get a copy of the object? ♣ Should a client get a reference (proxy) to the original object Exception occurs when you try to pass an object reference to a different domain Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 15 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 16 Sistemi Distribuiti, Paolo Nesi 4 Dipartimento di Sistemi e Informatica, University of Florence Serializable objects O MarshalByRef objects When runtime can make a copy of the object, an object can marshalmarshal-byby-value to other AppDomains O ♣ Add SerializableAttribute ♣ Or implement the ISerializable interface [Serializable] class Foo : System.MarshalByRefObject { . . . } [Serializable] Class Foo { . . . } O Clients in foreign AppDomains receive clone O O Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 17 Clients in foreign AppDomains receive proxy How does a client specify what proxy? 18 Writing a server Clients must connect to servers O ♣ Server needs to publish an object I listen on this TCP channel and that HTTP channel I have a service called "MathService" When client connects to MathService using a supported channel, give the client [ a | this ] Calculator instance ♣ Clients need to specify the desired object Connect to the "MathService" on server "LightningFast" using protocol HTTP on port 80 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 // MBRO overrides // Serializable Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Remoting in general O When the object's class derives, directly or indirectly, from MarshalByRefObject, MarshalByRefObject, the runtime creates a proxy to the object O Assumption: You have an assembly containing MarshalByRefObject types you wish to make available for use via remoting A server then becomes simply a host app ♣ Loads the managed types ♣ Configures remoting to expose the types O O 19 Can write your own host Can use IIS as an already available HTTP host Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 20 Sistemi Distribuiti, Paolo Nesi 5 Dipartimento di Sistemi e Informatica, University of Florence Channels Server design and implementation O O Design considerations O O Implementation ♣ ♣ ♣ Runtime provides builtbuilt-in channel types ♣ HTTP and TCP channels ♣ You can write custom channels Select/write appropriate host Configure remoting system activation mode Register channels Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 A channel transports messages to and from a remote object ♣ A server selects the channels upon which it listens for requests ♣ A client selects the channels it wishes to use to communicate with the server ♣ Decide which channels/ports to support ♣ Select an activation model ♣ Decide how clients get type metadata 21 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 22 Activation requests ChannelServices.RegisterChannel O using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Http; using System.Runtime.Remoting.Channels.Tcp; . . . ChannelServices.RegisterChannel (new HttpChannel()); ChannelServices.RegisterChannel (new TcpChannel(4242)); O Server also chooses how it wants to process activations requests for a type Two forms of server activation ♣ WellKnownObjectMode.SingleCall ♣ WellKnownObjectMode.Singleton O One form of client activation ♣ Client activated object (CAO) Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 23 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 24 Sistemi Distribuiti, Paolo Nesi 6 Dipartimento di Sistemi e Informatica, University of Florence SingleCall objects O Singleton objects Server's remoting layer creates one SingleCall object per method call O ♣ Sole object handles method calls from all clients Lifetime equals server lifetime ♣ Each object services one and only one request Created onon-demand as method calls arrive Lifetime limited to method call O O O Useful in stateful applications O Best choice where overhead of creating and maintaining objects is substantial ♣ Can only store clientclient-independent state Useful in stateless applications Best choice for loadload-balanced applications Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 25 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 WellWell-known objects O 26 WellWell-known objects Server activated types are "well"well-known" O ♣ Server tells remoting Here's a type Here's how and when to instantiate the type Here's the name (end point) a client will use to contact the type ♣ Clients tell remoting Connect to this server machine Get the (known) type at this end point (name) Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Server's remoting layer creates one Singleton object Server registers a wellwell-known type using RegisterWellKnownServiceType specifying ♣ The type being registered ♣ The end point name known to clients ♣ The activation model 27 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 28 Sistemi Distribuiti, Paolo Nesi 7 Dipartimento di Sistemi e Informatica, University of Florence Server activation example RegisterWellKnownServiceType using using using using using System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Http; System.Runtime.Remoting.Channels.Tcp; class RemotingHost { static void Main(string[] args) { RemotingConfiguration.ApplicationName = "WiseOwlMathService"; WellKnownServiceTypeEntry WKSTE = new WellKnownServiceTypeEntry(typeof(WiseOwl.Calculator), "SharedCalc", WellKnownObjectMode.Singleton); using System.Runtime.Remoting; . . . WellKnownServiceTypeEntry WKSTE = new WellKnownServiceTypeEntry(typeof(WiseOwl.Calculator), "EphemeralCalc", WellKnownObjectMode.SingleCall); RemotingConfiguration.RegisterWellKnownServiceType(WKSTE); RemotingConfiguration.RegisterWellKnownServiceType(WKSTE); ChannelServices.RegisterChannel(new HttpChannel(9000)); ChannelServices.RegisterChannel(new TcpChannel(4242)); Console.ReadLine(); } } Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 29 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 WellWell-known object URLs O Remoting config file ServerServer-activated objects are published at a URL O ♣ The URL is "well"well-known" to the client Such types are called wellwell-known types The URL is called the wellwell-known object URL All hardhard-coded remoting information in prior example can reside in external config file ♣ Default filename is executable plus ".config" ♣ E.g. RuntimeHost.exe is RuntimeHost.exe.config ProtocolScheme://ComputerName:Port/PossibleApplicationName/ObjectUri O 30 O Host must tell remoting to use the config file O Server code simplifies… simplifies… ♣ RemotingConfiguration.Configure (file) When IIS is the server's host: ♣ PossibleApplicationName becomes virtual dir name ♣ ObjectUri should end in ".rem" or ".soap" O A TcpChannel requires the port number Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 31 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 32 Sistemi Distribuiti, Paolo Nesi 8 Dipartimento di Sistemi e Informatica, University of Florence Server remoting config file Revised Server Example <configuration> <system.runtime.remoting> <application name="WiseOwlMathService"> <service> <wellknown mode="SingleCall" type="WiseOwl.Calculator,MathObjects" objectUri = "EphemeralCalc" /> <wellknown mode="Singleton" type="WiseOwl.Calculator,MathObjects" objectUri = "SharedCalc" /> </service> <channels> <channel port="9000" ref="http" /> <channel port="4242" ref="tcp" /> </channels> </application> </system.runtime.remoting> </configuration> Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 using System; using System.Reflection; using System.Runtime.Remoting; class RemotingHost { static void Main(string[] args) { String s = Assembly.GetExecutingAssembly().Location; RemotingConfiguration.Configure (s + ".config"); Console.ReadLine(); } } 33 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Client activated objects Lease based lifetime O O O O Client activated object's lifetime controlled by a lease on the object ♣ Leases have a lease time ♣ Remoting infrastructure drops reference to object when lease expires Server activated is one activation model Client activated is quite different Each client activation creates one object O Each method call renews the lease O Clients can renew the lease using the proxy Sponsors can renew the lease ♣ Use default renew on call time ♣ Object's lifetime extends until the earliest event: Client drops reference to object Object's lease expires ♣ Similar to COM coclass activation semantics ♣ Can store perper-client state, receive constructor args Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 34 O 35 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 36 Sistemi Distribuiti, Paolo Nesi 9 Dipartimento di Sistemi e Informatica, University of Florence Client activation example Registering Client Activated Objs O using using using using using Server registers a client activated type using RegisterActivatedServiceType System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Http; System.Runtime.Remoting.Channels.Tcp; class RemotingHost { static void Main(string[] args) { RemotingConfiguration.ApplicationName = "WiseOwlMathService"; ♣ Specifies the type being registered ActivatedServiceTypeEntry ASTE = new ActivatedServiceTypeEntry(typeof(WiseOwl.Calculator)); RemotingConfiguration.RegisterActivatedServiceType(ASTE using System.Runtime.Remoting; . . . ActivatedServiceTypeEntry ASTE = new ActivatedServiceTypeEntry(typeof(WiseOwl.Calculator)); ChannelServices.RegisterChannel(new HttpChannel(9000)); ChannelServices.RegisterChannel(new TcpChannel(4242)); Console.ReadLine(); RemotingConfiguration.RegisterActivatedServiceType(ASTE); } } Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 37 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Client activation URLs O 38 Remoting config file 2 Client activated objects do not need a unique URL for each object O As before, all hardhard-coded remoting information can reside in external config file ProtocolScheme://ComputerName:Port/PossibleApplicationName ♣ PossibleApplicationName becomes virtual directory name ♣ PossibleApplicationName becomes virtual directory name when hosted in IIS ♣ A TcpChannel requires the port number Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 <configuration> <system.runtime.remoting> <application name="WiseOwlMathService"> <service> <activated type="WiseOwl.Calculator,MathObjects" /> </service> <channels> <channel port="9000" ref="http" /> <channel port="4242" ref="tcp" /> </channels> </application> </system.runtime.remoting> </configuration> 39 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 40 Sistemi Distribuiti, Paolo Nesi 10 Dipartimento di Sistemi e Informatica, University of Florence Revised Server Example O Remoting clients Server uses config file doesn't change! O ♣ WellWell-known objects exist at a URL Client obtains proxy using Activator.GetObject Client can also obtain proxy using new ♣ Client activated object factory exists at a URL Client requests factory to instantiate object and return a proxy to it using Activator.CreateInstance Client can also make same request using new using System; using System.Reflection; using System.Runtime.Remoting; class RemotingHost { static void Main(string[] args) { String s = Assembly.GetExecutingAssembly().Location; RemotingConfiguration.Configure (s + ".config"); Console.ReadLine(); } } Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 41 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Activator.GetObject O A clients wants to use a remote object 42 RemotingServices.Connect GetObject returns a proxy for the wellwell-known type served at the specified location O Dim o as Object = Activator.GetObject ( GetType (WiseOwl.Calculator), "http://localhost:9000/WiseOwlMathService/SharedCalc") GetObject is a thin wrapper over System.Runtime.Remoting. RemotingServices.Connect WiseOwl.Calculator c = CType (o, WiseOwl.Calculator) Using System.Runtime.Remoting; c.Add (42); O static object o RemotingServices.Connect ( Type classToProxy, string url); No network traffic until first method call! ♣ Proxy built on client from metadata ♣ Server activates object on first method call Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 ♣ Which calls System.Runtime.Remoting. RemotingServices.Unmarshal 43 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 44 Sistemi Distribuiti, Paolo Nesi 11 Dipartimento di Sistemi e Informatica, University of Florence RemotingServices.Unmarshal O RemotingServices.Unmarshal does the real work ♣ ♣ ♣ ♣ O Activator.CreateInstance O Client activation requires a network round trip ♣ Send activation message to server Can include constructor parameters ♣ Server creates object using specified constructor ♣ Server builds ObjRef about new instance ♣ Server sends message with ObjRef to client ♣ Client creates proxy from ObjRef Checks that type is MarshalByRef or Interface Find or creates identity based on URI Creates envoy and channel sink chains Gets or creates transparent and real proxy End results is client gets a proxy Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 45 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Activator.CreateInstance O Complete client application I CreateInstance returns a proxy to a new instance of the type served at the specified location Imports Imports Imports Imports Imports System System.Runtime.Remoting System.Runtime.Remoting.Channels System.Runtime.Remoting.Channels.Http System.Runtime.Remoting.Channels.Tcp Class RemotingClient Shared Sub Main() ' Register channel(s) ChannelServices.RegisterChannel(New HttpChannel()) Dim activationAttributes() As Object = { New _ Activation.UrlAttribute("http://localhost:9000/WiseOwlMathService") } ' Connect to a Well-known object Dim uriWKO As String = "http://localhost:9000/WiseOwlMathService/SharedCalc" Dim o As Object = Activator.GetObject(GetType(WiseOwl.Calculator), uriWKO) Dim o As Object = Activator.CreateInstance(GetType(WiseOwl.Calculator), Nothing, activationAttributes) ' Use the Calculator Dim c As WiseOwl.Calculator c = CType(o, WiseOwl.Calculator) WiseOwl.Calculator c = CType (o, WiseOwl.Calculator) c.Add (42); Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 46 c.Add(21) End Sub End Class 47 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 48 Sistemi Distribuiti, Paolo Nesi 12 Dipartimento di Sistemi e Informatica, University of Florence Complete client application II Imports O Imports Imports Imports Imports Client's remoting config file System Still need to information runtime of proper channels to use System.Runtime.Remoting O System.Runtime.Remoting.Channels System.Runtime.Remoting.Channels.Http System.Runtime.Remoting.Channels.Tcp ♣ RemotingConfiguration.Configure (file) Class RemotingClient Shared Sub Main() ' Register channel(s) ChannelServices.RegisterChannel(New TcpChannel()) <configuration> <system.runtime.remoting> <application name="WiseOwlMathService"> <client url = "http://localhost:9000/WiseOwlMathService" displayName = "WiseOwlMathService"> <activated type = "WiseOwl.Calculator,MathObjects"/> <wellknown type = "WiseOwl.BadCalculator,MathObjects" url="http://localhost:9000/WiseOwlMathService/BadCalc"/> </client> </application> </system.runtime.remoting> </configuration> ' Create a client activated object Dim url As String = "tcp://localhost:4242/WiseOwlMathService" Dim activationAttributes() As Object = { New Activation.UrlAttribute(url) } Dim o As Object = Activator.CreateInstance(GetType(WiseOwl.Calculator), _ Nothing, activationAttributes) ' Use the Calculator Dim c As WiseOwl.Calculator c = CType(o, WiseOwl.Calculator) c.Add(21) End Sub End Class Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 49 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Complete client application III O 50 Default client channels All remoting information from config file O Machine.config configuration file defines two default, delaydelayloaded client channels ♣ HttpClientChannel and TcpClientChannel Class RemotingClient Shared Sub Main() ' Use remoting configuration in file Dim s As String = System.Reflection.Assembly.GetExecutingAssembly().Location System.Runtime.Remoting.RemotingConfiguration.Configure(s + ".config") <channel ref="http client" displayName="http client (delay loaded)" delayLoadAsClientChannel="true" /> <channel ref="tcp client" displayName="tcp client (delay loaded)" delayLoadAsClientChannel="true" /> . . . <channel id="http client" type="System.Runtime.Remoting.Channels.Http.HttpClientChannel,System.Runtime.Remoting" /> <channel id="tcp client" ' Use the Calculator Dim c As WiseOwl.Calculator = New WiseOwl.Calculator() c.Add(21) ' Use the BadCalculator Dim b As WiseOwl.BadCalculator = New WiseOwl.BadCalculator() b.Add(21) type="System.Runtime.Remoting.Channels.Tcp.TcpClientChannel, System.Runtime.Remoting" /> O End Sub End Class Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 As with a server, all client remoting information can reside in external config file 51 Must register explicit client channel to get callbacks or use a nonnon-default channel type Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 52 Sistemi Distribuiti, Paolo Nesi 13 Dipartimento di Sistemi e Informatica, University of Florence How does it work? O RealProxy class Client receives a proxy object when activating a remote object O RealProxy forwards msg to remote object O RealProxy class can be extended, customized ♣ Client "thinks" proxy is actual object O Proxy is instance of TransparentProxy class O A call on the proxy: ♣ Handles all method calls to remote object ♣ Mimics inheritance hierarchy of remote object ♣ For example, load balancing method calls, client side validation/processing of certain calls ♣ passes control to actual object when in same domain ♣ creates an IMessage to object in different domain ♣ Passes message to a RealProxy instance Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 O TransparentProxy cannot be replaced ♣ Internal remoting implementation class 53 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 IsTransparentProxy O ObjRef O You can call IsTransparentProxy on any object reference to see if it is a proxy O ♣ Normally, you don't care How does TransparentProxy know about the remote class? bool RemotingServices.IsTransparentProxy (Object o); Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Runtime creates an ObjRef when you register an object with the remoting services An ObjRef contains all information required to locate and access a remote object ♣ ♣ ♣ ♣ ♣ using System.Runtime.Remoting; O 54 55 the strong name of the class the class's hierarchy (its parents) the names of all interfaces the class implements the object URI details of all available registered channels Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 56 Sistemi Distribuiti, Paolo Nesi 14 Dipartimento di Sistemi e Informatica, University of Florence How to remote existing objects O RemotingServices.Marshal Server/client activation expose "new" objects // // On the server, we find our hero about to go public. . . WiseOwl.Calculator calc = new WiseOwl.Calculator (); ♣ What about existing objects? O RemotingService.Marshal ♣ ♣ ♣ O // Let the remoting layer (and the world) know about it ObjRef or = RemotingServices.Marshal (calc, "ExplicitCalculator"); Accepts a MarshalByRefObject Registers it with remoting Returns an ObjRef // Clients can now connect to the Calculator as a Well-known object // prot://machine:port/WiseOwlMathServices/ExplicitCalculator // Alternatively, we can serialize and send the ObjRef to a client // System.Runtime.Serialization.Formatters.Soap.SoapFormatter sf = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter (); System.IO.FileStream fs = new System.IO.FileStream (@"C:\ObjRef.xml", System.IO.FileMode.Create); sf.Serialize (fs, or); fs.Close (); RemotingService.Unmarshal ♣ Accepts an ObjRef ♣ Returns a proxy Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 57 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 RemotingServices.Unmarshal ClientClient-side remoting O ' ' There's an ObjRef serialized to a file using the SOAP formatter ' Get a formatter that can read the format Dim sf As System.Runtime.Serialization.Formatters.Soap.SoapFormatter sf = New System.Runtime.Serialization.Formatters.Soap.SoapFormatter() O ' Open a stream on the file Dim fs As System.IO.FileStream fs = New System.IO.FileStream("C:\ObjRef.xml", System.IO.FileMode.Open) O ' Deserialize the object in the file Dim o As Object = sf.Deserialize(fs) O fs.Close() 58 Client calls method on TransparentProxy TransparentProxy builds message ♣ Stack frame to message O O O O TransparentProxy passes msg to RealProxy RealProxy forwards msg to envoy sink(s) Last envoy sink forwards msg to context sink(s) Last context sink forwards msg to channel sink(s) Channel sinks turn message into a byte stream Last channel sink sends byte stream to server ' Done with the file ' Object is really an WiseOwl.Calculator Dim c As WiseOwl.Calculator = CType(o, WiseOwl.Calculator) ' Use the Calculator c.Add(21) Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 59 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 60 Sistemi Distribuiti, Paolo Nesi 15 Dipartimento di Sistemi e Informatica, University of Florence ServerServer-side remoting O O Remoting chain Channel receives a stream of bytes Channel forwards stream to channel sink(s) Message Transparent Proxy ♣ Last channel sink converts stream into message O Last channel sink forwards msg to context sink(s) Last context sink forwards msg to server sink(s) O Stack frame sink builds and issues call to requested method O Envoy Envoy Envoy Sink Sink Sinks Real Proxy Tx Tx Context Sink Sink Sinks Formatter Sink 010110… Transport Sink Channel ♣ Last server sink is stack frame sink Channel Sink Channel Sink Client-side Server-side 010110… Channel Transport Sink Channel Sink Channel Sink Message Server object Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 61 Tx Tx Context Sink Sink Sinks Formatter Sink 62 Web Services O Expose WebService endpoints from any process over any transport using any payload encoding Process types include console apps, graphical applications, NT Services, IIS BuiltBuilt-in Transports include HTTP and TCP O BuiltBuilt-in encodings include SOAP and Binary O Supports SOAP 1.1 (~XSD) type system O O .NET supports two basic forms of remoting ♣ Web Services An entry point into application specified by an URL • <protocol>:<machine>:<port>/<URI> E.g. http://localhost:4242/SomeServiceName Uses SOAP data types ♣ CLR Object Remoting Builds on Web Services Uses native CLR data types Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Tx Tx Server Sink Sink Sinks Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 .NET Remoting O Stack Builder Sink ♣ Extensible via pluggable channels ♣ Extensible via pluggable serialization formatters 63 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 64 Sistemi Distribuiti, Paolo Nesi 16 Dipartimento di Sistemi e Informatica, University of Florence CLR Object Remoting O Remoting via Web Services Full CLR type system fidelity ♣ class hierarchies, constructors, delegates, interfaces, methods, overloaded methods, properties, fields O Supports additional features over Web Services O ♣ Marshal by value (make a copy) ♣ Marshal by reference (pass an ObjRef) ObjRef) O O O O 65 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Remoting via HTTP O .NET client 66 Remoting via TCP .NET using HTTP/SOAP O ♣ HTTP channel uses the SOAP formatter Can override this default behavior Less efficient than binary formatter ♣ Firewall friendly ♣ Uses CLR type system, not XSD Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 .NET using HTTP/SOAP ♣ .NET object exposed as a Web Service by hosting in IIS ♣ Web Services use wellwell-defined interfaces called contracts Contracts are described using a Web Services Description Language (WSDL) file ♣ Any client that can consume a WSDL file can make SOAP calls to the the remote object as per the contract ♣ Firewall friendly, client OS agnostic ♣ XML Schema data (XSD) types used in contract Maintains distributed object identity Provides object activation semantics Allows control over object lifetime using leases Permits out of band info using CallContext Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Any client .NET client .NET using TCP channel ♣ TCP channel uses the binary formatter Can override this default behavior More efficient than SOAP formatter ♣ Raw socket connection used for transport Mostly useful behind a firewall, not through one 67 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 68 Sistemi Distribuiti, Paolo Nesi 17 Dipartimento di Sistemi e Informatica, University of Florence Remoting via DCOM O .NET client COM Using IIS as the host server .NET O ♣ .NET client to COM uses RCW and COM interop DCOM used when COM object is remote ♣ COM to .NET uses CCW and COM interop DCOM used when .NET server is remote O ♣ Server does not have to be manually started ♣ IIS uses web.config remoting config file <configuration> <system.runtime.remoting> <application> <service> <wellknown mode="SingleCall" type="WiseOwl.Calculator,MathObjects" objectUri = "EphemeralCalc.rem" /> <wellknown mode="Singleton" type="WiseOwl.Calculator,MathObjects" objectUri = "SharedCalc.soap" /> <activated type = "WiseOwl.Calculator,MathObjects"/> </service> </application> </system.runtime.remoting> </configuration> Useful in heterogeneous environments Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 69 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 WSDL O 70 IIS notes Web Service Description Language O ♣ The service description is an XML document written in an XML grammar that defines the format of messages the Web Service understands O IIS provides activation WKO URIs must end with .soap or .rem ♣ Can add additional bindings in machine.config IIS provides service descriptions via reflection WSDL for WKO at ObjectURI with ?wsdl ?wsdl query http://< http://<Computer> Computer>:<Port> Port>/<VirtDir> VirtDir>/ObjectURI> ObjectURI>?wsdl WSDL for CAO at following URI with ?wsdl ?wsdl query http://< http://<Computer> Computer>:<Port> Port>/<VirtDir> VirtDir>/RemoteApplicationMetadata.rem?wsdl Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 71 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 72 Sistemi Distribuiti, Paolo Nesi 18 Dipartimento di Sistemi e Informatica, University of Florence SoapSuds notes O Server activated object issues SoapSuds.exe builds a remoting proxy given WSDL description of a web service O ♣ Can have it build an XML schema, source, metadata assembly ♣ ♣ Name of assembly containing the type must be identical on client and server ♣ Name of type must be identical on client and server ♣ SoapSuds builds assembly with correct name soapsuds -url:http://localhost/WiseOwlIISMathService/SharedCalc.rem?wsdl -gc Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 73 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Client activated object issues O O 74 Remoting O Same requirements as server activated objects Additionally, client assembly must contain an implementation of the types O O ♣ All members must have identical signatures as same members in the server's implementation ♣ Implementation need not be the same! Typically stubs throw NotSupportedException SoapSuds creates such stubs for clients using SOAP Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 Type identity is determined using the type and assembly name combination O 75 Il Remoting fornisce una struttura che consente agli oggetti di interagire tra di loro anche se risiedono su diversi application domain La comunicazione avviene attraverso canali Prima che i messaggi tra le applicazioni remote vengano inviati sui canali vengono codificati: ♣ In binario per le applicazioni critiche ♣ In XML dove è essenziale interoperabilità interoperabilità I messaggi XML utilizzano sempre SOAP Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 76 Sistemi Distribuiti, Paolo Nesi 19 Dipartimento di Sistemi e Informatica, University of Florence Remoting O O O Remoting I servizi di Remoting offerti dal framework nascondono al programmatore la complessità complessità dei metodi di chiamata remoti. Quando un client attiva un oggetto remoto ne riceve un proxy con il quale interagisce Per prima cosa si registra un canale di comunicazione (HTTP, TCP), TCP), poi diventa possibile registrare gli oggetti remoti O Per la registrazione di un oggetto remoto servono i seguenti dati: dati: ♣ Il nome del tipo di oggetto remoto. ♣ L'oggetto URI (Uniform (Uniform Resource Identifier) Identifier) che i client utilizzeranno per individuare l'oggetto. ♣ La modalità modalità oggetto richiesta per l'attivazione da server, che può essere SingleCall o Singleton. Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 77 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 78 Remoting using using using using O SigleCall namespace RemotingSamples { public class Sample { ♣ Un oggetto SingleCall crea un'istanza di classe per ogni chiamata del client, client, anche se le chiamate provengono dallo stesso client. client. server.cs server.cs public static int Main(string [] args) { // Crea e registra un nuovo canale Tcp TcpChannel chan = new TcpChannel(8085); ChannelServices.RegisterChannel(chan); // Il metodo RegisterWellKnownServiceType permette di registrare l’oggetto per la // futura attivazione [PARAMETRI (Tipo, URI, metodo di attivazione)] RemotingConfiguration.RegisterWellKnownServiceType (Type.GetType("RemotingSamples.HelloServer,object"), "SayHello", WellKnownObjectMode.SingleCall); System.Console.WriteLine("Hit to exit..."); System.Console.ReadLine(); return 0; } ♣ L'invocazione successiva, sarà sarà sempre servita da una differente istanza del server anche se la precedente non è stata ancora riciclata dal sistema. O System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Tcp; Singleton ♣ Un oggetto Singleton invece non presenta mai più più di una istanza contemporaneamente ♣ Se una istanza è già già esistente la richiesta viene soddisfatta da quella istanza. Se l'istanza non esiste, alla prima richiesta viene creata dal server server e tutte le successive richieste vengono soddisfatte da quella istanza. } } Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 79 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 80 Sistemi Distribuiti, Paolo Nesi 20 Dipartimento di Sistemi e Informatica, University of Florence using using using using System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Tcp; namespace RemotingSamples { public class HelloServer : MarshalByRefObject { using using using using object.cs client.cs namespace RemotingSamples { public class Client { public static int Main(string [] args) { TcpChannel chan = new TcpChannel(); ChannelServices.RegisterChannel(chan); // Il client localizza l’oggetto remoto passando tipo e URL HelloServer obj = (HelloServer)Activator.GetObject(typeof(RemotingSamples.HelloServer) , "tcp://localhost:8085/SayHello"); if (obj == null) System.Console.WriteLine("Could not locate server"); else Console.WriteLine(obj.HelloMethod("Carlo")); return 0; } } } public HelloServer() { Console.WriteLine("HelloServer activated"); } public String HelloMethod(String name) { Console.WriteLine("Hello.HelloMethod : {0}", name); return "Hi there " + name; } } } Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Tcp; 81 Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 82 References O O Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 83 http://www.dotnetremoting.cc http://www.chttp://www.c-sharpcorner.com/Remoting.asp Sistemi Distribuiti, Univ. Firenze, Paolo Nesi 2004-2005 84 Sistemi Distribuiti, Paolo Nesi 21
Documenti analoghi
Sistemi P2P - Dipartimento di Ingegneria dell`Informazione
it is not always possible in P2P solutions in which it is tracked who has
downloaded the file, or has the reference
Notification of changes in the downloaded files, in the accessed resources, e...