Merge pull request #1769 from jow-/master
authorJo-Philipp Wich <jo@mein.io>
Fri, 18 May 2018 14:44:33 +0000 (16:44 +0200)
committerGitHub <noreply@github.com>
Fri, 18 May 2018 14:44:33 +0000 (16:44 +0200)
UCI apply/rollback workflow

17 files changed:
applications/luci-app-radicale/luasrc/view/radicale/tabmap_nsections.htm
modules/luci-base/luasrc/cbi.lua
modules/luci-base/luasrc/controller/admin/servicectl.lua [deleted file]
modules/luci-base/luasrc/dispatcher.lua
modules/luci-base/luasrc/model/uci.lua
modules/luci-base/luasrc/model/uci.luadoc
modules/luci-base/luasrc/view/cbi/apply_widget.htm [new file with mode: 0644]
modules/luci-base/luasrc/view/cbi/apply_xhr.htm [deleted file]
modules/luci-base/luasrc/view/cbi/map.htm
modules/luci-base/root/etc/config/luci
modules/luci-base/root/etc/init.d/ucitrack [new file with mode: 0755]
modules/luci-mod-admin-full/luasrc/controller/admin/uci.lua
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/wifi.lua
modules/luci-mod-admin-full/luasrc/view/admin_uci/apply.htm [deleted file]
modules/luci-mod-admin-full/luasrc/view/admin_uci/changes.htm
modules/luci-mod-admin-full/luasrc/view/admin_uci/revert.htm
modules/luci-mod-admin-full/luasrc/view/cbi/wireless_modefreq.htm

index 45fe60c..2b526a3 100644 (file)
@@ -2,12 +2,23 @@
        <div class="errorbox"><%=pcdata(msg)%></div>
 <%- end end -%>
 
-<%-+cbi/apply_xhr-%>
-
 <div class="cbi-map" id="cbi-<%=self.config%>">
        <% if self.title and #self.title > 0 then %><h2 name="content"><%=self.title%></h2><% end %>
        <% if self.description and #self.description > 0 then %><div class="cbi-map-descr"><%=self.description%></div><% end %>
-       <%- if firstmap and applymap then cbi_apply_xhr(self.config, parsechain, redirect) end -%>
+       <%- if firstmap and (applymap or confirmmap) then -%>
+               <%+cbi/apply_widget%>
+               <% cbi_apply_widget() %>
+               <div class="alert-message" id="cbi_apply_status" style="display:none"></div>
+               <script type="text/javascript">
+                       document.addEventListener("DOMContentLoaded", function() {
+                               <% if confirmmap then -%>
+                                       uci_confirm(true, Date.now() + <%=confirmmap%> * 1000);
+                               <%- else -%>
+                                       uci_apply(true);
+                               <%- end %>
+                       });
+               </script>
+       <%- end -%>
 
        <% if self.tabbed then %>
                <ul class="cbi-tabmenu map">
index 2184395..4728642 100644 (file)
@@ -388,21 +388,21 @@ function Map.parse(self, readinput, ...)
 
        if self.save then
                self:_run_hooks("on_save", "on_before_save")
+               local i, config
                for i, config in ipairs(self.parsechain) do
                        self.uci:save(config)
                end
                self:_run_hooks("on_after_save")
                if (not self.proceed and self.flow.autoapply) or luci.http.formvalue("cbi.apply") then
                        self:_run_hooks("on_before_commit")
-                       for i, config in ipairs(self.parsechain) do
-                               self.uci:commit(config)
-
-                               -- Refresh data because commit changes section names
-                               self.uci:load(config)
+                       if self.apply_on_parse == false then
+                               for i, config in ipairs(self.parsechain) do
+                                       self.uci:commit(config)
+                               end
                        end
                        self:_run_hooks("on_commit", "on_after_commit", "on_before_apply")
-                       if self.apply_on_parse then
-                               self.uci:apply(self.parsechain)
+                       if self.apply_on_parse == true or self.apply_on_parse == false then
+                               self.uci:apply(self.apply_on_parse)
                                self:_run_hooks("on_apply", "on_after_apply")
                        else
                                -- This is evaluated by the dispatcher and delegated to the
diff --git a/modules/luci-base/luasrc/controller/admin/servicectl.lua b/modules/luci-base/luasrc/controller/admin/servicectl.lua
deleted file mode 100644 (file)
index 1d73eb4..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
--- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org>
--- Licensed to the public under the Apache License 2.0.
-
-module("luci.controller.admin.servicectl", package.seeall)
-
-function index()
-       entry({"servicectl"}, alias("servicectl", "status")).sysauth = "root"
-       entry({"servicectl", "status"}, call("action_status")).leaf = true
-       entry({"servicectl", "restart"}, post("action_restart")).leaf = true
-end
-
-function action_status()
-       local data = nixio.fs.readfile("/var/run/luci-reload-status")
-       if data then
-               luci.http.write("/etc/config/")
-               luci.http.write(data)
-       else
-               luci.http.write("finish")
-       end
-end
-
-function action_restart(args)
-       local uci = require "luci.model.uci".cursor()
-       if args then
-               local service
-               local services = { }
-
-               for service in args:gmatch("[%w_-]+") do
-                       services[#services+1] = service
-               end
-
-               local command = uci:apply(services, true)
-               if nixio.fork() == 0 then
-                       local i = nixio.open("/dev/null", "r")
-                       local o = nixio.open("/dev/null", "w")
-
-                       nixio.dup(i, nixio.stdin)
-                       nixio.dup(o, nixio.stdout)
-
-                       i:close()
-                       o:close()
-
-                       nixio.exec("/bin/sh", unpack(command))
-               else
-                       luci.http.write("OK")
-                       os.exit(0)
-               end
-       end
-end
index 38932af..45e1e30 100644 (file)
@@ -182,6 +182,7 @@ local function session_retrieve(sid, allowed_users)
           (not allowed_users or
            util.contains(allowed_users, sdat.values.username))
        then
+               uci:set_session_id(sid)
                return sid, sdat.values
        end
 
@@ -884,6 +885,8 @@ local function _cbi(self, ...)
        local pageaction = true
        local parsechain = { }
 
+       local is_rollback, time_remaining = uci:rollback_pending()
+
        for i, res in ipairs(maps) do
                if res.apply_needed and res.parsechain then
                        local c
@@ -911,6 +914,7 @@ local function _cbi(self, ...)
                res:render({
                        firstmap   = (i == 1),
                        applymap   = applymap,
+                       confirmmap = (is_rollback and time_remaining or nil),
                        redirect   = redirect,
                        messages   = messages,
                        pageaction = pageaction,
index fc2a605..34323f0 100644 (file)
@@ -3,6 +3,7 @@
 
 local os    = require "os"
 local util  = require "luci.util"
+local conf  = require "luci.config"
 local table = require "table"
 
 
@@ -143,22 +144,84 @@ function commit(self, config)
        return (err == nil), ERRSTR[err]
 end
 
---[[
-function apply(self, configs, command)
-       local _, config
+function apply(self, rollback)
+       local _, err
+
+       if rollback then
+               local timeout = tonumber(conf.apply and conf.apply.rollback or "") or 0
 
-       assert(not command, "Apply command not supported anymore")
+               _, err = call("apply", {
+                       timeout  = (timeout > 30) and timeout or 30,
+                       rollback = true
+               })
 
-       if type(configs) == "table" then
-               for _, config in ipairs(configs) do
-                       call("service", "event", {
-                               type = "config.change",
-                               data = { package = config }
+               if not err then
+                       util.ubus("session", "set", {
+                               ubus_rpc_session = session_id,
+                               values = { rollback = os.time() + timeout }
                        })
                end
+       else
+               _, err = call("changes", {})
+
+               if not err then
+                       if type(_) == "table" and type(_.changes) == "table" then
+                               local k, v
+                               for k, v in pairs(_.changes) do
+                                       _, err = call("commit", { config = k })
+                                       if err then
+                                               break
+                                       end
+                               end
+                       end
+               end
+
+               if not err then
+                       _, err = call("apply", { rollback = false })
+               end
+       end
+
+       return (err == nil), ERRSTR[err]
+end
+
+function confirm(self)
+       local _, err = call("confirm", {})
+       if not err then
+               util.ubus("session", "set", {
+                       ubus_rpc_session = session_id,
+                       values = { rollback = 0 }
+               })
        end
+       return (err == nil), ERRSTR[err]
+end
+
+function rollback(self)
+       local _, err = call("rollback", {})
+       if not err then
+               util.ubus("session", "set", {
+                       ubus_rpc_session = session_id,
+                       values = { rollback = 0 }
+               })
+       end
+       return (err == nil), ERRSTR[err]
+end
+
+function rollback_pending(self)
+       local deadline, err = util.ubus("session", "get", {
+               ubus_rpc_session = session_id,
+               keys = { "rollback" }
+       })
+
+       if type(deadline) == "table" and
+          type(deadline.values) == "table" and
+          type(deadline.values.rollback) == "number" and
+          deadline.values.rollback > os.time()
+       then
+               return true, deadline.values.rollback - os.time()
+       end
+
+       return false, ERRSTR[err]
 end
-]]
 
 
 function foreach(self, config, stype, callback)
@@ -425,59 +488,3 @@ function delete_all(self, config, stype, comparator)
 
        return (err == nil), ERRSTR[err]
 end
-
-
-function apply(self, configlist, command)
-       configlist = self:_affected(configlist)
-       if command then
-               return { "/sbin/luci-reload", unpack(configlist) }
-       else
-               return os.execute("/sbin/luci-reload %s >/dev/null 2>&1"
-                       % util.shellquote(table.concat(configlist, " ")))
-       end
-end
-
--- Return a list of initscripts affected by configuration changes.
-function _affected(self, configlist)
-       configlist = type(configlist) == "table" and configlist or { configlist }
-
-       -- Resolve dependencies
-       local reloadlist = { }
-
-       local function _resolve_deps(name)
-               local reload = { name }
-               local deps = { }
-
-               self:foreach("ucitrack", name,
-                       function(section)
-                               if section.affects then
-                                       for i, aff in ipairs(section.affects) do
-                                               deps[#deps+1] = aff
-                                       end
-                               end
-                       end)
-
-               local i, dep
-               for i, dep in ipairs(deps) do
-                       local j, add
-                       for j, add in ipairs(_resolve_deps(dep)) do
-                               reload[#reload+1] = add
-                       end
-               end
-
-               return reload
-       end
-
-       -- Collect initscripts
-       local j, config
-       for j, config in ipairs(configlist) do
-               local i, e
-               for i, e in ipairs(_resolve_deps(config)) do
-                       if not util.contains(reloadlist, e) then
-                               reloadlist[#reloadlist+1] = e
-                       end
-               end
-       end
-
-       return reloadlist
-end
index ef89d09..d798b00 100644 (file)
@@ -28,12 +28,63 @@ Create a new Cursor initialized to the state directory.
 ]]
 
 ---[[
-Applies UCI configuration changes
+Applies UCI configuration changes.
+
+If the rollback parameter is set to true, the apply function will invoke the
+rollback mechanism which causes the configuration to be automatically reverted
+if no confirm() call occurs within a certain timeout.
+
+The current default timeout is 30s and can be increased using the
+"luci.apply.timeout" uci configuration key.
 
 @class                         function
 @name                          Cursor.apply
-@param configlist      List of UCI configurations
-@param command         Don't apply only return the command
+@param rollback                Enable rollback mechanism
+@return                                Boolean whether operation succeeded
+]]
+
+---[[
+Confirms UCI apply process.
+
+If a previous UCI apply with rollback has been invoked using apply(true),
+this function confirms the process and cancels the pending rollback timer.
+
+If no apply with rollback session is active, the function has no effect and
+returns with a "No data" error.
+
+@class                         function
+@name                          Cursor.confirm
+@return                                Boolean whether operation succeeded
+]]
+
+---[[
+Cancels UCI apply process.
+
+If a previous UCI apply with rollback has been invoked using apply(true),
+this function cancels the process and rolls back the configuration to the
+pre-apply state.
+
+If no apply with rollback session is active, the function has no effect and
+returns with a "No data" error.
+
+@class                         function
+@name                          Cursor.rollback
+@return                                Boolean whether operation succeeded
+]]
+
+---[[
+Checks whether a pending rollback is scheduled.
+
+If a previous UCI apply with rollback has been invoked using apply(true),
+and has not been confirmed or rolled back yet, this function returns true
+and the remaining time until rollback in seconds. If no rollback is pending,
+the function returns false. On error, the function returns false and an
+additional string describing the error.
+
+@class                         function
+@name                          Cursor.rollback_pending
+@return                                Boolean whether rollback is pending
+@return                                Remaining time in seconds
 ]]
 
 ---[[
diff --git a/modules/luci-base/luasrc/view/cbi/apply_widget.htm b/modules/luci-base/luasrc/view/cbi/apply_widget.htm
new file mode 100644 (file)
index 0000000..543ef0b
--- /dev/null
@@ -0,0 +1,181 @@
+<% export("cbi_apply_widget", function(redirect_ok) -%>
+<style type="text/css">
+       #cbi_apply_status {
+               display: flex;
+               flex-wrap: wrap;
+               min-height: 32px;
+               align-items: center;
+               margin: 1.5em 0 1.5em 0;
+       }
+
+       #cbi_apply_status > h4,
+       #cbi_apply_status > p,
+       #cbi_apply_status > div {
+               flex-basis: 100%;
+       }
+
+       #cbi_apply_status > img {
+               margin-right: 1em;
+               flex-basis: 32px;
+       }
+
+       #cbi_apply_status + script + .cbi-section {
+               margin-top: -1em;
+       }
+
+       .alert-message.notice {
+               background: linear-gradient(#fff 0%, #eee 100%);
+       }
+</style>
+
+<script type="text/javascript" src="<%=resource%>/cbi.js"></script>
+<script type="text/javascript">//<![CDATA[
+       var xhr = new XHR(),
+           stat, indicator,
+           uci_apply_auth = { sid: '<%=luci.dispatcher.context.authsession%>', token: '<%=token%>' },
+           uci_apply_rollback = <%=math.max(luci.config and luci.config.apply and luci.config.apply.rollback or 30, 30)%>,
+           uci_apply_holdoff = <%=math.max(luci.config and luci.config.apply and luci.config.apply.holdoff or 4, 1)%>,
+           uci_apply_timeout = <%=math.max(luci.config and luci.config.apply and luci.config.apply.timeout or 5, 1)%>,
+           uci_apply_display = <%=math.max(luci.config and luci.config.apply and luci.config.apply.display or 1.5, 1)%>;
+
+       function uci_rollback(checked) {
+               if (checked) {
+                       stat.classList.remove('notice');
+                       stat.classList.add('warning');
+                       stat.innerHTML = '<img src="<%=resource%>/icons/loading.gif" alt="" style="vertical-align:middle" /> ' +
+                                        '<%:Failed to confirm apply within %ds, waiting for rollback…%>'.format(uci_apply_rollback);
+
+                       var call = function(r) {
+                               if (r.status === 204) {
+                                       stat.innerHTML = '<h4><%:Configuration has been rolled back!%></h4>' +
+                                               '<p><%:The device could not be reached within %d seconds after applying the pending changes, which caused the configuration to be rolled back for safety reasons. If you believe that the configuration changes are correct nonetheless, perform an unchecked configuration apply. Alternatively, you can dismiss this warning and edit changes before attempting to apply again, or revert all pending changes to keep the currently working configuration state.%></p>'.format(uci_apply_rollback) +
+                                               '<div class="right">' +
+                                                       '<input type="button" class="btn" onclick="this.parentNode.parentNode.style.display=\'none\'" value="<%:Dismiss%>" /> ' +
+                                                       '<input type="button" class="btn" onclick="uci_revert()" value="<%:Revert changes%>" /> ' +
+                                                       '<input type="button" class="btn danger" onclick="uci_apply(false)" value="<%:Apply unchecked%>" />' +
+                                               '</div>';
+
+                                       return;
+                               }
+
+                               xhr.post('<%=url("admin/uci/confirm")%>', uci_apply_auth, call, uci_apply_timeout * 1000);
+                       };
+
+                       call({ status: 0 });
+               }
+               else {
+                       stat.classList.remove('notice');
+                       stat.classList.add('warning');
+                       stat.innerHTML = '<h4><%:Device unreachable!%></h4>' +
+                               '<p><%:Could not regain access to the device after applying the configuration changes. You might need to reconnect if you modified network related settings such as the IP address or wireless security credentials.%></p>';
+               }
+       }
+
+       function uci_confirm(checked, deadline) {
+               var tt;
+               var ts = Date.now();
+
+               stat = document.getElementById('cbi_apply_status');
+               stat.style.display = '';
+               stat.classList.remove('warning');
+               stat.classList.add('notice');
+
+               indicator = document.querySelector('.uci_change_indicator');
+
+               var call = function(r) {
+                       if (Date.now() >= deadline) {
+                               uci_rollback(checked);
+                               return;
+                       }
+                       else if (r && (r.status === 200 || r.status === 204)) {
+                               if (indicator)
+                                       indicator.style.display = 'none';
+
+                               stat.innerHTML = '<%:Configuration has been applied.%>';
+
+                               window.clearTimeout(tt);
+                               window.setTimeout(function() {
+                                       stat.style.display = 'none';
+                                       <% if redirect_ok then %>location.href = decodeURIComponent('<%=luci.util.urlencode(redirect_ok)%>');<% end %>
+                               }, uci_apply_display * 1000);
+
+                               return;
+                       }
+
+                       xhr.post('<%=url("admin/uci/confirm")%>', uci_apply_auth, call, uci_apply_timeout * 1000);
+               };
+
+               var tick = function() {
+                       var now = Date.now();
+
+                       stat.innerHTML = '<img src="<%=resource%>/icons/loading.gif" alt="" style="vertical-align:middle" /> ' +
+                                        '<%:Waiting for configuration to get applied… %ds%>'.format(Math.max(Math.floor((deadline - Date.now()) / 1000), 0));
+
+                       if (now >= deadline)
+                               return;
+
+                       tt = window.setTimeout(tick, 1000 - (now - ts));
+                       ts = now;
+               };
+
+               tick();
+
+               /* wait a few seconds for the settings to become effective */
+               window.setTimeout(call, Math.max(uci_apply_holdoff * 1000 - ((ts + uci_apply_rollback * 1000) - deadline), 1));
+       }
+
+       function uci_apply(checked) {
+               stat = document.getElementById('cbi_apply_status');
+               stat.style.display = '';
+               stat.classList.remove('warning');
+               stat.classList.add('notice');
+               stat.innerHTML = '<img src="<%=resource%>/icons/loading.gif" alt="" style="vertical-align:middle" /> ' +
+                                '<%:Starting configuration apply…%>';
+
+               xhr.post('<%=url("admin/uci")%>/' + (checked ? 'apply_rollback' : 'apply_unchecked'), uci_apply_auth, function(r) {
+                       if (r.status === (checked ? 200 : 204)) {
+                               uci_confirm(checked, Date.now() + uci_apply_rollback * 1000);
+                       }
+                       else if (checked && r.status === 204) {
+                               stat.innerHTML = '<%:There are no changes to apply.%>';
+                               window.setTimeout(function() {
+                                       stat.style.display = 'none';
+                                       <% if redirect_ok then %>location.href = decodeURIComponent('<%=luci.util.urlencode(redirect_ok)%>');<% end %>
+                               }, uci_apply_display * 1000);
+                       }
+                       else {
+                               stat.classList.add('warning');
+                               stat.classList.remove('notice');
+                               stat.innerHTML = '<%_Apply request failed with status <code>%h</code>%>'.format(r.responseText || r.statusText || r.status);
+                       }
+               });
+       }
+
+       function uci_revert() {
+               stat = document.getElementById('cbi_apply_status');
+               stat.style.display = '';
+               stat.classList.remove('warning');
+               stat.classList.add('notice');
+               stat.innerHTML = '<img src="<%=resource%>/icons/loading.gif" alt="" style="vertical-align:middle" /> ' +
+                                '<%:Reverting configuration…%>';
+
+               xhr.post('<%=url("admin/uci/revert")%>', uci_apply_auth, function(r) {
+                       if (r.status === 200) {
+                               stat.innerHTML = '<%:Changes have been reverted.%>';
+                               window.setTimeout(function() {
+                                       <% if redirect_ok then -%>
+                                               location.href = decodeURIComponent('<%=luci.util.urlencode(redirect_ok)%>');
+                                       <%- else -%>
+                                               window.location = window.location.href.split('#')[0];
+                                       <%- end %>
+                               }, uci_apply_display * 1000);
+                       }
+                       else {
+                               stat.classList.add('warning');
+                               stat.classList.remove('notice');
+                               stat.innerHTML = '<%_Revert request failed with status <code>%h</code>%>'.format(r.statusText || r.status);
+                       }
+               });
+       }
+//]]></script>
+<%-    end) %>
diff --git a/modules/luci-base/luasrc/view/cbi/apply_xhr.htm b/modules/luci-base/luasrc/view/cbi/apply_xhr.htm
deleted file mode 100644 (file)
index daa57c1..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-<% export("cbi_apply_xhr", function(id, configs, redirect) -%>
-<fieldset class="cbi-section" id="cbi-apply-<%=id%>">
-       <legend><%:Applying changes%></legend>
-       <script type="text/javascript">//<![CDATA[
-               var apply_xhr = new XHR();
-
-               apply_xhr.post('<%=url('servicectl/restart', table.concat(configs, ","))%>', { token: '<%=token%>' },
-                       function() {
-                               var checkfinish = function() {
-                                       apply_xhr.get('<%=url('servicectl/status')%>', null,
-                                               function(x) {
-                                                       if( x.responseText == 'finish' )
-                                                       {
-                                                               var e = document.getElementById('cbi-apply-<%=id%>-status');
-                                                               if( e )
-                                                               {
-                                                                       e.innerHTML = '<%:Configuration applied.%>';
-                                                                       window.setTimeout(function() {
-                                                                               e.parentNode.style.display = 'none';
-                                                                               <% if redirect then %>location.href='<%=redirect%>';<% end %>
-                                                                       }, 1000);
-                                                               }
-                                                       }
-                                                       else
-                                                       {
-                                                               var e = document.getElementById('cbi-apply-<%=id%>-status');
-                                                               if( e && x.responseText ) e.innerHTML = x.responseText;
-
-                                                               window.setTimeout(checkfinish, 1000);
-                                                       }
-                                               }
-                                       );
-                               }
-
-                               window.setTimeout(checkfinish, 1000);
-                       }
-               );
-       //]]></script>
-
-       <img src="<%=resource%>/icons/loading.gif" alt="<%:Loading%>" style="vertical-align:middle" />
-       <span id="cbi-apply-<%=id%>-status"><%:Waiting for changes to be applied...%></span>
-</fieldset>
-<%-    end) %>
index e3210ad..69ef361 100644 (file)
@@ -2,12 +2,23 @@
        <div class="errorbox"><%=pcdata(msg)%></div>
 <%- end end -%>
 
-<%-+cbi/apply_xhr-%>
-
 <div class="cbi-map" id="cbi-<%=self.config%>">
        <% if self.title and #self.title > 0 then %><h2 name="content"><%=self.title%></h2><% end %>
        <% if self.description and #self.description > 0 then %><div class="cbi-map-descr"><%=self.description%></div><% end %>
-       <%- if firstmap and applymap then cbi_apply_xhr(self.config, parsechain, redirect) end -%>
+       <%- if firstmap and (applymap or confirmmap) then -%>
+               <%+cbi/apply_widget%>
+               <% cbi_apply_widget(redirect) %>
+               <div class="alert-message" id="cbi_apply_status" style="display:none"></div>
+               <script type="text/javascript">
+                       document.addEventListener("DOMContentLoaded", function() {
+                               <% if confirmmap then -%>
+                                       uci_confirm(true, Date.now() + <%=confirmmap%> * 1000);
+                               <%- else -%>
+                                       uci_apply(true);
+                               <%- end %>
+                       });
+               </script>
+       <%- end -%>
 
        <% if self.tabbed then %>
                <ul class="cbi-tabmenu map">
index baa3ac5..82c2230 100644 (file)
@@ -22,3 +22,9 @@ config internal ccache
        option enable 1
                
 config internal themes
+
+config internal apply
+       option rollback 30
+       option holdoff 4
+       option timeout 5
+       option display 1.5
diff --git a/modules/luci-base/root/etc/init.d/ucitrack b/modules/luci-base/root/etc/init.d/ucitrack
new file mode 100755 (executable)
index 0000000..27d34fa
--- /dev/null
@@ -0,0 +1,57 @@
+#!/bin/sh /etc/rc.common
+
+START=80
+USE_PROCD=1
+
+register_init() {
+       local config="$1"
+       local init="$2"
+       shift; shift
+
+       if [ -x "$init" ] && "$init" enabled && ! grep -sqE 'USE_PROCD=.' "$init"; then
+               logger -t "ucitrack" "Setting up /etc/config/$config reload trigger for non-procd $init"
+               procd_add_config_trigger "config.change" "$config" "$init" "$@"
+       fi
+}
+
+register_trigger() {
+       local sid="$1"
+       local config init exec affects affected
+
+       config_get config "$sid" TYPE
+       config_get init "$sid" init
+       config_get exec "$sid" exec
+       config_get affects "$sid" affects
+
+       if [ -n "$init" ]; then
+               register_init "$config" "/etc/init.d/$init" "reload"
+       fi
+
+       if [ -n "$exec" ]; then
+               case "$exec" in
+                       /etc/init.d/*)
+                               set -- $exec
+                               register_init "$config" "$@"
+                       ;;
+                       *)
+                               logger -t "ucitrack" "Setting up non-init /etc/config/$config reload handler: $exec"
+                               procd_add_config_trigger "config.change" "$config" "$exec"
+                       ;;
+               esac
+       fi
+
+       for affected in $affects; do
+               logger -t "ucitrack" "Setting up /etc/config/$config reload dependency on /etc/config/$affected"
+               procd_add_config_trigger "config.change" "$affected" \
+                       ubus call service event \
+                       "$(printf '{"type":"config.change","data":{"package":"%s"}}' $config)"
+       done
+}
+
+service_triggers() {
+       config_foreach register_trigger
+}
+
+start_service() {
+       config_load ucitrack
+}
index ba317f9..9533ff5 100644 (file)
@@ -11,54 +11,91 @@ function index()
        entry({"admin", "uci"}, nil, _("Configuration"))
        entry({"admin", "uci", "changes"}, call("action_changes"), _("Changes"), 40).query = {redir=redir}
        entry({"admin", "uci", "revert"}, post("action_revert"), _("Revert"), 30).query = {redir=redir}
-       entry({"admin", "uci", "apply"}, post("action_apply"), _("Apply"), 20).query = {redir=redir}
-       entry({"admin", "uci", "saveapply"}, post("action_apply"), _("Save &#38; Apply"), 10).query = {redir=redir}
+
+       local node
+       local authen = function(checkpass, allowed_users)
+               return "root", luci.http.formvalue("sid")
+       end
+
+       node = entry({"admin", "uci", "apply_rollback"}, post("action_apply_rollback"), nil)
+       node.cors = true
+       node.sysauth_authenticator = authen
+
+       node = entry({"admin", "uci", "apply_unchecked"}, post("action_apply_unchecked"), nil)
+       node.cors = true
+       node.sysauth_authenticator = authen
+
+       node = entry({"admin", "uci", "confirm"}, post("action_confirm"), nil)
+       node.cors = true
+       node.sysauth_authenticator = authen
 end
 
+
 function action_changes()
-       local uci = luci.model.uci.cursor()
+       local uci  = require "luci.model.uci"
        local changes = uci:changes()
 
        luci.template.render("admin_uci/changes", {
-               changes = next(changes) and changes
+               changes  = next(changes) and changes,
+               timeout  = timeout
        })
 end
 
-function action_apply()
-       local path = luci.dispatcher.context.path
-       local uci = luci.model.uci.cursor()
+function action_revert()
+       local uci = require "luci.model.uci"
        local changes = uci:changes()
-       local reload = {}
 
-       -- Collect files to be applied and commit changes
+       -- Collect files to be reverted
+       local r, tbl
        for r, tbl in pairs(changes) do
-               table.insert(reload, r)
-               if path[#path] ~= "apply" then
-                       uci:load(r)
-                       uci:commit(r)
-                       uci:unload(r)
-               end
+               uci:revert(r)
        end
 
-       luci.template.render("admin_uci/apply", {
-               changes = next(changes) and changes,
-               configs = reload
+       luci.template.render("admin_uci/revert", {
+               changes = next(changes) and changes
        })
 end
 
 
-function action_revert()
-       local uci = luci.model.uci.cursor()
-       local changes = uci:changes()
+local function ubus_state_to_http(errstr)
+       local map = {
+               ["Invalid command"]   = 400,
+               ["Invalid argument"]  = 400,
+               ["Method not found"]  = 404,
+               ["Entry not found"]   = 404,
+               ["No data"]           = 204,
+               ["Permission denied"] = 403,
+               ["Timeout"]           = 504,
+               ["Not supported"]     = 500,
+               ["Unknown error"]     = 500,
+               ["Connection failed"] = 503
+       }
 
-       -- Collect files to be reverted
-       for r, tbl in pairs(changes) do
-               uci:load(r)
-               uci:revert(r)
-               uci:unload(r)
+       local code = map[errstr] or 200
+       local msg  = errstr      or "OK"
+
+       luci.http.status(code, msg)
+
+       if code ~= 204 then
+               luci.http.prepare_content("text/plain")
+               luci.http.write(msg)
        end
+end
 
-       luci.template.render("admin_uci/revert", {
-               changes = next(changes) and changes
-       })
+function action_apply_rollback()
+       local uci = require "luci.model.uci"
+       local _, errstr = uci:apply(true)
+       ubus_state_to_http(errstr)
+end
+
+function action_apply_unchecked()
+       local uci = require "luci.model.uci"
+       local _, errstr = uci:apply(false)
+       ubus_state_to_http(errstr)
+end
+
+function action_confirm()
+       local uci = require "luci.model.uci"
+       local _, errstr = uci:confirm()
+       ubus_state_to_http(errstr)
 end
index a574d35..a3e28fe 100644 (file)
@@ -7,6 +7,17 @@ local ut = require "luci.util"
 local nt = require "luci.sys".net
 local fs = require "nixio.fs"
 
+local acct_port, acct_secret, acct_server, anonymous_identity, ant1, ant2,
+       auth, auth_port, auth_secret, auth_server, bssid, cacert, cacert2,
+       cc, ch, cipher, clientcert, clientcert2, ea, eaptype, en, encr,
+       ft_protocol, ft_psk_generate_local, hidden, htmode, identity,
+       ieee80211r, ieee80211w, ifname, ifsection, isolate, key_retries,
+       legacyrates, max_timeout, meshfwd, meshid, ml, mobility_domain, mode,
+       mp, nasid, network, password, pmk_r1_push, privkey, privkey2, privkeypwd,
+       privkeypwd2, r0_key_lifetime, r0kh, r1_key_holder, r1kh,
+       reassociation_deadline, retry_timeout, ssid, st, tp, wepkey, wepslot,
+       wmm, wpakey, wps
+
 arg[1] = arg[1] or ""
 
 m = Map("wireless", "",
@@ -19,8 +30,6 @@ m:chain("network")
 m:chain("firewall")
 m.redirect = luci.dispatcher.build_url("admin/network/wireless")
 
-local ifsection
-
 function m.on_commit(map)
        local wnet = nw:get_wifinet(arg[1])
        if ifsection and wnet then
@@ -40,38 +49,6 @@ if not wnet or not wdev then
        return
 end
 
--- wireless toggle was requested, commit and reload page
-function m.parse(map)
-       local new_cc = m:formvalue("cbid.wireless.%s.country" % wdev:name())
-       local old_cc = m:get(wdev:name(), "country")
-
-       if m:formvalue("cbid.wireless.%s.__toggle" % wdev:name()) then
-               if wdev:get("disabled") == "1" or wnet:get("disabled") == "1" then
-                       wnet:set("disabled", nil)
-               else
-                       wnet:set("disabled", "1")
-               end
-               wdev:set("disabled", nil)
-
-               nw:commit("wireless")
-               luci.sys.call("(env -i /bin/ubus call network reload) >/dev/null 2>/dev/null")
-
-               luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless", arg[1]))
-               return
-       end
-
-       Map.parse(map)
-
-       if m:get(wdev:name(), "type") == "mac80211" and new_cc and new_cc ~= old_cc then
-               luci.sys.call("iw reg set %s" % ut.shellquote(new_cc))
-               luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless", arg[1]))
-               return
-       end
-end
-
-m.title = luci.util.pcdata(wnet:get_i18n())
-
-
 local function txpower_list(iw)
        local list = iw.txpwrlist or { }
        local off  = tonumber(iw.txpower_offset) or 0
@@ -112,6 +89,57 @@ local hw_modes      = iw.hwmodelist or { }
 local tx_power_list = txpower_list(iw)
 local tx_power_cur  = txpower_current(wdev:get("txpower"), tx_power_list)
 
+-- wireless toggle was requested, commit and reload page
+function m.parse(map)
+       local new_cc = m:formvalue("cbid.wireless.%s.country" % wdev:name())
+       local old_cc = m:get(wdev:name(), "country")
+
+       if m:formvalue("cbid.wireless.%s.__toggle" % wdev:name()) then
+               if wdev:get("disabled") == "1" or wnet:get("disabled") == "1" then
+                       wnet:set("disabled", nil)
+               else
+                       wnet:set("disabled", "1")
+               end
+               wdev:set("disabled", nil)
+               m.apply_needed = true
+               m.redirect = nil
+       end
+
+       Map.parse(map)
+
+       if m:get(wdev:name(), "type") == "mac80211" and new_cc and new_cc ~= old_cc then
+               luci.sys.call("iw reg set %s" % ut.shellquote(new_cc))
+
+               local old_ch = tonumber(m:formvalue("cbid.wireless.%s._mode_freq.channel" % wdev:name()) or "")
+               if old_ch then
+                       local _, c, new_ch
+                       for _, c in ipairs(iw.freqlist) do
+                               if c.channel > old_ch or (old_ch <= 14 and c.channel > 14) then
+                                       break
+                               end
+                               new_ch = c.channel
+                       end
+                       if new_ch ~= old_ch then
+                               wdev:set("channel", new_ch)
+                               m.message = translatef("Channel %d is not available in the %s regulatory domain and has been auto-adjusted to %d.",
+                                       old_ch, new_cc, new_ch)
+                       end
+               end
+       end
+
+       if wdev:get("disabled") == "1" or wnet:get("disabled") == "1" then
+               en.title      = translate("Wireless network is disabled")
+               en.inputtitle = translate("Enable")
+               en.inputstyle = "apply"
+       else
+               en.title      = translate("Wireless network is enabled")
+               en.inputtitle = translate("Disable")
+               en.inputstyle = "reset"
+       end
+end
+
+m.title = luci.util.pcdata(wnet:get_i18n())
+
 s = m:section(NamedSection, wdev:name(), "wifi-device", translate("Device Configuration"))
 s.addremove = false
 
@@ -119,29 +147,12 @@ s:tab("general", translate("General Setup"))
 s:tab("macfilter", translate("MAC-Filter"))
 s:tab("advanced", translate("Advanced Settings"))
 
---[[
-back = s:option(DummyValue, "_overview", translate("Overview"))
-back.value = ""
-back.titleref = luci.dispatcher.build_url("admin", "network", "wireless")
-]]
-
 st = s:taboption("general", DummyValue, "__status", translate("Status"))
 st.template = "admin_network/wifi_status"
 st.ifname   = arg[1]
 
 en = s:taboption("general", Button, "__toggle")
 
-if wdev:get("disabled") == "1" or wnet:get("disabled") == "1" then
-       en.title      = translate("Wireless network is disabled")
-       en.inputtitle = translate("Enable")
-       en.inputstyle = "apply"
-else
-       en.title      = translate("Wireless network is enabled")
-       en.inputtitle = translate("Disable")
-       en.inputstyle = "reset"
-end
-
-
 local hwtype = wdev:get("type")
 
 -- NanoFoo
@@ -170,9 +181,7 @@ if found_sta then
                found_sta.channel or "(auto)", table.concat(found_sta.names, ", "))
 else
        ch = s:taboption("general", Value, "_mode_freq", '<br />'..translate("Operating frequency"))
-       ch.hwmodes = hw_modes
-       ch.htmodes = iw.htmodelist
-       ch.freqlist = iw.freqlist
+       ch.iwinfo = iw
        ch.template = "cbi/wireless_modefreq"
 
        function ch.cfgvalue(self, section)
@@ -1049,7 +1058,7 @@ if hwtype == "mac80211" then
                retry_timeout.rmempty = true
        end
 
-       local key_retries = s:taboption("encryption", Flag, "wpa_disable_eapol_key_retries",
+       key_retries = s:taboption("encryption", Flag, "wpa_disable_eapol_key_retries",
                translate("Enable key reinstallation (KRACK) countermeasures"),
                translate("Complicates key reinstallation attacks on the client side by disabling retransmission of EAPOL-Key frames that are used to install keys. This workaround might cause interoperability issues and reduced robustness of key negotiation especially in environments with heavy traffic load."))
 
diff --git a/modules/luci-mod-admin-full/luasrc/view/admin_uci/apply.htm b/modules/luci-mod-admin-full/luasrc/view/admin_uci/apply.htm
deleted file mode 100644 (file)
index 370027e..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-<%#
- Copyright 2008 Steven Barth <steven@midlink.org>
- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
- Licensed to the public under the Apache License 2.0.
--%>
-
-<%+header%>
-
-<h2 name="content"><%:Configuration%> / <%:Apply%></h2>
-
-<% if changes then %>
-       <%+cbi/apply_xhr%>
-       <%+admin_uci/changelog%>
-
-       <%- cbi_apply_xhr('uci-apply', configs) -%>
-
-       <p><strong><%:The following changes have been committed%>:</strong></p>
-       <%- uci_changelog(changes) -%>
-<% else %>
-       <p><strong><%:There are no pending changes to apply!%></strong></p>
-<% end %>
-
-<%+footer%>
index 6e725c8..9e9ce2b 100644 (file)
@@ -1,40 +1,41 @@
 <%#
  Copyright 2008 Steven Barth <steven@midlink.org>
- Copyright 2008-2015 Jo-Philipp Wich <jow@openwrt.org>
+ Copyright 2008-2018 Jo-Philipp Wich <jo@mein.io>
  Licensed to the public under the Apache License 2.0.
 -%>
 
 <%+header%>
 
+<%-
+       local node, redir_url = luci.dispatcher.lookup(luci.http.formvalue("redir"))
+
+       include("cbi/apply_widget")
+       include("admin_uci/changelog")
+
+       cbi_apply_widget(redir_url or url("admin/uci/changes"))
+-%>
+
 <h2 name="content"><%:Configuration%> / <%:Changes%></h2>
 
 <% if changes then %>
-       <%+admin_uci/changelog%>
        <%- uci_changelog(changes) -%>
 <% else %>
        <p><strong><%:There are no pending changes!%></strong></p>
 <% end %>
 
+<div class="alert-message" id="cbi_apply_status" style="display:none"></div>
+
 <div class="cbi-page-actions">
-       <% local node, url = luci.dispatcher.lookup(luci.http.formvalue("redir")); if url then %>
+       <% if redir_url then %>
        <div style="float:left">
-               <form class="inline" method="get" action="<%=luci.util.pcdata(url)%>">
+               <form class="inline" method="get" action="<%=luci.util.pcdata(redir_url)%>">
                        <input class="cbi-button cbi-button-link" style="float:left; margin:0" type="submit" value="<%:Back%>" />
                </form>
        </div>
        <% end %>
 
        <div style="text-align:right">
-               <form class="inline" method="post" action="<%=controller%>/admin/uci/apply">
-                       <input type="hidden" name="token" value="<%=token%>" />
-                       <input type="hidden" name="redir" value="<%=pcdata(luci.http.formvalue("redir"))%>" />
-                       <input class="cbi-button cbi-button-apply" type="submit" value="<%:Apply%>" />
-               </form>
-               <form class="inline" method="post" action="<%=controller%>/admin/uci/saveapply">
-                       <input type="hidden" name="token" value="<%=token%>" />
-                       <input type="hidden" name="redir" value="<%=pcdata(luci.http.formvalue("redir"))%>" />
-                       <input class="cbi-button cbi-button-save" type="submit" value="<%:Save & Apply%>" />
-               </form>
+               <input class="cbi-button cbi-button-save" type="button" id="apply_button" value="<%:Save & Apply%>" onclick="uci_apply(true); this.blur()" />
                <form class="inline" method="post" action="<%=controller%>/admin/uci/revert">
                        <input type="hidden" name="token" value="<%=token%>" />
                        <input type="hidden" name="redir" value="<%=pcdata(luci.http.formvalue("redir"))%>" />
index 20327ad..dff5342 100644 (file)
@@ -1,26 +1,39 @@
 <%#
  Copyright 2008 Steven Barth <steven@midlink.org>
- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
+ Copyright 2008-2018 Jo-Philipp Wich <jo@mein.io>
  Licensed to the public under the Apache License 2.0.
 -%>
 
 <%+header%>
 
+<%-
+       local node, redir_url = luci.dispatcher.lookup(luci.http.formvalue("redir"))
+
+       include("cbi/apply_widget")
+       include("admin_uci/changelog")
+
+       cbi_apply_widget(redir_url or url("admin/uci/revert"))
+-%>
+
 <h2 name="content"><%:Configuration%> / <%:Revert%></h2>
 
 <% if changes then %>
-       <%+cbi/apply_xhr%>
-       <%+admin_uci/changelog%>
-
        <p><strong><%:The following changes have been reverted%>:</strong></p>
        <%- uci_changelog(changes) -%>
 <% else %>
        <p><strong><%:There are no pending changes to revert!%></strong></p>
 <% end %>
 
-<% local node, url = luci.dispatcher.lookup(luci.http.formvalue("redir")); if url then %>
+<div class="alert-message" id="cbi_apply_status" style="display:none"></div>
+<script type="text/javascript">
+       document.addEventListener("DOMContentLoaded", function() {
+               uci_apply(true);
+       });
+</script>
+
+<% if redir_url then %>
        <div class="cbi-page-actions">
-               <form class="inline" method="get" action="<%=luci.util.pcdata(url)%>">
+               <form class="inline" method="get" action="<%=luci.util.pcdata(redir_url)%>">
                        <input class="cbi-button cbi-button-link" style="margin:0" type="submit" value="<%:Back%>" />
                </form>
        </div>
index 2fb64b3..ebb02e4 100644 (file)
@@ -1,9 +1,9 @@
 <%+cbi/valueheader%>
 
 <script type="text/javascript">//<![CDATA[
-       var freqlist = <%= luci.http.write_json(self.freqlist) %>;
-       var hwmodes  = <%= luci.http.write_json(self.hwmodes) %>;
-       var htmodes  = <%= luci.http.write_json(self.htmodes) %>;
+       var freqlist = <%= luci.http.write_json(self.iwinfo.freqlist) %>;
+       var hwmodes  = <%= luci.http.write_json(self.iwinfo.hwmodelist or {}) %>;
+       var htmodes  = <%= luci.http.write_json(self.iwinfo.htmodelist) %>;
 
        var channels = {
                '11g': [