View Javadoc

1   package org.apache.helix;
2   /*
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   */
20  import java.net.InetAddress;
21  
22  import org.apache.commons.cli.CommandLine;
23  import org.apache.commons.cli.CommandLineParser;
24  import org.apache.commons.cli.GnuParser;
25  import org.apache.commons.cli.HelpFormatter;
26  import org.apache.commons.cli.Option;
27  import org.apache.commons.cli.OptionBuilder;
28  import org.apache.commons.cli.Options;
29  import org.apache.commons.cli.ParseException;
30  import org.apache.helix.tools.ClusterSetup;
31  import org.apache.log4j.Logger;
32  import org.restlet.Application;
33  import org.restlet.Component;
34  import org.restlet.Context;
35  import org.restlet.data.Request;
36  import org.restlet.Restlet;
37  import org.restlet.data.MediaType;
38  import org.restlet.data.Protocol;
39  import org.restlet.resource.StringRepresentation;
40  import org.restlet.Router;
41  
42  import org.restlet.data.Response;
43  
44  
45  public class MockEspressoService extends Application
46  {
47    private static final Logger logger = Logger.getLogger(MockEspressoService.class);
48  	
49    public static final String HELP = "help";
50    public static final String CLUSTERNAME = "clusterName";
51    public static final String INSTANCENAME = "instanceName";
52    public static final String ZKSERVERADDRESS = "zkSvr";
53    public static final String PORT = "port";
54    public static final int DEFAULT_PORT = 8100;
55    protected static final String NODE_TYPE = "EspressoStorage";
56    //protected static final String INSTANCE_NAME = "localhost_1234";
57    
58    public static final String DATABASENAME = "database";
59    public static final String TABLENAME = "table";
60    public static final String RESOURCENAME = "resource";
61    public static final String SUBRESOURCENAME = "subresource";
62    public static final String STOPSERVICECOMMAND = "stopservice";
63    
64    public static final String CONTEXT_MOCK_NODE_NAME = "mocknode";
65    public static final String COMPONENT_NAME = "component";
66    
67    Context _applicationContext;
68    static int _serverPort;
69    static String _zkAddr = "localhost:9999";
70    static String _instanceName = "localhost";
71    static String _clusterName = "";
72    public CMConnector _connector;
73    public EspressoStorageMockNode _mockNode;
74    static Context _context;
75    static Component _component;
76  
77    public MockEspressoService(Context context)
78    {
79  	  super(_context);
80  	  _connector = null;
81  
82  
83  	  try {
84  		  _connector = new CMConnector(_clusterName, _instanceName, _zkAddr); //, zkClient);
85  	  }
86  	  catch (Exception e) {
87  		  logger.error("Unable to initialize CMConnector: "+e);
88  		  e.printStackTrace();
89  		  System.exit(-1);
90  	  }
91  	  _mockNode = (EspressoStorageMockNode)MockNodeFactory.createMockNode(NODE_TYPE, _connector);
92  	  context.getAttributes().put(CONTEXT_MOCK_NODE_NAME, (Object)_mockNode);
93    }
94   
95    @Override
96    public Restlet createRoot()
97    {
98  	Router router = new Router(_context);
99  
100     Restlet mainpage = new Restlet()
101     {
102       @Override
103       public void handle(Request request, Response response)
104       {
105         StringBuilder stringBuilder = new StringBuilder();
106         stringBuilder.append("<html>");
107         stringBuilder
108             .append("<head><title>Restlet Cluster Management page</title></head>");
109         stringBuilder.append("<body bgcolor=white>");
110         stringBuilder.append("<table border=\"0\">");
111         stringBuilder.append("<tr>");
112         stringBuilder.append("<td>");
113         stringBuilder.append("<h1>Rest cluster management interface V1</h1>");
114         stringBuilder.append("</td>");
115         stringBuilder.append("</tr>");
116         stringBuilder.append("</table>");
117         stringBuilder.append("</body>");
118         stringBuilder.append("</html>");
119         response.setEntity(new StringRepresentation(stringBuilder.toString(),
120             MediaType.TEXT_HTML));
121       }
122     };
123     
124     if (_mockNode == null) {
125     	logger.debug("_mockNode in createRoot is null");
126     }
127     router.attach("", mainpage);
128     
129     //Espresso handlers
130     router.attach("/{"+DATABASENAME+"}/{"+TABLENAME+"}/{"+RESOURCENAME+"}", EspressoResource.class);
131     router.attach("/{"+DATABASENAME+"}/{"+TABLENAME+"}/{"+RESOURCENAME+"}/{"+SUBRESOURCENAME+"}", EspressoResource.class);
132     
133     //Admin handlers
134     router.attach("/{"+STOPSERVICECOMMAND+"}", StopServiceResource.class);
135     
136     return router;
137   }
138   
139   public static void printUsage(Options cliOptions)
140   {
141     HelpFormatter helpFormatter = new HelpFormatter();
142     helpFormatter.printHelp("java " + MockEspressoService.class.getName(), cliOptions);
143   }
144 
145   @SuppressWarnings("static-access")
146   private static Options constructCommandLineOptions()
147   {
148     Option helpOption = OptionBuilder.withLongOpt(HELP)
149         .withDescription("Prints command-line options info").create();
150     helpOption.setArgs(0);
151     helpOption.setRequired(false);
152     helpOption.setArgName("print help message");
153     
154     Option zkServerOption = OptionBuilder.withLongOpt(ZKSERVERADDRESS)
155         .withDescription("Provide zookeeper address").create();
156     zkServerOption.setArgs(1);
157     zkServerOption.setRequired(true);
158     zkServerOption.setArgName("ZookeeperServerAddress(Required)");
159     
160     Option clusterOption = OptionBuilder.withLongOpt(CLUSTERNAME)
161     		.withDescription("Provide cluster name").create();
162     clusterOption.setArgs(1);
163     clusterOption.setRequired(true);
164     clusterOption.setArgName("Cluster name(Required)");
165 
166     Option instanceOption = OptionBuilder.withLongOpt(INSTANCENAME)
167     		.withDescription("Provide name for this instance").create();
168     instanceOption.setArgs(1);
169     instanceOption.setRequired(false);
170     instanceOption.setArgName("Instance name(Optional, defaults to localhost)");
171 
172     Option portOption = OptionBuilder.withLongOpt(PORT)
173     .withDescription("Provide web service port").create();
174     portOption.setArgs(1);
175     portOption.setRequired(false);
176     portOption.setArgName("web service port, default: "+ DEFAULT_PORT);
177         
178     Options options = new Options();
179     options.addOption(helpOption);
180     options.addOption(zkServerOption);
181     options.addOption(clusterOption);
182     options.addOption(instanceOption);
183     options.addOption(portOption);
184     
185     return options;
186   }
187   
188   public static void processCommandLineArgs(String[] cliArgs) throws Exception
189   {
190     CommandLineParser cliParser = new GnuParser();
191     Options cliOptions = constructCommandLineOptions();
192     CommandLine cmd = null;
193 
194     try
195     {
196       cmd = cliParser.parse(cliOptions, cliArgs);
197     } 
198     catch (ParseException pe)
199     {
200       System.err.println("MockEspressoService: failed to parse command-line options: "
201           + pe.toString());
202       printUsage(cliOptions);
203       System.exit(1);
204     }
205     _serverPort = DEFAULT_PORT;
206     if(cmd.hasOption(HELP))
207     {
208       printUsage(cliOptions);
209       return;
210     }
211     else if(cmd.hasOption(PORT))
212     {
213       _serverPort = Integer.parseInt(cmd.getOptionValue(PORT));
214     }
215     if (cmd.hasOption(ZKSERVERADDRESS)) {
216     	_zkAddr = cmd.getOptionValue(ZKSERVERADDRESS);
217     }
218     if (cmd.hasOption(CLUSTERNAME)) {
219     	_clusterName = cmd.getOptionValue(CLUSTERNAME);
220     	logger.debug("_clusterName: "+_clusterName);
221     }
222     if (cmd.hasOption(INSTANCENAME)) {
223     	_instanceName = cmd.getOptionValue(INSTANCENAME);
224     	_instanceName = _instanceName.replace(':', '_');
225     	logger.debug("_instanceName: "+_instanceName);
226     }
227   }
228   
229   public void run() throws Exception {
230 	 
231 	  logger.debug("Start of mock service run");
232 	  
233 	
234 	  if (_mockNode == null) {
235 		  logger.debug("_mockNode null");
236 	  }
237 	  else {
238 		  logger.debug("_mockNode not null");
239 	  }
240 	  if (_mockNode != null) {
241 		  // start web server with the zkServer address
242 		  _component = new Component();
243 		  _component.getServers().add(Protocol.HTTP, _serverPort);
244 		  // Attach the application to the component and start it
245 		  _component.getDefaultHost().attach(this); //(application);
246 		  _context.getAttributes().put(COMPONENT_NAME, (Object)_component);
247 		 // _context.getParameters().set("maxTotalConnections", "16",true); 
248 		  _component.start();
249 		  //start mock espresso node
250 		  //!!!_mockNode.run();
251 	  }
252 	  else {
253 		  logger.error("Unknown MockNode type "+NODE_TYPE);
254 		  System.exit(-1);
255 	  }
256 	  logger.debug("mock service done");
257   }
258   
259   /**
260    * @param args
261    * @throws Exception
262    */
263   public static void main(String[] args) throws Exception
264   {
265 	  processCommandLineArgs(args);
266 	  _context = new Context();
267 	  MockEspressoService service = new MockEspressoService(_context);
268 	  service.run();
269 	  
270   }
271 }