the druby bookmedia.pragprog.com/titles/sidruby/design.pdfpure ruby druby is a distributed object...

8
Extracted from: The dRuby Book Distributed and Parallel Computing with Ruby This PDF file contains pages extracted from The dRuby Book, published by the Pragmatic Bookshelf. For more information or to purchase a paperback or PDF copy, please visit http://www.pragprog.com. Note: This extract contains some colored text (particularly in code listing). This is available only in online versions of the books. The printed versions are black and white. Pagination might vary between the online and printer versions; the content is otherwise identical. Copyright © 2010 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina

Upload: others

Post on 20-Aug-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The dRuby Bookmedia.pragprog.com/titles/sidruby/design.pdfPure Ruby dRuby is a distributed object system purely targeted to Ruby. It sounds lim-iting, but this also means you can run

Extracted from:

The dRuby BookDistributed and Parallel Computing with Ruby

This PDF file contains pages extracted from The dRuby Book, published by thePragmatic Bookshelf. For more information or to purchase a paperback or PDF

copy, please visit http://www.pragprog.com.

Note: This extract contains some colored text (particularly in code listing). Thisis available only in online versions of the books. The printed versions are blackand white. Pagination might vary between the online and printer versions; the

content is otherwise identical.

Copyright © 2010 The Pragmatic Programmers, LLC.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise,

without the prior consent of the publisher.

The Pragmatic BookshelfDallas, Texas • Raleigh, North Carolina

Page 2: The dRuby Bookmedia.pragprog.com/titles/sidruby/design.pdfPure Ruby dRuby is a distributed object system purely targeted to Ruby. It sounds lim-iting, but this also means you can run
Page 3: The dRuby Bookmedia.pragprog.com/titles/sidruby/design.pdfPure Ruby dRuby is a distributed object system purely targeted to Ruby. It sounds lim-iting, but this also means you can run

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and The PragmaticProgrammers, LLC was aware of a trademark claim, the designations have been printed ininitial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer,Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade-marks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher assumesno responsibility for errors or omissions, or for damages that may result from the use ofinformation (including program listings) contained herein.

Our Pragmatic courses, workshops, and other products can help you and your team createbetter software and have more fun. For more information, as well as the latest Pragmatictitles, please visit us at http://pragprog.com.

The team that produced this book includes:

Susannah Pfalzer (editor)Potomac Indexing, LLC (indexer)Kim Wimpsett (copyeditor)David J Kelly (typesetter)Janet Furlow (producer)Juliet Benda (rights)Ellie Callahan (support)

Original Japanese edition:“dRuby niyoru Bunsan Web Programming” by Masatoshi SekiCopyright © 2005. Published by Ohmsha, Ltd

This English translation, revised for Ruby 1.9, is copyright © 2012 Pragmatic Programmers, LLC.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, ortransmitted, in any form, or by any means, electronic, mechanical, photocopying,recording, or otherwise, without the prior consent of the publisher.

Printed in the United States of America.ISBN-13: 978-1-934356-93-7Encoded using the finest acid-free high-entropy binary digits.Book version: P1.0—March 2012

Page 4: The dRuby Bookmedia.pragprog.com/titles/sidruby/design.pdfPure Ruby dRuby is a distributed object system purely targeted to Ruby. It sounds lim-iting, but this also means you can run

2.2 Design Principles of dRuby

I designed dRuby to extend Ruby method invocation over networks. dRubyis a library to implement distributed objects in Ruby.

dRuby has the following characteristics:

• Limited to Ruby• 100 percent written in Ruby• No IDL required

Let’s look at these concepts a little more closely.

Pure Ruby

dRuby is a distributed object system purely targeted to Ruby. It sounds lim-iting, but this also means you can run dRuby in any environment where Rubycan run (see Figure 10, The software layers, on page 6). This is very similarto Java RMI, which also can run anywhere Java can run.

Figure 11, An example of a system across multiple OSs, on page 6 shows thearchitecture of a complex system across different operating systems.

dRuby is written purely in Ruby without using any C extension libraries—another bonus. Ruby comes with network, thread, and marshaling-relatedlibraries as part of its standard library, so I was able to write everything inRuby. The first version of dRuby had only 160 lines (the current dRuby hasmore than 1,700 lines including RDoc), and the core part of the library is stillthe same (see The First dRuby, on page 7). The concise codebase of dRubydemonstrates how easily you can write a complex library by using just Ruby’sstandard libraries.

Feels Like Ruby

I paid special attention to the compatibility between dRuby and Ruby. Manyfeatures of Ruby remain in dRuby, too.

Ruby is very dynamic. You don’t need to use inheritance most of the timebecause the variables of Ruby aren’t typed. Ruby looks up methods at execu-tion time (method invocation time); these characteristics also apply to dRuby.dRuby doesn’t have type-in variables, and method searches are done at exe-cution time. Because you don’t need to prepare the list of methods and theirinheritance information, you don’t need to write IDL.

dRuby’s core mission isn’t about changing the behavior of Ruby, apart fromextending Ruby method invocation across networks. With this functionality,

• Click HERE to purchase this book now. discuss

Page 5: The dRuby Bookmedia.pragprog.com/titles/sidruby/design.pdfPure Ruby dRuby is a distributed object system purely targeted to Ruby. It sounds lim-iting, but this also means you can run

POSIX Windows Mac OS X

Ruby

dRuby

Application

Figure 10—The software layers. Observe where dRuby sits above the operating systems.

WEBrick Div

DivRWiki

Ring

Div

Dip

POSIX Windows Mac OS X

Figure 11—An example of a system across multiple OSs. Div, Ring, Dip, and RWiki areapplications that use dRuby.

you can have as much ease and fun programming in dRuby as you do withRuby. For example, you can still use a block for method calls and useexceptions as well. Other multithreading synchronization methods, such asMutex and Queue, are also available remotely, and you can use them tosynchronize multiple processes.

Pass by Reference, Pass by Value

Having said all that, sometimes you need to know the difference betweenRuby and dRuby.

In Ruby, objects are all exchanged by reference when you pass or receivemethod arguments, return values, or exceptions.

6 •

• Click HERE to purchase this book now. discuss

Page 6: The dRuby Bookmedia.pragprog.com/titles/sidruby/design.pdfPure Ruby dRuby is a distributed object system purely targeted to Ruby. It sounds lim-iting, but this also means you can run

The First dRuby

The first version of dRuby was created in 1999 and posted to the Japanese Ruby usermailing list.a The email is written in Japanese, but you can see some snippets ofsource code that look very similar to dRuby now.

# Starting drb server.DRb.start_server('druby://hostname:port', front)# Connecting to the remote serverro = DRbObject.new(nil, 'druby://server:port')ro.sample(1, DRbEx.new(2), 3)

The original source code is about 160 lines, and about 50 lines of the core code willgive you clear idea about how dRuby works internally.

class DRbObjectdef initialize(obj, uri=nil)

@uri = uri || DRb.uri@ref = obj.id if obj

enddef method_missing(msg_id, *a)

succ, result = DRbConn.new(@uri).send_message(self, msg_id, *a)raise result if ! succresult

end

attr :refend

DRbObject acts as a proxy object, so it doesn’t have any methods. Therefore,method_missing receives all the method calls and sends them to the DRbConn class.

class DRbConninclude DRbProtocol

def initialize(remote_uri)@host, @port = parse_uri(remote_uri)

enddef send_message(ref, msg_id, *arg)

beginsoc = TCPSocket.open(@host, @port)send_request(soc, ref, msg_id, *arg)recv_reply(soc)

ensuresoc.close if soc

endend

end

DRbConn acts as a TCPSocket server. It transfers the message to the remote server—sosimple. If you’re interested in the internals of dRuby, read the rest of the original codeto get a better idea about the structure of the library before jumping into reading thecurrent version of dRuby, which is more than 1,700 lines.

a. http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/15406

• Click HERE to purchase this book now. discuss

Design Principles of dRuby • 7

Page 7: The dRuby Bookmedia.pragprog.com/titles/sidruby/design.pdfPure Ruby dRuby is a distributed object system purely targeted to Ruby. It sounds lim-iting, but this also means you can run

In dRuby, objects are exchanged either by reference or by the copy of theoriginal value. When an object is passed by reference, the operation to theobject will affect the original (like a normal Ruby object). However, whenpassed by value, the operation doesn’t affect the original, and the changestays within the process where the object is modified (see Figure 12, Passingby reference and passing by value, on page 9).

This difference doesn’t exist in Ruby, and you have to pay special attentionto this when you program with dRuby.

If I really wanted to make dRuby look the same as Ruby, I could have designeddRuby to always pass by reference. However, remote object method invocationrequires some network overhead, and doing small object operations all viaRMI isn’t effective. It’s vital to pass the copy of the object in certain situationsto increase your application’s performance. Also, if you keep passing by refer-ence, you’ll never get the actual value from the remote server. Instead, you’llbe looping forever, trying to find out the object’s state.

It might sound a bit complicated, but don’t worry. You don’t have to specifywhether you plan to pass by value or by reference—dRuby does it for you.Because dRuby automatically selects the reference method, you don’t haveto write a special method for dRuby.

You’ll see more detail about automatically passing by value or by referencein Chapter 4, Pass by Reference, Pass by Value, on page ?.

8 •

• Click HERE to purchase this book now. discuss

Page 8: The dRuby Bookmedia.pragprog.com/titles/sidruby/design.pdfPure Ruby dRuby is a distributed object system purely targeted to Ruby. It sounds lim-iting, but this also means you can run

foofoo=(obj)dup

@fooFoo

foofoo=(obj)dup

@fooFoo

Pass by Reference

Pass by Value

foofoo=(obj)dup

@fooFoo

Reference informationLocation and id of original

CloneCopy of the originalNo impact on the original

To pass object "Foo"...

Figure 12—Passing by reference and passing by value

• Click HERE to purchase this book now. discuss

Design Principles of dRuby • 9