Zookeeper Source analysis----node creation process

Source: Internet
Author: User
Tags zookeeper

Zookeeper as a C/S mode of application, the client is mainly processing (encapsulation) user requests, serialization, and then the socket to send to the server, the server to deserialize after the processing of client request data.

Here is the client's main code:

Zookeepermain: Handles some of the operations of the zookeeper command-line pattern, where some of the code that is created is as follows:

if (cmd.equals ("create") && args.length >= 3) {int-a = 0;
            Createmode flags = createmode.persistent; if ((Args[1].equals ("E") && args[2].equals ("-S") | |
                (Args[1]). Equals ("-S") && (Args[2].equals ("E"))) {first+=2;
            Flags = createmode.ephemeral_sequential;
                else if (args[1].equals ("E")) {first++;
            Flags = createmode.ephemeral;
                else if (args[1].equals ("s")) {first++;
            Flags = createmode.persistent_sequential;
            } if (args.length = = 4) {ACL = PARSEACLS (args[first+3]);
            Path = Args[first + 1];
            String NewPath = zk.create (path, args[first+2].getbytes (), ACL, flags);
        System.err.println ("Created" + NewPath); }
As you can see from the code, the Zookeeper commands only support lowercase when processing command line commands. After the create command is processed, the zookeeper (client-side used by Java programming) object is invoked to create the node, zookeeper the command to create the node into a createrequest (implementing the Record Interface) object. The object is then serialized to the service side (through the NIO client Clientcnxnsocketnio).

Service-Side code:

Zookeeperserver: Mainly handles client requests, where method Processpacket is to encapsulate request data (Bytebuffer) into the requested object with the following code:

Request SI = new request (CNXN, Cnxn.getsessionid (), H.getxid (),
                  H.gettype (), Incomingbuffer, Cnxn.getauthinfo ()); C1/>si.setowner (servercnxn.me);
                Submitrequest (SI);

The object is submitted to the Preprequestprocessor object, which is submitted to the queue submittedrequests:

public void ProcessRequest (Request request) {
        //Request.addrqrec (">prep=" +zks.outstandingchanges.size ());
        Submittedrequests.add (request);
    }
The object is instantiated as a stand-alone thread running, and the following is where the Run method is:

public void Run () {try {while (true) {Request request = Submittedrequests.take ();
                Long tracemask = Zootrace.client_request_trace_mask;
                if (Request.type = = opcode.ping) {tracemask = Zootrace.client_ping_trace_mask;
                } if (log.istraceenabled ()) {zootrace.logrequest (LOG, Tracemask, ' P ', Request, "");
                } if (Request.requestofdeath = = Request) {break;
            } prequest (Request);
        The catch (Interruptedexception e) {log.error ("unexpected Interruption", e); catch (Requestprocessorexception e) {if (E.getcause () instanceof xidrolloverexception) {LO
            G.info (E.getcause (). GetMessage ());
        } log.error ("Unexpected exception", e); The catch (Exception e) {log.error ("UnexpectEd exception ", E);
    } log.info ("Preprequestprocessor exited loop!"); }
prequest directly invoke methods <span style= "Font-family:arial, Helvetica, Sans-serif;" >prequest2txn,</span><span style= "font-family:arial, Helvetica, Sans-serif;" >PREQUEST2TXN part of the code is as follows </span><span style= "Font-family:arial, Helvetica, Sans-serif;" >:</span> 
Case Opcode.create:                             &NBS P
  Zks.sessionTracker.checkSession (Request.sessionid, Request.getowner ());                 createrequest createrequest = (createrequest) record;                    if (deserialize)           &N Bsp
        Bytebufferinputstream.bytebuffer2record (request.request, createrequest);
                String path = Createrequest.getpath ();
                int lastslash = Path.lastindexof ('/');                 if (Lastslash = 1 | | path.indexof (' ")!=-1 | | failcreate) {& nbsp                   log.info ("Invalid path" + Path + "with session 0x" + &nbs P     &NBsp
                    long.tohexstring (Request.sessionid);                     throw new Keeperexception.badargumentsexception (path
);                                 list<
acl> Listacl = RemoveDuplicates (Createrequest.getacl ());                 if (!fixupacl (Request.authinfo, Listacl)) {      & nbsp
            throw new keeperexception.invalidaclexception (path);                                 String p
Arentpath = path.substring (0, Lastslash);


                Changerecord Parentrecord = Getrecordforpath (Parentpath);                 Checkacl (Zks, ParentrEcord.acl, ZooDefs.Perms.CREATE,                         Reque
St.authinfo);
                int parentcversion = ParentRecord.stat.getCversion ();                 Createmode createmode =            
        Createmode.fromflag (Createrequest.getflags ());                 if (createmode.issequential ()) {        &NBSP ;
          Path = path + String.Format (locale.english, "%010d", parentcversion);                                 try {&N Bsp
                  Pathutils.validatepath (path);                /catch (IllegalArgumentException IE) {                    log.info ("Invalid path" + Path + "with session 0x" +   &NB Sp
                        long.tohexstring (Request.sessionid)                     throw new Keeperexception.badargumentsexception (path
);                                 try {&N Bsp                   if (Getrecordforpath (path)!= null) {     
                  throw new keeperexception.nodeexistsexception (path);                                   & nbsp catch (Keeperexception.nonodeexception e) {                   //IGN Ore this one
                                Boolean
Ephemeralparent = ParentRecord.stat.getEphemeralOwner ()!= 0;                 if (ephemeralparent) {            & nbsp
      throw new keeperexception.nochildrenforephemeralsexception (path);                                 int NEWC
Version = ParentRecord.stat.getCversion () +1;                 REQUEST.TXN = new Createtxn (path, Createrequest.getdata (),                         Listacl,           & nbsp
            createmode.isephemeral (), newcversion);
                statpersisted s = new statpersisted ();                 if (createmode.isephemeral ()) {          &NBSP ;
        S.setephemeralowner (Request.sessionid);                                 Parentre
Cord = parentrecord.duplicate (Request.hdr.getZxid ());
                parentrecord.childcount++;
                parentRecord.stat.setCversion (newcversion);
                Addchangerecord (Parentrecord);                 Addchangerecord (new Changerecord (REQUEST.HDR.GETZXID), path, S, & nbsp
                      0, Listacl)
                 break;

From the above methods, we can see that zookeeper for the sequential, ephemeral type node, especially the sequential type of node, for path processing is more obvious.

In addition, for ephemeral types of nodes, you can see closesession from the Datatree.createnode () method and the Preprequestprocessor.prequest2txn () method. When the session is closed, the data with the node type ephemeral is removed.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.