public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // path = /wifi/... //m_log.DebugFormat("[Wifi]: path = {0}", path); //m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint); //foreach (object o in httpRequest.Query.Keys) // m_log.DebugFormat(" >> {0}={1}", o, httpRequest.Query[o]); string resource = GetParam(path); //m_log.DebugFormat("[Wifi]: resource {0}", resource); resource = Uri.UnescapeDataString(resource).Trim(WebAppUtils.DirectorySeparatorChars); Request request = RequestFactory.CreateRequest(resource, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language"))); Environment env = new Environment(request); if (resource == string.Empty || resource.StartsWith("index.")) { if (m_WebApp.StatisticsUpdateInterval != TimeSpan.Zero) { m_WebApp.Services.ComputeStatistics(); } httpResponse.ContentType = "text/html"; return(WebAppUtils.StringToBytes(m_WebApp.Services.DefaultRequest(env))); } else { string resourcePath = System.IO.Path.Combine(WebApp.DocsPath, resource); string type = WebAppUtils.GetContentType(resource); httpResponse.ContentType = type; //m_log.DebugFormat("[Wifi]: ContentType {0}", type); if (type.StartsWith("image")) { return(WebAppUtils.ReadBinaryResource(resourcePath)); } if (type.StartsWith("application")) { string res = WebAppUtils.ReadTextResource(resourcePath, true); return(WebAppUtils.StringToBytes(res)); } if (type.StartsWith("text")) { if (m_WebApp.StatisticsUpdateInterval != TimeSpan.Zero) { m_WebApp.Services.ComputeStatistics(); } resourcePath = Localization.LocalizePath(env, resource); Processor p = new Processor(m_WebApp.WifiScriptFace, env); string res = p.Process(WebAppUtils.ReadTextResource(resourcePath)); if (res == string.Empty) { res = m_WebApp.Services.DefaultRequest(env); } return(WebAppUtils.StringToBytes(res)); } } httpResponse.ContentType = "text/plain"; string result = "Boo!"; return(WebAppUtils.StringToBytes(result)); }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // It's a POST, so we need to read the data on the stream, the lines after the blank line StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); httpResponse.ContentType = "text/html"; string resource = GetParam(path); //m_log.DebugFormat("[XXX]: query String: {0}; resource: {1}", body, resource); try { // Here the data on the stream is transformed into a nice dictionary of keys & values Dictionary <string, object> postdata = ServerUtils.ParseQueryString(body); Request req = RequestFactory.CreateRequest(resource, httpRequest); Diva.Wifi.Environment env = new Diva.Wifi.Environment(req); string result = string.Empty; if (resource.Equals("/") || resource.Equals(string.Empty)) { // The client invoked /wifi/admin/users/ string terms = String.Empty; if (postdata.ContainsKey("terms")) { terms = postdata["terms"].ToString(); } result = m_WebApp.Services.UserSearchPostRequest(env, terms); } else if (resource.StartsWith("/edit")) { // The client invoked /wifi/admin/users/edit, possibly with the UUID parameter after UUID userID = UUID.Zero; string[] pars = SplitParams(path); if ((pars.Length >= 2) && UUID.TryParse(pars[1], out userID)) { // Indeed the client invoked /wifi/admin/users/edit/<uuid>, and we got it already in userID (above) string form = string.Empty; if (postdata.ContainsKey("form")) { form = postdata["form"].ToString(); } if (form == "1") { string first = string.Empty, last = string.Empty, email = string.Empty, title = string.Empty; int level = 0, flags = 0; if (postdata.ContainsKey("first") && WebAppUtils.IsValidName(postdata["first"].ToString())) { first = postdata["first"].ToString(); } if (postdata.ContainsKey("last") && WebAppUtils.IsValidName(postdata["last"].ToString())) { last = postdata["last"].ToString(); } if (postdata.ContainsKey("email") && WebAppUtils.IsValidEmail(postdata["email"].ToString())) { email = postdata["email"].ToString(); } if (postdata.ContainsKey("title")) { title = postdata["title"].ToString(); } if (postdata.ContainsKey("level")) { Int32.TryParse(postdata["level"].ToString(), out level); } if (postdata.ContainsKey("flags")) { Int32.TryParse(postdata["flags"].ToString(), out flags); } result = m_WebApp.Services.UserEditPostRequest(env, userID, first, last, email, level, flags, title); } else if (form == "2") { string password = string.Empty; if (postdata.ContainsKey("password")) { password = postdata["password"].ToString(); result = m_WebApp.Services.UserEditPostRequest(env, userID, password); } } } } else if (resource.StartsWith("/delete")) { // The client invoked /wifi/admin/users/edit, possibly with the UUID parameter after UUID userID = UUID.Zero; string[] pars = SplitParams(path); if ((pars.Length >= 2) && UUID.TryParse(pars[1], out userID)) { // Indeed the client invoked /wifi/admin/users/edit/<uuid>, and we got it already in userID (above) string form = string.Empty; if (postdata.ContainsKey("form")) { form = postdata["form"].ToString(); } if (form == "1") { result = m_WebApp.Services.UserDeletePostRequest(env, userID); } } } return(WebAppUtils.StringToBytes(result)); } catch (Exception e) { m_log.DebugFormat("[USER ACCOUNT POST HANDLER]: Exception {0}", e); } return(WebAppUtils.FailureResult()); }
/// <exception cref="System.IO.IOException"/> protected override void DoGet(HttpServletRequest req, HttpServletResponse resp) { try { string userApprovedParamS = req.GetParameter(ProxyUriUtils.ProxyApprovalParam); bool userWasWarned = false; bool userApproved = Sharpen.Extensions.ValueOf(userApprovedParamS); bool securityEnabled = IsSecurityEnabled(); string remoteUser = req.GetRemoteUser(); string pathInfo = req.GetPathInfo(); string[] parts = pathInfo.Split("/", 3); if (parts.Length < 2) { Log.Warn("{} gave an invalid proxy path {}", remoteUser, pathInfo); NotFound(resp, "Your path appears to be formatted incorrectly."); return; } //parts[0] is empty because path info always starts with a / string appId = parts[1]; string rest = parts.Length > 2 ? parts[2] : string.Empty; ApplicationId id = Apps.ToAppID(appId); if (id == null) { Log.Warn("{} attempting to access {} that is invalid", remoteUser, appId); NotFound(resp, appId + " appears to be formatted incorrectly."); return; } if (securityEnabled) { string cookieName = GetCheckCookieName(id); Cookie[] cookies = req.GetCookies(); if (cookies != null) { foreach (Cookie c in cookies) { if (cookieName.Equals(c.GetName())) { userWasWarned = true; userApproved = userApproved || Sharpen.Extensions.ValueOf(c.GetValue()); break; } } } } bool checkUser = securityEnabled && (!userWasWarned || !userApproved); AppReportFetcher.FetchedAppReport fetchedAppReport = null; ApplicationReport applicationReport = null; try { fetchedAppReport = GetApplicationReport(id); if (fetchedAppReport != null) { if (fetchedAppReport.GetAppReportSource() != AppReportFetcher.AppReportSource.Rm && fetchedAppReport.GetAppReportSource() != AppReportFetcher.AppReportSource.Ahs) { throw new NotSupportedException("Application report not " + "fetched from RM or history server." ); } applicationReport = fetchedAppReport.GetApplicationReport(); } } catch (ApplicationNotFoundException) { applicationReport = null; } if (applicationReport == null) { Log.Warn("{} attempting to access {} that was not found", remoteUser, id); URI toFetch = ProxyUriUtils.GetUriFromTrackingPlugins(id, this.trackingUriPlugins ); if (toFetch != null) { ProxyUtils.SendRedirect(req, resp, toFetch.ToString()); return; } NotFound(resp, "Application " + appId + " could not be found " + "in RM or history server" ); return; } string original = applicationReport.GetOriginalTrackingUrl(); URI trackingUri; if (original == null || original.Equals("N/A") || original.Equals(string.Empty)) { if (fetchedAppReport.GetAppReportSource() == AppReportFetcher.AppReportSource.Rm) { // fallback to ResourceManager's app page if no tracking URI provided // and Application Report was fetched from RM Log.Debug("Original tracking url is '{}'. Redirecting to RM app page", original == null ? "NULL" : original); ProxyUtils.SendRedirect(req, resp, StringHelper.Pjoin(rmAppPageUrlBase, id.ToString ())); } else { if (fetchedAppReport.GetAppReportSource() == AppReportFetcher.AppReportSource.Ahs) { // fallback to Application History Server app page if the application // report was fetched from AHS Log.Debug("Original tracking url is '{}'. Redirecting to AHS app page", original == null ? "NULL" : original); ProxyUtils.SendRedirect(req, resp, StringHelper.Pjoin(ahsAppPageUrlBase, id.ToString ())); } } return; } else { if (ProxyUriUtils.GetSchemeFromUrl(original).IsEmpty()) { trackingUri = ProxyUriUtils.GetUriFromAMUrl(WebAppUtils.GetHttpSchemePrefix(conf) , original); } else { trackingUri = new URI(original); } } string runningUser = applicationReport.GetUser(); if (checkUser && !runningUser.Equals(remoteUser)) { Log.Info("Asking {} if they want to connect to the " + "app master GUI of {} owned by {}" , remoteUser, appId, runningUser); WarnUserPage(resp, ProxyUriUtils.GetPathAndQuery(id, rest, req.GetQueryString(), true), runningUser, id); return; } // Append the user-provided path and query parameter to the original // tracking url. IList <NameValuePair> queryPairs = URLEncodedUtils.Parse(req.GetQueryString(), null ); UriBuilder builder = UriBuilder.FromUri(trackingUri); foreach (NameValuePair pair in queryPairs) { builder.QueryParam(pair.GetName(), pair.GetValue()); } URI toFetch_1 = builder.Path(rest).Build(); Log.Info("{} is accessing unchecked {}" + " which is the app master GUI of {} owned by {}" , remoteUser, toFetch_1, appId, runningUser); switch (applicationReport.GetYarnApplicationState()) { case YarnApplicationState.Killed: case YarnApplicationState.Finished: case YarnApplicationState.Failed: { ProxyUtils.SendRedirect(req, resp, toFetch_1.ToString()); return; } default: { break; } } // fall out of the switch Cookie c_1 = null; if (userWasWarned && userApproved) { c_1 = MakeCheckCookie(id, true); } ProxyLink(req, resp, toFetch_1, c_1, GetProxyHost()); } catch (Exception e) { throw new IOException(e); } }
public string UserActivateGetRequest(Environment env, UUID userID) { m_log.DebugFormat("[Wifi]: UserActivateGetRequest {0}", userID); Request request = env.TheRequest; SessionInfo sinfo; if (TryGetSessionInfo(request, out sinfo) && (sinfo.Account.UserLevel >= m_WebApp.AdminUserLevel)) { env.Session = sinfo; env.Flags = Flags.IsLoggedIn | Flags.IsAdmin; NotifyWithoutButton(env, _("The account has been activated.", env)); UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, userID); if (account != null) { // Remove pending identifier in name account.FirstName = account.FirstName.Replace(m_PendingIdentifier, ""); // Retrieve saved user data from serviceURLs and set them back to normal string password = (string)account.ServiceURLs["Password"]; account.ServiceURLs.Remove("Password"); Object value; if (account.ServiceURLs.TryGetValue("Avatar", out value)) { account.ServiceURLs.Remove("Avatar"); } string avatarType = (string)value; CultureInfo[] languages = null; if (account.ServiceURLs.TryGetValue("Language", out value)) { languages = Localization.GetLanguageInfo((string)value); account.ServiceURLs.Remove("Language"); } // Save changes to user account m_UserAccountService.StoreUserAccount(account); // Create the inventory m_InventoryService.CreateUserInventory(account.PrincipalID); // Set the password m_AuthenticationService.SetPassword(account.PrincipalID, password); // Set the avatar if (avatarType != null) { SetAvatar(env, account.PrincipalID, avatarType); } if (!string.IsNullOrEmpty(account.Email)) { string message = string.Format("{0}\n\n{1} {2}\n{3} {4}\n\n{5} {6}", _("Your account has been activated.", languages), _("First name:", languages), account.FirstName, _("Last name:", languages), account.LastName, _("LoginURI:", languages), m_WebApp.LoginURL); SendEMail(account.Email, _("Account activated", languages), message); } } return(WebAppUtils.PadURLs(env, sinfo.Sid, m_WebApp.ReadFile(env, "index.html"))); } return(m_WebApp.ReadFile(env, "index.html")); }
private static ContainerReport ConvertToContainerReport(TimelineEntity entity, string serverHttpAddress, string user) { int allocatedMem = 0; int allocatedVcore = 0; string allocatedHost = null; int allocatedPort = -1; int allocatedPriority = 0; long createdTime = 0; long finishedTime = 0; string diagnosticsInfo = null; int exitStatus = ContainerExitStatus.Invalid; ContainerState state = null; string nodeHttpAddress = null; IDictionary <string, object> entityInfo = entity.GetOtherInfo(); if (entityInfo != null) { if (entityInfo.Contains(ContainerMetricsConstants.AllocatedMemoryEntityInfo)) { allocatedMem = (int)entityInfo[ContainerMetricsConstants.AllocatedMemoryEntityInfo ]; } if (entityInfo.Contains(ContainerMetricsConstants.AllocatedVcoreEntityInfo)) { allocatedVcore = (int)entityInfo[ContainerMetricsConstants.AllocatedVcoreEntityInfo ]; } if (entityInfo.Contains(ContainerMetricsConstants.AllocatedHostEntityInfo)) { allocatedHost = entityInfo[ContainerMetricsConstants.AllocatedHostEntityInfo].ToString (); } if (entityInfo.Contains(ContainerMetricsConstants.AllocatedPortEntityInfo)) { allocatedPort = (int)entityInfo[ContainerMetricsConstants.AllocatedPortEntityInfo ]; } if (entityInfo.Contains(ContainerMetricsConstants.AllocatedPriorityEntityInfo)) { allocatedPriority = (int)entityInfo[ContainerMetricsConstants.AllocatedPriorityEntityInfo ]; } if (entityInfo.Contains(ContainerMetricsConstants.AllocatedHostHttpAddressEntityInfo )) { nodeHttpAddress = (string)entityInfo[ContainerMetricsConstants.AllocatedHostHttpAddressEntityInfo ]; } } IList <TimelineEvent> events = entity.GetEvents(); if (events != null) { foreach (TimelineEvent @event in events) { if (@event.GetEventType().Equals(ContainerMetricsConstants.CreatedEventType)) { createdTime = @event.GetTimestamp(); } else { if (@event.GetEventType().Equals(ContainerMetricsConstants.FinishedEventType)) { finishedTime = @event.GetTimestamp(); IDictionary <string, object> eventInfo = @event.GetEventInfo(); if (eventInfo == null) { continue; } if (eventInfo.Contains(ContainerMetricsConstants.DiagnosticsInfoEventInfo)) { diagnosticsInfo = eventInfo[ContainerMetricsConstants.DiagnosticsInfoEventInfo].ToString (); } if (eventInfo.Contains(ContainerMetricsConstants.ExitStatusEventInfo)) { exitStatus = (int)eventInfo[ContainerMetricsConstants.ExitStatusEventInfo]; } if (eventInfo.Contains(ContainerMetricsConstants.StateEventInfo)) { state = ContainerState.ValueOf(eventInfo[ContainerMetricsConstants.StateEventInfo ].ToString()); } } } } } NodeId allocatedNode = NodeId.NewInstance(allocatedHost, allocatedPort); ContainerId containerId = ConverterUtils.ToContainerId(entity.GetEntityId()); string logUrl = WebAppUtils.GetAggregatedLogURL(serverHttpAddress, allocatedNode. ToString(), containerId.ToString(), containerId.ToString(), user); return(ContainerReport.NewInstance(ConverterUtils.ToContainerId(entity.GetEntityId ()), Resource.NewInstance(allocatedMem, allocatedVcore), NodeId.NewInstance(allocatedHost , allocatedPort), Priority.NewInstance(allocatedPriority), createdTime, finishedTime , diagnosticsInfo, logUrl, exitStatus, state, nodeHttpAddress)); }
/// <exception cref="System.Exception"/> protected override void ServiceStart() { try { Configuration conf = GetConfig(); HttpServer2.Builder b = new HttpServer2.Builder().SetName("proxy").AddEndpoint(URI .Create(WebAppUtils.GetHttpSchemePrefix(conf) + bindAddress + ":" + port)).SetFindPort (port == 0).SetConf(GetConfig()).SetACL(acl); if (YarnConfiguration.UseHttps(conf)) { WebAppUtils.LoadSslConfiguration(b); } proxyServer = b.Build(); proxyServer.AddServlet(ProxyUriUtils.ProxyServletName, ProxyUriUtils.ProxyPathSpec , typeof(WebAppProxyServlet)); proxyServer.SetAttribute(FetcherAttribute, fetcher); proxyServer.SetAttribute(IsSecurityEnabledAttribute, isSecurityEnabled); proxyServer.SetAttribute(ProxyHostAttribute, proxyHost); proxyServer.Start(); } catch (IOException e) { Log.Error("Could not start proxy web server", e); throw; } base.ServiceStart(); }
protected override void Render(HtmlBlock.Block html) { Hamlet.TBODY <Hamlet.TABLE <Org.Apache.Hadoop.Yarn.Webapp.Hamlet.Hamlet> > tbody = html .Table("#apps").Thead().Tr().Th(".id", "ID").Th(".user", "User").Th(".name", "Name" ).Th(".type", "Application Type").Th(".queue", "Queue").Th(".fairshare", "Fair Share" ).Th(".starttime", "StartTime").Th(".finishtime", "FinishTime").Th(".state", "State" ).Th(".finalstatus", "FinalStatus").Th(".progress", "Progress").Th(".ui", "Tracking UI" ).().().Tbody(); ICollection <YarnApplicationState> reqAppStates = null; string reqStateString = $(YarnWebParams.AppState); if (reqStateString != null && !reqStateString.IsEmpty()) { string[] appStateStrings = reqStateString.Split(","); reqAppStates = new HashSet <YarnApplicationState>(appStateStrings.Length); foreach (string stateString in appStateStrings) { reqAppStates.AddItem(YarnApplicationState.ValueOf(stateString)); } } StringBuilder appsTableData = new StringBuilder("[\n"); foreach (RMApp app in apps.Values) { if (reqAppStates != null && !reqAppStates.Contains(app.CreateApplicationState())) { continue; } AppInfo appInfo = new AppInfo(rm, app, true, WebAppUtils.GetHttpSchemePrefix(conf )); string percent = string.Format("%.1f", appInfo.GetProgress()); ApplicationAttemptId attemptId = app.GetCurrentAppAttempt().GetAppAttemptId(); int fairShare = fsinfo.GetAppFairShare(attemptId); if (fairShare == FairSchedulerInfo.InvalidFairShare) { // FairScheduler#applications don't have the entry. Skip it. continue; } appsTableData.Append("[\"<a href='").Append(Url("app", appInfo.GetAppId())).Append ("'>").Append(appInfo.GetAppId()).Append("</a>\",\"").Append(StringEscapeUtils.EscapeJavaScript (StringEscapeUtils.EscapeHtml(appInfo.GetUser()))).Append("\",\"").Append(StringEscapeUtils .EscapeJavaScript(StringEscapeUtils.EscapeHtml(appInfo.GetName()))).Append("\",\"" ).Append(StringEscapeUtils.EscapeJavaScript(StringEscapeUtils.EscapeHtml(appInfo .GetApplicationType()))).Append("\",\"").Append(StringEscapeUtils.EscapeJavaScript (StringEscapeUtils.EscapeHtml(appInfo.GetQueue()))).Append("\",\"").Append(fairShare ).Append("\",\"").Append(appInfo.GetStartTime()).Append("\",\"").Append(appInfo. GetFinishTime()).Append("\",\"").Append(appInfo.GetState()).Append("\",\"").Append (appInfo.GetFinalStatus()).Append("\",\"").Append("<br title='").Append(percent) .Append("'> <div class='").Append(JQueryUI.CProgressbar).Append("' title='").Append (StringHelper.Join(percent, '%')).Append("'> ").Append("<div class='").Append(JQueryUI .CProgressbarValue).Append("' style='").Append(StringHelper.Join("width:", percent , '%')).Append("'> </div> </div>").Append("\",\"<a href='"); // Progress bar string trackingURL = !appInfo.IsTrackingUrlReady() ? "#" : appInfo.GetTrackingUrlPretty (); appsTableData.Append(trackingURL).Append("'>").Append(appInfo.GetTrackingUI()).Append ("</a>\"],\n"); } if (appsTableData[appsTableData.Length - 2] == ',') { appsTableData.Delete(appsTableData.Length - 2, appsTableData.Length - 1); } appsTableData.Append("]"); html.Script().$type("text/javascript").("var appsTableData=" + appsTableData).(); tbody.().(); }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // It's a POST, so we need to read the data on the stream, the lines after the blank line StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); httpResponse.ContentType = "text/html"; string resource = GetParam(path); //m_log.DebugFormat("[XXX]: query String: {0}; resource: {1}", body, resource); try { // Here the data on the stream is transformed into a nice dictionary of keys & values Dictionary <string, object> postdata = ServerUtils.ParseQueryString(body); Request req = RequestFactory.CreateRequest(resource, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language"))); Environment env = new Environment(req); string result = string.Empty; if (resource.Equals("/") || resource.Equals(string.Empty)) { // The client invoked /wifi/admin/users/ string terms = String.Empty; if (postdata.ContainsKey("terms")) { terms = postdata["terms"].ToString(); } result = m_WebApp.Services.UserSearchPostRequest(env, terms); } else if (resource.StartsWith("/edit")) { // The client invoked /wifi/admin/groups/edit, possibly with the UUID parameter after UUID groupID = UUID.Zero; string[] pars = SplitParams(path); if ((pars.Length >= 2) && UUID.TryParse(pars[1], out groupID)) { // Indeed the client invoked /wifi/admin/groups/edit/<uuid>, and we got it already in userID (above) string name = string.Empty, charter = string.Empty; if (postdata.ContainsKey("name")) { name = postdata["name"].ToString(); } if (postdata.ContainsKey("charter")) { charter = postdata["charter"].ToString(); } result = m_WebApp.Services.GroupsEditPostRequest(env, groupID, name, charter); } } else if (resource.StartsWith("/delete")) { // The client invoked /wifi/admin/groups/edit, possibly with the UUID parameter after UUID groupID = UUID.Zero; string[] pars = SplitParams(path); if ((pars.Length >= 2) && UUID.TryParse(pars[1], out groupID)) { // Indeed the client invoked /wifi/admin/groups/edit/<uuid>, and we got it already in userID (above) string form = string.Empty; result = m_WebApp.Services.GroupsDeletePostRequest(env, groupID); } } return(WebAppUtils.StringToBytes(result)); } catch (Exception e) { m_log.DebugFormat("[USER ACCOUNT POST HANDLER]: Exception {0}", e); } return(WebAppUtils.FailureResult()); }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // path = /wifi/... //m_log.DebugFormat("[Wifi]: path = {0}", path); //m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint); //foreach (object o in httpRequest.Query.Keys) // m_log.DebugFormat(" >> {0}={1}", o, httpRequest.Query[o]); httpResponse.ContentType = "text/html"; string resource = GetParam(path); //m_log.DebugFormat("[INVENTORY HANDLER POST]: resource {0}", resource); Request request = RequestFactory.CreateRequest(string.Empty, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language"))); Environment env = new Environment(request); string result = string.Empty; if (resource.Equals("/") || resource.Equals(string.Empty)) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); Dictionary <string, object> postdata = ServerUtils.ParseQueryString(body); string action = postdata.Keys.FirstOrDefault(key => key.StartsWith("action-")); if (action == null) { action = string.Empty; } else { action = action.Substring("action-".Length); } string folder = string.Empty; string newFolderName = string.Empty; List <string> nodes = new List <string>(); List <string> types = new List <string>(); if (postdata.ContainsKey("folder")) { folder = postdata["folder"].ToString(); } if (postdata.ContainsKey("newFolderName")) { newFolderName = postdata["newFolderName"].ToString(); } foreach (KeyValuePair <string, object> kvp in postdata) { if (kvp.Key.StartsWith("inv-")) { nodes.Add(kvp.Key.Substring(4)); types.Add(kvp.Value.ToString()); } } result = m_WebApp.Services.InventoryPostRequest(env, action, folder, newFolderName, nodes, types); } else if (resource.StartsWith("/upload")) { HttpMultipartParser parser = new HttpMultipartParser(requestData, "datafile"); if (parser.Success) { //string user = HttpUtility.UrlDecode(parser.Parameters["user"]); if (!Directory.Exists(WebAppUtils.UploadPath)) { Directory.CreateDirectory(WebAppUtils.UploadPath); } string filename = new Guid().ToString().Substring(0, 8) + ".iar"; string pathToFile = System.IO.Path.Combine(WebAppUtils.UploadPath, filename); if (File.Exists(pathToFile)) { File.Delete(pathToFile); } using (FileStream w = new FileStream(pathToFile, FileMode.CreateNew)) { w.Write(parser.FileContents, 0, parser.FileContents.Length); } result = m_WebApp.Services.InventoryUploadRequest(env, pathToFile); File.Delete(pathToFile); } } return(WebAppUtils.StringToBytes(result)); }
public string TOSPostRequest(Environment env, string action, string userID, string sessionID) { if (!m_WebApp.IsInstalled) { m_log.DebugFormat("[Wifi]: warning: someone is trying to access InventoryPostRequest and Wifi isn't installed!"); return(m_WebApp.ReadFile(env, "index.html")); } m_log.DebugFormat("[Wifi]: TOSPostRequest {0} {1} {2}", action, userID, sessionID); Request request = env.TheRequest; SessionInfo sinfo; if (TryGetSessionInfo(request, out sinfo)) { env.Session = sinfo; if (action == "accept") { AcceptTOS(env, userID); if (sinfo.Account != null) { env.Flags = Flags.IsLoggedIn; } else { env.Flags = Flags.IsValidSession; } env.State = State.AcceptTOS; } else { TOSData d = new TOSData(); d.UserID = userID; d.SessionID = sinfo.Sid; List <object> loo = new List <object>(); loo.Add(d); env.Data = loo; if (sinfo.Account != null) { env.Flags = Flags.IsLoggedIn; } else { env.Flags = Flags.IsValidSession; } env.State = State.GetTOS; } if (sinfo.Account != null) { env.Flags = Flags.IsLoggedIn; } return(WebAppUtils.PadURLs(env, sinfo.Sid, m_WebApp.ReadFile(env, "index.html"))); } else { m_log.DebugFormat("[Wifi]: no session found"); return(m_WebApp.ReadFile(env, "index.html")); } }
/// <exception cref="System.Exception"/> protected override void ServiceStart() { lock (this) { this._enclosing.StartResourceManager(this.index); MiniYARNCluster.Log.Info("MiniYARN ResourceManager address: " + this.GetConfig(). Get(YarnConfiguration.RmAddress)); MiniYARNCluster.Log.Info("MiniYARN ResourceManager web address: " + WebAppUtils.GetRMWebAppURLWithoutScheme (this.GetConfig())); base.ServiceStart(); } }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // It's a POST, so we need to read the data on the stream, the lines after the blank line StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); httpResponse.ContentType = "text/html"; string resource = GetParam(path); //m_log.DebugFormat("[HYPERLINK POST HANDLER]: query String: {0}; resource: {1}", body, resource); try { // Here the data on the stream is transformed into a nice dictionary of keys & values Dictionary <string, object> postdata = ServerUtils.ParseQueryString(body); Request request = RequestFactory.CreateRequest(resource, httpRequest); Diva.Wifi.Environment env = new Diva.Wifi.Environment(request); string result = string.Empty; if (resource.StartsWith("/add")) { // The client invoked /wifi/linkregion/add string address = string.Empty; uint xloc = 0, yloc = 0; if (postdata.ContainsKey("address")) { address = postdata["address"].ToString(); } if (postdata.ContainsKey("xloc")) { UInt32.TryParse(postdata["xloc"].ToString(), out xloc); } if (postdata.ContainsKey("yloc")) { UInt32.TryParse(postdata["yloc"].ToString(), out yloc); } result = m_WebApp.Services.HyperlinkAddRequest(env, address, xloc, yloc); } else if (resource.StartsWith("/delete")) { // The client invoked /wifi/linkregion/delete, possibly with the UUID parameter after UUID regionID = UUID.Zero; string[] pars = SplitParams(path); if ((pars.Length >= 2) && UUID.TryParse(pars[1], out regionID)) { // Indeed the client invoked /wifi/linkregion/delete/<uuid>, and we got it already in regionID (above) result = m_WebApp.Services.HyperlinkDeletePostRequest(env, regionID); } } return(WebAppUtils.StringToBytes(result)); } catch (Exception e) { m_log.DebugFormat("[HYPERLINK POST HANDLER]: Exception {0}", e); } return(WebAppUtils.FailureResult()); }
public virtual WebApp Build(WebApp webapp) { if (webapp == null) { webapp = new _WebApp_171(); } // Defaults should be fine in usual cases webapp.SetName(name); webapp.SetWebServices(wsName); string basePath = "/" + name; webapp.SetRedirectPath(basePath); IList <string> pathList = new AList <string>(); if (basePath.Equals("/")) { webapp.AddServePathSpec("/*"); pathList.AddItem("/*"); } else { webapp.AddServePathSpec(basePath); webapp.AddServePathSpec(basePath + "/*"); pathList.AddItem(basePath + "/*"); } if (wsName != null && !wsName.Equals(basePath)) { if (wsName.Equals("/")) { webapp.AddServePathSpec("/*"); pathList.AddItem("/*"); } else { webapp.AddServePathSpec("/" + wsName); webapp.AddServePathSpec("/" + wsName + "/*"); pathList.AddItem("/" + wsName + "/*"); } } if (conf == null) { conf = new Configuration(); } try { if (application != null) { webapp.SetHostClass(application.GetType()); } else { string cls = InferHostClass(); Log.Debug("setting webapp host class to {}", cls); webapp.SetHostClass(Sharpen.Runtime.GetType(cls)); } if (devMode) { if (port > 0) { try { new Uri("http://localhost:" + port + "/__stop").GetContent(); Log.Info("stopping existing webapp instance"); Sharpen.Thread.Sleep(100); } catch (ConnectException e) { Log.Info("no existing webapp instance found: {}", e.ToString()); } catch (Exception e) { // should not be fatal Log.Warn("error stopping existing instance: {}", e.ToString()); } } else { Log.Error("dev mode does NOT work with ephemeral port!"); System.Environment.Exit(1); } } string httpScheme; if (this.httpPolicy == null) { httpScheme = WebAppUtils.GetHttpSchemePrefix(conf); } else { httpScheme = (httpPolicy == HttpConfig.Policy.HttpsOnly) ? WebAppUtils.HttpsPrefix : WebAppUtils.HttpPrefix; } HttpServer2.Builder builder = new HttpServer2.Builder().SetName(name).AddEndpoint (URI.Create(httpScheme + bindAddress + ":" + port)).SetConf(conf).SetFindPort(findPort ).SetACL(new AccessControlList(conf.Get(YarnConfiguration.YarnAdminAcl, YarnConfiguration .DefaultYarnAdminAcl))).SetPathSpec(Sharpen.Collections.ToArray(pathList, new string [0])); bool hasSpnegoConf = spnegoPrincipalKey != null && conf.Get(spnegoPrincipalKey) != null && spnegoKeytabKey != null && conf.Get(spnegoKeytabKey) != null; if (hasSpnegoConf) { builder.SetUsernameConfKey(spnegoPrincipalKey).SetKeytabConfKey(spnegoKeytabKey). SetSecurityEnabled(UserGroupInformation.IsSecurityEnabled()); } if (httpScheme.Equals(WebAppUtils.HttpsPrefix)) { WebAppUtils.LoadSslConfiguration(builder); } HttpServer2 server = builder.Build(); foreach (WebApps.Builder.ServletStruct @struct in servlets) { server.AddServlet(@struct.name, @struct.spec, @struct.clazz); } foreach (KeyValuePair <string, object> entry in attributes) { server.SetAttribute(entry.Key, entry.Value); } HttpServer2.DefineFilter(server.GetWebAppContext(), "guice", typeof(GuiceFilter). FullName, null, new string[] { "/*" }); webapp.SetConf(conf); webapp.SetHttpServer(server); } catch (TypeLoadException e) { throw new WebAppException("Error starting http server", e); } catch (IOException e) { throw new WebAppException("Error starting http server", e); } Injector injector = Guice.CreateInjector(webapp, new _AbstractModule_280(this)); Log.Info("Registered webapp guice modules"); // save a guice filter instance for webapp stop (mostly for unit tests) webapp.SetGuiceFilter(injector.GetInstance <GuiceFilter>()); if (devMode) { injector.GetInstance <Dispatcher>().SetDevMode(devMode); Log.Info("in dev mode!"); } return(webapp); }