Chap 2. Architeture and Design Goals

Save this PDF as:
 WORD  PNG  TXT  JPG

Size: px
Start display at page:

Download "Chap 2. Architeture and Design Goals"

Transcription

1 Client-Server Model 1. Client-Server Architecture 2. Message Passing 3. Client-Server Communication 4. IPC 1

2 1. Client Server Architecture Consists of one or more clients and one or more servers. 3 basic components of C/S application 1. Presentation logic 2. Application logic 3. Data management logic Client Server Architecture c lie n t se rve r P A D 2 tie r P A D 2 tier architecture P A A D 2 tier architecture P A D 3 tier architecture 2

3 2. Message Passing Send and Receive operations Single message passing can be supported by send and receive operations. In order for one process to communicate with another, one process sends a message to a destination and another process at the destination receives the message. It involves the synchronization of the two processes. PROCEDURE Send( p: PortId, m: Message) PROCEDURE Receive( p: PortId, VAR m: Message) 3

4 Synchronous/Asynchronous Communication Synchronous communication The sending and receiving processes synchronize at every message. Whenever a Send is issued, the sending process is blocked until the corresponding Receive is issued. Whenever a Receive is issued, the process blocks until a message arrives. Asynchronous communication Send is non-blocking, the sending process is allowed to proceed as soon as the message has been copied to a local buffer The transmission of the message proceeds in parallel with the sending process. In the non-blocking receive, the receiver proceeds with its program after issuing a Receive operation which provides a buffer to be filled in the background. The receiving process must separately receive notification that its buffer has been filled. Non-blocking comm. appears to be more efficient, but it involves extra complexity in the receiving process associated with the need to acquire the incoming message. 4

5 The blocking receive is good in multiple thread environment It can be issued by one thread while other thread in the process remain active, and Synchronizing the receiving threads with the incoming message is simple. A simple blocking receive could wait for the arrival of a message; but for many purposes a timeout is required. Communication Blocking Blocking Languages,Systems Type Send Receive Synchronous Yes Yes occam of the Transputer Asynchronous No Yes Mach, Chorus, BSD 4.x Asynchronous No No Charlotte 5

6 Location-independent identifiers Message Destinations In DOS that use location-independent identifiers, services can be relocated without having to inform clients about their new locations. When the destination in the Send operation is specified as a location-independent identifier, this is mapped to a low-level address in order to deliver a message. This mapping is carried out by routing software when the message is sent and takes into account the current location of the destination. Port Most OSs have chosen to use either processes or ports as message destinations. A port is one of several alternative points of entry to a receiving process. A port is a message destination that has exactly one receiver, but can have many senders. Port enables to deliver the same message to the members of a set of processes. Ports are sometimes called mailboxes - a mailbox always has a message queue, whereas a port may or may not have one. Any process that knows the identifier of a port can send a message to it. Servers generally publicize their port identifiers for use by clients. Mach, Chorus, Amoeba, provides ports with location-independent identifiers. 6

7 Ports For process to receive messages, its socket must be bound to a local port and one of the Internet addresses of the computer on which it runs socket any port agreed port socket client Internet address = message other ports server Internet address =

8 3. Client-Server Communication Message exchanges in typical client-server interaction. In the normal case, request-reply communication is synchronous because the client process blocks until the reply arrives from the sender. Request-reply protocols The Amoeba, Chorus, Mach and V OS have protocols designed to support this communication with less overheads by introducing three of message primitives: DoOperation, GetRequest and SendReply. It uses the server reply message as an ACK of the client request message. DoOperation. (wait). (continuation) Request message Reply message GetRequest execute request SendReply 8

9 Delivery Failure Assumption about request-reply protocol Messages are occasionally dropped by sender, receivers and network gateways. Networks may become partitioned, thus one or more nodes of a network may become detached from the remainder of the network. Processes may sometimes fail. How to recognize this? In general, it is impossible. Network provides communication error-freeness. Possibilities of delivery failure Loss of the request message Server process failure during its task Loss of the reply message Three types of request/reply protocols the request (R) protocol the request/reply (RR) protocol the request/reply/acknowledge-reply (RRA) protocol 9

10 Operations for Reliability Timeouts To prepare the failure, DoOperation should use a timeout when it is waiting reply. When the timer expires, it may return immediately from DoOperation with an indication. Alternatively, DoOperation may send the request message repeatedly until either it succeeds or else it is reasonably sure that the delay is due to the server. Discarding duplicate request messages In cases when the request message is retransmitted, the server may receive it more than once. To avoid repeated processing, the protocol is designed to recognize successive messages (from the same client) with the same message identifier and to filter out duplicates. Lost reply messages If the server has already sent the reply when it receives the duplicate request, it may need to execute the operation again to obtain the result. Idempotent operation An operation that can be performed repeatedly with the same effect as if it had been performed exactly once. A server whose operations are all idempotent need not take special measure to avoid executing its operations more than once. 10

11 History To allow the server to retransmit reply messages when client processes request them. For servers that require retransmission of replies without re-execution of operations, a history may be used. An entry contains a message identifier, a message and an identifier of the client. A problem is its memory cost. It will become very large unless the server can tell when the messages will no longer be needed for retransmission. Multipacket message Each packet has an element that indicates whether it is part of a multipacket and a sequence number. Acknowledgment Server acknowledges once when all the packets have been received. Server acknowledges each request packet. 11

12 BSD 4.x UNIX 4. IPC in UNIX IPC primitives in BSD 4.x are provided as system calls which are implemented as a layer over the Internet TCP and UDP protocols. Message destinations are specified as socket addresses A socket address is a communication identifier. It consists of a local port number and an Internet address. Socket mechanism Messages are queued at the sending socket until the networking protocol has transmitted them, and until an ACK arrives, if the protocol requires one. When messages arrive, they are queued at the receiving socket until the receiving process makes an appropriate system call to receive them. The socket call returns a descriptor by which the socket may be referenced in subsequent system calls. Before a pair of processes can communicate, the recipient must bind its socket descriptor to a socket address The sender must also bind its socket descriptor to a socket address if it requires a reply. Once a socket has been bound, its address cannot be changed. 12

13 Datagram communication In order to send datagrams, a socket pair is identified each time a communication is made. This is achieved by the sending process using its local socket descriptor and the socket address of the receiving socket. Stream communication In order to use the stream protocol, two processes must first establish a connection (uni- or bi-directional) between their pair of sockets. When a connection is accepted, UNIX automatically creates a new socket and pairs it with the client's socket so that the server may continue listening for other clients' connection requests through the original socket. 13

14 Procedure to Use Stream The server (listening process) first uses the socket operation to create a stream socket. The server binds its socket to a socket address. It uses listen operation to listen on its socket for client requests for connections. The client creates socket. Then the client uses the connect system call to request a connection via the socket address of the listening process. As the connect call automatically binds a socket name to the caller's socket, prior binding is unnecessary. The server uses the accept system call to accept a connection requested by a client and obtain a new socket for communication with that client. The original socket may still be used to accept further connections with other clients. 14

15 Sockets used for datagrams Sending a message Receiving a message s = socket(af_inet,sock_dgram, 0) bind(s, ClientAddress) sendto(s, message, ServerAddress) s = socket(af_inet,sock_dgram, 0) bind(s, ServerAddress) amount = recvfrom(s, buffer, from) ServerAddress and ClientAdderss are sockets consisting of internet address and port number 15

16 Sockets used for streams Requesting a connection s = socket(af_inet, SOCK_STREAM, 0) connect(s, ServerAddress) write(s, message, length) Listening and accepting a connection s = socket(af_inet, SOCK_STREAM, 0) bind(s, ServerAddress); listen(s,5); snew = accept(s, from); N = read(snew,buffer,amount) ServerAddress is a socket consisting of internet address and port number 16

17 Middleware 1. Definition 2. RPC Middleware 3. DB Middleware 4. MOM 5. TP Monitor 6. CORBA 7. CORBA Programming 8. OLE/COM/DCOM 17

18 1. Definition 미들웨어 (middleware) Computer와 computer 사이에통신및정보처리를지원하는기능 OSI 참조모델의 5계층 ~6계층에존재하면서컴퓨터와컴퓨터간의통신을쉽고안전하게제공하며이에대한관리를도와주는소프트웨어 네트웍프로그램을 빠르게작성하고 쉽게사용하며 편하게관리하게하는기능 - of the client-server system, / of the client/server system 18

19 Technology 에의한분류 RPC middleware Message Oriented Middleware(MOM) Transaction Processing(TP) Monitor Object based middleware Groupware 미들웨어의종류 용도에의한분류 Computer communication (RPC, Groupware, CORBA) DB middleware Mobile computing middleware Home automation middleware 19

20 2. RPC Middleware Remote Procedure Call 기반미들웨어 이종시스템의프로세스들간통신을위해데이터표현변환, synchronization 을지원 단순한 point-to-point 형태이므로다양한형태의응용프로그램지원에한계 장애감내성 (fault tolerance), 트랜잭션처리부적절 예 : Inprise 의 Entera( 20

21 Remote Procedure Call Model client process server process local procedure call = (1) client routines client stub (10) server routines (6) (5 ) server stub system call = (2) (9) (7) (4) network routines (8) (3) = network communications network routines 21

22 Executing in order 1. The client calls a local procedure,called the client stub. The purpose of the stub is to package up the arguments to the remote procedure, possibly put them into some standard format and then build one or more network messages. 2. Network messages are sent to the remote system by the client stub. This requires a system call into the local kernel. 3. The network messages are transferred to the remote system. 4. A server stub procedure is waiting on the remote system for the client s request. It unmarshals the arguments from the network messages and possibly converts them. 5. The server stub executes a local procedure call to invoke the actual server function, passing it the arguments that it received in the network messages from the client stub. 6. When the server procedure is finished, it returns to the server stub, returning whatever its return values are. 7. The server stub converts the return values, if necessary, and marshals them into one or more network messages to send back to the client stub. 8. The messages get transferred back across the network to the client stub. 9. The client stub reads the network messages from the local kernel. 10. After possibly converting the return values, the client stub finally returns to the client function. 22

23 Sun RPC An actual RPC implementation with the Sun RPC system. Consists of the following parts rpcgen, a compiler that takes the definition of a remote procedure interface, and generates the client stubs and the server stubs. XDR(eXternal Data Representation), a standard way of encoding data in a port-able fashion between different systems. A run-time library to handle all the details. Example Defines two functions that the client calls using RPC. bin_date_1 : returns the current time as the number of seconds since 00:00;00 GMT, January 1,1970. str_date_1 : takes a long integer value from the previous function and converts it into an ASCII string that is fit for human consumption. 23

24 Files involved in generating a Sun RPC program server procedures server program date_proc.c server stub cc date_svc date_svc.c RPC specification file date.x rpcgen date.h RPC run-time library client main function date_clnt.c client program rdate.c cc rdate Must provide the three files date_proc.c : server procedures that are called remotely from the client. date.x : RPC specification file. rdate.c : client main function. rpcgen compiler takes the date.x file and generates two C files, the client stub and the server stub, along with a header file. 24

25 date.x / * date.x - Specification of remote date and time service. */ / * Define 2 procedures : * bin_date_1() returns the binary time and date(no arguments). * str_date_1() takes a binary time and returns a human-readable string. * / program DATE_PROG{ version DATE_VERS { long BIN_DATE(void) = 1; / * procedure number = 1 * / string STR_DATE(long) = 2; / * procedure number = 2 * / } = 1; / * version number = 1 * / } = 0x ; / * program number = 0x * / date.h (generated by rpcgen) #definedate_prog ((unsigned long)(0x )) #definedate_vers ((unsigned long)(1)) #definebin_date ((unsigned long)(1)) extern long * bin_date_1(); #definestr_date ((unsigned long)(2)) extern char ** str_date_1(); #endif /*!_DATE_H_RPCGEN */ 25

26 rdate.c ( client program for remote date service) #include <stdio.h> #include <rpc/rpc.h> /* standard RPC include file */ #include "date.h /* this file is generated by rpcgen */ main(argc,argv) int argc; char *argv[]; { CLIENT *cl; /* RPC handle */ char *server; long * lresult; /* return value from bin_date_1() */ char **sresult; /* return value from str_date_1() */ if(argc!=2){ fprintf(stderr,"usage:%s hostname n",argv[0]); exit(1); } server=argv[1]; 26

27 /* create the client handle */ if((cl=clnt_create(server,date_prog,date_vers,"udp"))==null){ clnt_pcreateerror(server); /* couldn t establish connecion with server. */ exit(2); } /* Fist call the remote procedure bin_date */ if( (lresult=bin_date_1(null,cl)) ==NULL){ clnt_perror(cl,server); exit(3); } printf("time on host %s=%ld n",server,*lresult); } /* call the remote procedure str_date */ if((sresult=str_date_1(lresult,cl))==null){ clnt_perror(cl,server); exit(4); } printf("time on host %s=%s",server,*sresult); clnt_destroy(cl); /* done with the handle */ exit(0); 27

28 call clnt_create to create an RPC handle to the specified program and version on a host and specify UDP as the protocol call bin_date_1, the first argument of the call is the argument we defined in the date.x specification file -a void argument that we specify as a NULL pointer. The second argument is the client handle. The return value is a pointer to a long integer. call str_date_1 function, the first argument is a pointer to a long integer. 28

29 dateproc.c ( remote procedures ; called by server stub) #include <rpc/rpc.h> #include "date.h" /* return the binary date and time */ long* bin_date_1(){ static long timeval; /* must be static */ long time(); /* unix function */ timeval =time((long*)0); return(&timeval); } /* convert a binary time and return a human readable string. */ char ** str_date_1(bintime) long *bintime; { static char *ptr; char *ctime(); ptr=ctime(bintime); /* convert to local time */ return(&ptr); /* return the address of pointer */ } 29

30 return values must be static variable because both functions return the address of these variables. Steps to use RPC 1. Compile the RPC specification file rpcgen date.x 2. The client stub is compiled with our client main function to generate the executable client program. gcc -o rdate rdate.c date_clnt.c -lnsl 3. Generate the server program by compiling the server stub along with server function. gcc -o date_svc date_proc.c date_svc.c -lnsl 4. Start server as a background process date_svc & 5. Invoke it from anather system(or same system) using client program 6. Result./rdate concert.comeng.chungnam.ac.kr time on host concert = time on host concert = Mon Aug 30 14:05:

31 Steps involved in RPC calls portmapper daemon (1) tell port mapper who we are date_svc (server) remote system (2) (3) (4) rdate (client) local system (1) When we start the server program on the remote system, it creates a UDP socket and binds any local port to the socket and calls a function in the RPC library, svc_register, to register its program number and version. This function contacts the port mapper process to register itself. The port mapper keeps track of the program number, version number, and port number. Server then waits for a client request. This step are done by the server stub, the main function that is generated by the rpcgen compiler. 31

32 (2) Starting client program and it calls the clnt_create function. This call specifies the name of the remote system, the program number, version number, and the protocol. This function contacts the port mapper on the remote system to find out the UDP port for the server. (3) Client program calls the bin_date_1 function. This function is defined in the client stub that was generated by the rpcgen compiler. This function sends a datagram to the server, using the UDP port number from the previous step and waits for a response, this stub determines which procedure is being called and calls our bin_date_1 function. When our function returns to the server stub, the stub takes the return value, converts it into the XDR standard format and packages it into a datagram for transmission back to the client. When the response if received, the client stub takes the value from the datagram, converts it as required, and returns it to our client program. (4) Client calls the str_date_1 function, which goes through a similar sequence of operations as described in the previous step. One difference is that the client stub has to pass an argument to the remote procedure. 32

33 Transparency issues Parameter passing A single argument and a single result are allowed. Multiple arguments or return values must be packaged into a structure Binding The port mapper daemon on the desired remote system is contacted to locate a specific program and version. The caller has to specify the name of the remote system and the transport protocol. Transport protocol Supports either UDP or TCP. Exception Handling Using UDP : it automatically times out and retransmits an RPC request, if necessary. Using TCP : an error is also returned to the caller if the connection is terminated by the server. Call Semantics Every client request carries a unique transaction ID, 32-bit integer termed the xid. 33

34 Data Representation Supported by XDR. Security Null authentication Unix authentication DES authentication 34

35 3. DB Middleware Client 가 DB에접속해SQL(Structured Query Language) 을사용할수있도록함. 이종의 DB를대상으로 client 프로그램을작성할수있도록 MS에서 ODBC(Open Database Connectivity) 규격정의 주로특정 DB 제품에의존적인 2-tier 구조 (client : DB) 최근컴퓨팅환경이 3-tier 화함에따라위축 예 : ORACLE의 SQL*Net( 35

36 4. MOM 프로세스간메시지형식의통신기능제공 Non-blocking, Store-and-forward 통신 36

37 메시지를 queue 저장한후관리, 전송 우선순위등급에따라메시지처리속도차별화 내용에따라불필요한메시지 filtering 가능 전자메일, FAX, 음성메일등최근인터넷응용에적합 예 : IBM의 MQSeries, BEA의 MessageQ ( 37

38 5. TP Monitor 트랜잭션처리를감시, 관리하는소프트웨어 IBM 메인프레임에서은행입출금처리업무에적용된것을시초로하여많은사용자를대상으로즉각적인처리를필요로하는업무에보편화 프로세스관리기능과트랜잭션관리기능으로구성 프로세스관리기능 : 시스템성능감시, 동작상태감시 트랜잭션처리및관리 확장성및장애감내성우수 예 : IBM 의 CICS, IMS, BEA 의 TUXEDO, TOPEND( OTM(Object Transaction Manager) 로발전 38

39 6. CORBA Object Based Middleware 분산객체 ( 프로그램, 데이터 ) 간통신 객체지향기술과더불어최근각광 ORB(Object Request Broker) TP 모니터기능추가위해 OTS(Object Transaction Service) 정의 예 : OMG의 CORBA, MS의 DCOM CORBA Common Object Request Broker Architecture 39

40 Distributed Object System 배경 OMG CORBA Develop Client/Server SW in the Heterogeneous Network(HN) Need to Integration Method of a group of Application in DS RPC, OLE(Object Linking and Embedding) -->primitive OMG --> CORBA Standard 제정 OMG Consortium : 1984 OMA(Object Management Architecture) 제안 (1990) OMA(Object Management Architecture) CORBA(Common Object Request Broker) OMG ORB(Object Request Broker) Software Bus 40

41 Community Group PTC(Platform Technology Community) : CORBA 자체하부기술 DTC(Domain Technology Community) : CORBA 기반응용분야 GSIG(General Special Interest Group) : OMG 전반에관련된명세 OMA 구조 : OO-based Application Objects C,C++,Java,Smalltalk... Vertical Facilities user interface info manage Horizontal Facilities Common Object Request Broker Architecture Name Event Life Cycle Persistence Relationships Externalization Transactions Concurrency Security Time Licensing Properties Query Trading Collections Startup CORBA Services 41

42 Object Request Broker(ORB) CORBA Concept Request : Clint Request---->Object Implementation(Server) (ORB) Structure of ORB Interface Client Object Implementation IDL Complier Dynamic Invocation IDL Stubs ORB Interface Static IDL Skeleton Dynamic Skeleton Object Adapter ORB Core ORB implimentation interface object adapter interface stubs/skeleton interface ORB-dependant interface 42

43 Object Request Broker ORB Components Static IDL Stubs/Skeletons Static-->defined at the compilation time Define Interface between client and object implementation Compiled by IDL Compiler--> translate the implemented language(c, C++, Java, etc.) Client-->Stub Object Implementation-->Skeleton Dynamic Invocation Interface(DII) Dynamic-->determined at the execution time Client find to an object method in the Interface Repository Request to the object for the service ORB Interface the interface can directly access to the ORB 43

44 Object Request Broker (Con t) Dynamic Skeleton Interface(DSI) Allows dynamic handling of object invocation 외부구현객체호출 Skeleton, stub를갖지않는객체외부객체 Client s Dynamic Invocation Interface와유사 메시지의파라미터를통해객체나메소드 search ORB와 ORB간 bridge나, 외부모듈과의 gateway 구현에적합 Object Adapter Primary way that an Object Implementation accesses services provided by ORB Client s object Service request를받아들이고, 구현객체에 object reference를부여하고, object activate, The method invoke through the skeleton 44

45 Repositories Interface Repository IDL로작성된모든 interface information 저장 client가요구한 service request에대한interface information 조회 ConstantDef, ModuleDef, ExceptionDef, InterfaceDef, TypeDef, OperationDef Implementation Repository 구현객체정보를저장 객체어댑터가구현객체구동시 : 물리적위치, 서버구동방식, 사용프로토콜 IDL Definitions Implementation Installation Interface Repository Stubs Stubs Stubs Skeletons Skeletons Skeletons Implementation Repository Client Object Implementation 45

46 BOA s role Basic Object Adapter Register Object Implementation to Implementation repository Create the instance of new object implementation Grant OID to the created object Inform to the ORB for creation object Receive service request from client through ORB Up-call a method to object implementation by skeleton then skeleton analysis receiving parameters 구현객체호출을위해 Implementation Repository 참조 미리정보가저장되어야함. 객체의물리적위치, 이름, 활성화정책, 사용프로토콜등 Object Activate Policy(4) Shared server policy : BOA 가활성화 (1 server-m OI) Persistent server policy : user 가수동적으로 server 구동 (1 server- m OI) Unshared server policy : server method 를호출할때마다 BOA 가활성화 (1 server-1 method), method 수행수 OI 종료 46

47 CORBA Invocation Principle A request consists of target object operation, parameters optional request context Invocation Caller Caller Stub Marshalling Person::getAge() { return age; }... person *person; Interconnection Network Callee Person->getAge(); Unmarshalling Skeleton Callee 47

48 Service Request Client Static Invocation Method-->using Stubs Dynamic Invocation Interface Declaration of the required object Select an interface of the object implementation from the interface repository get_interface method return the object reference of OI Get the method description lookup_name(), describe() Construction of parameters list NVList(NamedValue list) struct NamedValue{ Identifier name; any argument; long len; Flags arg_modes; }; Construct a request object using create_request --> send to OI 48

49 Client Start-up ORB Interface -->functionality supported by the ORB basic function : Communication function, Method invocation applied to the client object and the object implementation Client Start-up Process step1:get Object_Name (string type) Client Process step2:get Object reference (OID) step3: Request Invoke (method) step4:exception check step5:result OK step6:orbfree() string_to_object OID user Invocation Results Exception ORB Interface Interface Stubs ORB Core 49

50 Object Implementation Start-up Object Implementation Start-up Process Object start-up(activate) Method Invocation Object Inactivate Object Implementation step2: start-up Object Impl. step3: regist Object Impl. step4: activate Object step5: invoke Method Method Skeletons step6:boa Service invoke 활용 Results Basic Object Adapter step1:boa Service Invocation ORB 50

51 Horizontal Facilities User Interface Information Management System Management Common Facility Vertical Facilities : common functionality in the special part Image part Information highway part Distributed simulation part Session part Application development part Mapping part Manufacturing part 51

52 응용프로그램작성단계 7. CORBA Programming IDL 작성및컴파일 클라이언트와서버구현코드작성 구현객체구현 클라이언트와구현객체의메인프로그램작성 생성된모든화일들을컴파일하고링크한후클라이언트와구현객체의바이너리생성 클라이언트와서버바이너리완성 구현저장소에구현객체의실행정보저장 클라이언트바이너리실행 52

53 CORBA 응용프로그램개발절차 Client Source Code Step 2 C++ Compiler Step 1 Client Stub Code Step 3 Client Binary IDL file (. Idl) IDL Compiler Header Orbix Runtime Library Server Skeleton Code Step 3 Server Binary C++ Compiler Server Source Code Step 2 53

54 환경설정과실행 환경설정 Orbix 의실행화일과라이브러리 path 지정과 Orbixd& 명령어를통해 Orbix 실행프로그램을띄운다. 54

55 클라이언트 2 차원격자에대한 IDL 작성 (grid.idl) IDL 작성및컴파일 idl 컴파일러를통해 C++ 형태의소스코드로변환 -B : BOA(Basic Object Adapter) 를이용하는데필요한기능생성 idl -B grid.idl // IDL defintion of a 2-D grid (in row major order): Interface grid { readonly attribute short height; // height of the grid readonly attribute short width; // width of the grid }; // IDL operations // set the element [n,m] of the grid, to value: void set(in short n, in short m, in long value); // return element [n,m] of the grid: long get(in short n, in short m); 55

56 생성파일 IDL 작성및컴파일 grid.hh : Orbix 를운용하는데필요한클래스정의 class grid_dispatch : 해당객체를디스패치하는데필요한메소드선언 class grid : grid 인터페이스가 C++ 클래스로변환된결과 class gridproxyfactoryclass : 프락시객체를생성하고조작하기위해필요한메소드선언 class gridboaimpl : 분산객체처리에필요한 BOA 선언 class grid##x : 분산객체처리에필요한 TIE 선언 gridc.cc grid.hh 에정의한클래스의멤버함수구현 클라이언트가구현객체의구현부분에요구사항을전달하기위한메소드구현 grids.cc 서버구현객체에서필요한메소드선언 56

57 서버측면 IDL 작성및컴파일 idl 컴파일러를통해 C++ 형태의소스코드로변환 -S : 사용자가서버쪽에구현해야할부분을명시 idl -S grid.idl 생성파일 grid.ic, grid.ih, grid.hh, gridc.cc, grids.cc Grid 에대한클래스선언과메소드선언만이정의되어있는 grid.ih 와 grid.ic 화일에각기원하는로직을추가함으로서클라이언트에게서비스할객체를구현한다. grid.ih -> grid_i.h, grid.ic -> grid_i.cc 변경 57

58 Sample Server Source[1] grid.ih #include "grid.hh" class grid== { public: virtual CORBA::Short height (CORBA::Environment &IT_env=CORBA::default_environment) throw (CORBA::SystemException); virtual CORBA::Short width (CORBA::Environment &IT_env=CORBA::default_environment) throw (CORBA::SystemException); virtual void set (CORBA::Short n, CORBA::Short m, CORBA::Long value, CORBA::Environment &IT_env= CORBA::default_environment) throw (CORBA::SystemException); virtual CORBA::Long get (CORBA::Short n, CORBA::Short m, CORBA::Environment &IT_env= CORBA::default_environment) throw (CORBA::SystemException); }; #endif 58

59 Sample Server Source [2] grid_i.h #include "grid.hh class grid_i : public gridboaimpl { short m_height; // store the height short m_width; // store the width long **m_a; // a 2-D array to store the grid data itself public: // ctor grid_i(short h, short w); // dtor virtual ~grid_i(); // functions corresponding to the two IDL readonly attributes. virtual short width(corba::environment &env); virtual short height(corba::environment &env); // functions corresponding to the two IDL operations virtual void set(short n, short m, long value, CORBA::Environment &env); virtual long get(short n, short m, CORBA::Environment &env); }; 59

60 Sample Server Source [3] grid.ic #include "grid.ih" CORBA::Short grid==:: height (CORBA::Environment &IT_env) throw (CORBA::SystemException) { } CORBA::Short grid==:: width (CORBA::Environment &IT_env) throw (CORBA::SystemException) { } void grid==:: set (CORBA::Short n, CORBA::Short m, CORBA::Long value, CORBA::Environment &IT_env) { } CORBA::Long grid==:: get (CORBA::Short n, CORBA::Short m, CORBA::Environment &IT_env) { } 60

61 Sample Server Source [4] grid_i.cc #include "grid_i.h" // ctor grid_i:: grid_i (CORBA::Short h, CORBA::Short w) { m_height=h; // set up height m_width=w; // set up width // now allocate the 2-D array: as an array of pointers to 1-D arrays. m_a = new CORBA::Long* [h]; for (int i = 0; i < h; i++ ) m_a[i] = new CORBA::Long[w]; } // dtor grid_i:: ~grid_i() { // free the individual 1-D arrays: for (int i = 0; i < m_height; i++) delete[] m_a[i]; // then free the overall array: delete[] m_a; } // implementation of the function which reads the height attribute CORBA::Short rid_i::height(corba::environment&) { return m_height; } // implementation of the function which reads the width attribute CORBA::Short grid_i::width(corba::environment &) { return m_width; } // implementation of the set operation: void grid_i::set(corba::short n, CORBA::Short m, CORBA::Long value, CORBA::Environment &) { } m_a[n][m] = value; // implementation of the get operation: CORBA::Long grid_i::get(corba::short n, CORBA::Short m, CORBA::Environment &) { return m_a[n][m]; } 61

62 메인프로그램작성 클라이언트 구현객체쪽의 grid_i 클래스를이용하는클라이언트프로그램 구성 해당클래스선언 (grid_var gridvar;) 구현객체의구현부분과해당클래스를바인딩 (gridvar=grid::bind();) 해당클래스의메소드호출 (gridvar -> height();) 서버 서버쪽클래스인 grid_i 를선언하고, 이를클라이언트에서사용가능할수있도록한다. 62

63 Sample Client Main Source Client.cc #include "grid.hh" #include <stream.h> #include <stdlib.h> int main (int argc, char **argv) { grid_var gridvar; // pointer the grid object that will be used. CORBA::Short h, w; CORBA::Long v; if (argc < 2) { cout << "usage: " << argv[0] << " <hostname>" << endl; exit (-1); } try { gridvar = grid::_bind ("", argv[1]); } catch (CORBA::SystemException &sysex) { cerr << "Unexpected system exception" << endl; cerr << &sysex; exit(1); } catch(...) { cerr << "Bind to object failed" << endl; cerr << "Unexpected exception " << endl; exit(1); } try { h = gridvar->height (); w = gridvar->width (); } catch (CORBA::SystemException &sysex) { cerr << "Unexpected system exception" << endl; cerr << &sysex; exit(1); catch(...) { // no problem reading the height and width: cout << "height is " << h << endl; cout << "width is " << w << endl; 63

64 try { // try to set element [2,4] of the grid - to value 123 gridvar->set (2, 4, 123); // then read back what we have just set: v = gridvar->get (2, 4); } catch (CORBA::SystemException &sysex) { cerr << "Unexpected system exception" << endl; cerr << &sysex; exit(1); } catch(...) { // an error occurred while calling set or get: cerr << "Call to set or get failed" << endl; cerr << "Unexpected exception " << endl; exit(1); } // no problem setting and getting the elememt: cout << "grid[2,4] is " << v << endl; // sanity check: make sure we got the value 123 back: if ( v!= 123 ) { // oops - we didn't: cerr << "something went seriously wrong" << endl; exit(1); } return 0; } 64

65 Sample Server Main Source Srv_Main.cc #include <stream.h> #include <stdlib.h> #include "grid_i.h" int main() { // create a grid object - using the implementation class grid_i grid_i mygrid(100,100); try { // tell Orbix that we have completed the server's initialisation: CORBA::Orbix.impl_is_ready("grid"); } catch (CORBA::SystemException &sysex) { cerr << "Unexpected system exception" << endl; cerr << &sysex; exit(1); } catch (...) { // an error occured calling impl_is_ready() - output the error. cout << "Unexpected exception" << endl; exit(1); } // impl_is_ready() returns only when Orbix times-out an idle server // (or an error occurs). cout << "server exiting" << endl; return 0; } 65

66 코드생성및정보저장 클라이언트와서버바이너리코드생성 스터브와스켈리턴코드그리고작성한프로그램들을통합하여컴파일한후바이너리를생성 client.exe, server.exe 구현객체의구현저장소에실행정보저장 구현저장소에구현된구현객체의위치정보와이름을저장 putit -hflower grid/lab2/ds/jyyou/demos/grid/server 66

67 클라이언트바이너리실행 67

68 catit lsit rmit putit killit pingit 자주쓰는 Orbix 관리명령어 주어진서버에대한정보를구현저장소에서추출하여보여준다. 구현저장소에서해당구현객체를조회하거나매개변수없이사용할경우모든구현객체의이름을보여준다. 구현저장소에서해당서버를삭제한다. 구현저장소에구현된구현객체의위치정보와이름을명시한다. 서버구현객체를종료한다. Orbixd 데몬의생사여부를확인한다. chmodit IR 의소유권한을변경할때사용한다. chownit 구현저장소에대한접근권한을조정할때사용한다. 68

69 8. OLE/COM/DCOM OLE(Object Linking and Embedding)? 초기 OLE 워드내에엑셀시트를삽입하거나파워포인트그림을삽입하는등서로다른데이터를통합해하나의문서를만드는방법으로이해 사용자에게는마치하나의데이터처럼보이지만실제로는두개이상의다른응용프로그램을사용해생성된복합문서를작성하기위한기술 현재 OLE COM(Component Object Model) 이라는기술을바탕으로서로다른응용프로그램들이생산해내는다수의정보소스객체를모아서하나의문서를만들어낼수있는기술 COM 은모든윈도우응용프로그램간의통합이가능한윈도우객체버스 OLE 개발역사 응용프로그램간의데이터교환방법인 DDE(Dynamic Data Exchange) 를확장한새로운데이터교환방법을제안 -> OLE OLE 1.0 : 복합문서중심의역할 OLE 2.0 : 프로그램간의통신기능추가, 다른프로그램의 in-place action OLE 3.0 : 네트워크 OLE 를통합분산윈도우객체, DCE(Distributed Computing Environment) RPC 이용 69

70 COM(Component Object Model)? OLE 의기본토대 COM 응용프로그램을작성한다고가정할때응용프로그램은해당작업을위해운영체제, 각종라이브러리, 그리고다른프로세스와정보를교환 OLE 프로그램작성자는운영체제의시스템호출, 라이브러리의 API 호출, 다른프로세스와의 IPC 호출등각기다른방법을사용하여프로그래밍이어려움 단일한인터페이스를제공해주는 COM 으로문제점해결 COM 객체를이용하여각종라이브러리나운영체제에서 COM 인터페이스를제공한다면단일 COM 인터페이스로일관된접근가능 COM 은 client 프로그램과객체서버프로그램간의상호통신방식을정의한모델 윈도우객체버스 단일컴퓨터내 CORBA 에해당 복수컴퓨터내 CORBA ---->DCOM(Distributed COM) 70

71 COM 객체모델 COM 객체는데이터와메소드로구성 개발되는언어에독립적 윈도우객체버스 COM 단지인터페이스만을알고이를통하면원하는메소드를호출할수있기때문 COM 은인터페이스를통한바이너리표준을제공 이표준을이용하면 C++ 객체든다른바이너리객체든상관할것없이응용프로그램을작성 COM 인터페이스 COM 은인터페이스를작성하기위한기반도구로서 IDL(Interface Definition Language) 을제공 COM IDL 은 DCE IDL 을채용하여사용하기때문에다양한언어로의매핑이불가능 DCE IDL 은 C 언어로의매핑을전제로하기때문 클라이언트가해당인터페이스를통해 COM 객체의메소드를이용하는과정 클라이언트틑해당인터페이스에대한포인터 (COM 에서제공 ) 를얻음 이포인터를따라가면각메소드를가리키고있는함수테이블이존재 이함수테이블에서원하는메소드를호출 71

72 DCOM(Distributed COM)? DCOM 네트웍에서 OLE 가가능하도록만들어진기능 네트웍환경에서프로그램을공유해서사용할수있게하기위해만들어진기술 DCOM 은 LAN, WAN 또는인터넷에서서로다른컴퓨터간의통신을지원하기위한 COM 의확장형 DCOM 을이용하면응용프로그램사용자나응용프로그램간에적절하게위치를분배해서사용가능 로컬이든네트웍이든상관없이어디에나응용프로그램을가져다놓고여러사람이사용가능 클라이언트는오버헤드도없이컴포넌트의메소드를호출해서사용 72

73 CORBA 와 OLE/COM 윈도우프로그래머입장에서 COM/OLE 는보편화된기능일수도있지만, 모든것을 CORBA 프로그램으로대체하거나반대로윈도우프로그램으로대체하는것은불가능 현재분산객체기술의핵심인 OMG 의 CORBA 와 MS 의 COM/OLE, DCOM/OLE 의결합이주요이슈 차세대미들웨어기술 환경적측면 : 기존의 LAN 을기반환경에서인터넷을포함한 WAN 환경으로변환 기술적측면 : 초기파일서버나데이터베이스서버에서분산객체시스템으로전환 각각의장점을바탕으로 CORBA 와 DCOM 을기반으로하는분산객체시스템은계속확산될것으로예상 기존 www 의프로토콜인 HTTP 에 CORBA 의인터넷호환프로토콜이자분산객체호출프로토콜인 IIOP 가통합될전망 인터넷의광범위한확산과아울러인터넷을기반으로한통합정보시스템인인트라넷을구현가능 차세대미들웨어의모습 수많은서버를자동으로찾아다니며클라이언트의서비스를자동으로해결해주는모습일것으로예측 73

74 Memo 74