2 Support for managing apps (as created with "0install add").
6 # Copyright (C) 2012, Thomas Leonard
7 # See the README file for details, or visit http://0install.net.
9 from zeroinstall
import _
, SafeException
10 from zeroinstall
.support
import basedir
, portable_rename
11 from zeroinstall
.injector
import namespaces
, selections
, qdom
12 from logging
import warn
, info
13 import re
, os
, time
, tempfile
15 # Avoid characters that are likely to cause problems (reject : and ; everywhere
16 # so that apps can be portable between POSIX and Windows).
17 valid_name
= re
.compile(r
'''^[^./\\:=;'"][^/\\:=;'"]*$''')
19 def validate_name(name
):
20 if valid_name
.match(name
): return
21 raise SafeException("Invalid application name '{name}'".format(name
= name
))
23 def find_bin_dir(paths
= None):
24 """Find the first writable path in the list (default $PATH),
25 skipping /bin, /sbin and everything under /usr except /usr/local/bin"""
27 paths
= os
.environ
['PATH'].split(os
.pathsep
)
29 if path
.startswith('/usr/') and not path
.startswith('/usr/local/bin'):
30 # (/usr/local/bin is OK if we're running as root)
32 elif path
.startswith('/bin') or path
.startswith('/sbin'):
34 elif os
.path
.realpath(path
).startswith(basedir
.xdg_cache_home
):
35 pass # print "Skipping cache", first_path
36 elif not os
.access(path
, os
.W_OK
):
37 pass # print "No access", first_path
45 _command_template
= """#!/bin/sh
46 exec 0install run {app} "$@"
50 def __init__(self
, config
, path
):
54 def set_selections(self
, sels
):
55 """Store a new set of selections. We include today's date in the filename
56 so that we keep a history of previous selections (max one per day), in case
57 we want to to roll back later."""
58 date
= time
.strftime('%Y-%m-%d')
59 sels_file
= os
.path
.join(self
.path
, 'selections-{date}.xml'.format(date
= date
))
62 tmp
= tempfile
.NamedTemporaryFile(prefix
= 'selections.xml-', dir = self
.path
, delete
= False)
64 dom
.writexml(tmp
, addindent
=" ", newl
="\n", encoding
= 'utf-8')
70 portable_rename(tmp
.name
, sels_file
)
72 sels_latest
= os
.path
.join(self
.path
, 'selections.xml')
73 if os
.path
.exists(sels_latest
):
74 os
.unlink(sels_latest
)
75 os
.symlink(os
.path
.basename(sels_file
), sels_latest
)
77 self
.set_last_checked()
79 def get_selections(self
, snapshot_date
= None):
80 """Load the selections. Does not check whether they are cached, nor trigger updates.
81 @param date: get a historical snapshot
82 @type date: (as returned by L{get_history})
83 @return: the selections
84 @rtype: L{selections.Selections}"""
86 sels_file
= os
.path
.join(self
.path
, 'selections-' + snapshot_date
+ '.xml')
88 sels_file
= os
.path
.join(self
.path
, 'selections.xml')
89 with
open(sels_file
) as stream
:
90 return selections
.Selections(qdom
.parse(stream
))
92 def get_history(self
):
93 """Get the dates of the available snapshots, starting with the most recent.
95 date_re
= re
.compile('selections-(\d\d\d\d-\d\d-\d\d).xml')
97 for f
in os
.listdir(self
.path
):
98 match
= date_re
.match(f
)
100 snapshots
.append(match
.group(1))
101 snapshots
.sort(reverse
= True)
104 def download_selections(self
, sels
):
105 """Download any missing implementations in the given selections.
106 If no downloads are needed, but we haven't checked for a while, start
107 a background process to check for updates (but return None immediately).
108 @return: a blocker which resolves when all needed implementations are available
109 @rtype: L{tasks.Blocker} | None
111 stores
= self
.config
.stores
113 # Check the selections are still available
114 blocker
= sels
.download_missing(self
.config
) # TODO: package impls
119 # Nothing to download, but is it time for a background update?
120 timestamp_path
= os
.path
.join(self
.path
, 'last-checked')
122 utime
= os
.stat(timestamp_path
).st_mtime
123 staleness
= time
.time() - utime
124 info("Staleness of app %s is %d hours", self
, staleness
/ (60 * 60))
125 freshness_threshold
= self
.config
.freshness
126 need_update
= freshness_threshold
> 0 and staleness
>= freshness_threshold
129 last_check_attempt_path
= os
.path
.join(self
.path
, 'last-check-attempt')
130 if os
.path
.exists(last_check_attempt_path
):
131 last_check_attempt
= os
.stat(last_check_attempt_path
).st_mtime
132 if last_check_attempt
+ 60 * 60 > time
.time():
133 info("Tried to check within last hour; not trying again now")
135 except Exception as ex
:
136 warn("Failed to get time-stamp of %s: %s", timestamp_path
, ex
)
140 self
.set_last_check_attempt()
141 from zeroinstall
.injector
import background
142 r
= self
.get_requirements()
143 background
.spawn_background_update2(r
, True, self
)
145 def set_requirements(self
, requirements
):
147 tmp
= tempfile
.NamedTemporaryFile(prefix
= 'tmp-requirements-', dir = self
.path
, delete
= False)
149 json
.dump(dict((key
, getattr(requirements
, key
)) for key
in requirements
.__slots
__), tmp
)
156 reqs_file
= os
.path
.join(self
.path
, 'requirements.json')
157 portable_rename(tmp
.name
, reqs_file
)
159 def get_requirements(self
):
161 from zeroinstall
.injector
import requirements
162 r
= requirements
.Requirements(None)
163 reqs_file
= os
.path
.join(self
.path
, 'requirements.json')
164 with
open(reqs_file
) as stream
:
165 values
= json
.load(stream
)
166 for k
, v
in values
.items():
170 def set_last_check_attempt(self
):
171 timestamp_path
= os
.path
.join(self
.path
, 'last-check-attempt')
172 fd
= os
.open(timestamp_path
, os
.O_WRONLY | os
.O_CREAT
, 0o644)
174 os
.utime(timestamp_path
, None) # In case file already exists
176 def get_last_checked(self
):
177 """Get the time of the last successful check for updates.
178 @return: the timestamp (or None on error)
179 @rtype: float | None"""
180 last_updated_path
= os
.path
.join(self
.path
, 'last-checked')
182 return os
.stat(last_updated_path
).st_mtime
183 except Exception as ex
:
184 warn("Failed to get time-stamp of %s: %s", last_updated_path
, ex
)
187 def get_last_check_attempt(self
):
188 """Get the time of the last attempted check.
189 @return: the timestamp, or None if we updated successfully.
190 @rtype: float | None"""
191 last_check_attempt_path
= os
.path
.join(self
.path
, 'last-check-attempt')
192 if os
.path
.exists(last_check_attempt_path
):
193 last_check_attempt
= os
.stat(last_check_attempt_path
).st_mtime
195 last_checked
= self
.get_last_checked()
197 if last_checked
< last_check_attempt
:
198 return last_check_attempt
201 def set_last_checked(self
):
202 timestamp_path
= os
.path
.join(self
.path
, 'last-checked')
203 fd
= os
.open(timestamp_path
, os
.O_WRONLY | os
.O_CREAT
, 0o644)
205 os
.utime(timestamp_path
, None) # In case file already exists
208 # Check for shell command
209 # TODO: remember which commands we own instead of guessing
210 name
= self
.get_name()
211 bin_dir
= find_bin_dir()
212 launcher
= os
.path
.join(bin_dir
, name
)
213 expanded_template
= _command_template
.format(app
= name
)
214 if os
.path
.exists(launcher
) and os
.path
.getsize(launcher
) == len(expanded_template
):
215 with
open(launcher
, 'r') as stream
:
216 contents
= stream
.read()
217 if contents
== expanded_template
:
218 #print "rm", launcher
221 # Remove the app itself
223 shutil
.rmtree(self
.path
)
225 def integrate_shell(self
, name
):
226 # TODO: remember which commands we create
227 if not valid_name
.match(name
):
228 raise SafeException("Invalid shell command name '{name}'".format(name
= name
))
229 bin_dir
= find_bin_dir()
230 launcher
= os
.path
.join(bin_dir
, name
)
231 if os
.path
.exists(launcher
):
232 raise SafeException("Command already exists: {path}".format(path
= launcher
))
234 with
open(launcher
, 'w') as stream
:
235 stream
.write(_command_template
.format(app
= self
.get_name()))
236 # Make new script executable
237 os
.chmod(launcher
, 0o111 | os
.fstat(stream
.fileno()).st_mode
)
240 return os
.path
.basename(self
.path
)
243 return '<app ' + self
.get_name() + '>'
246 def __init__(self
, config
):
249 def create_app(self
, name
, requirements
):
252 apps_dir
= basedir
.save_config_path(namespaces
.config_site
, "apps")
253 app_dir
= os
.path
.join(apps_dir
, name
)
254 if os
.path
.isdir(app_dir
):
255 raise SafeException(_("Application '{name}' already exists: {path}").format(name
= name
, path
= app_dir
))
258 app
= App(self
.config
, app_dir
)
259 app
.set_requirements(requirements
)
260 app
.set_last_checked()
264 def lookup_app(self
, name
, missing_ok
= False):
265 """Get the App for name.
266 Returns None if name is not an application (doesn't exist or is not a valid name).
267 Since / and : are not valid name characters, it is generally safe to try this
268 before calling L{model.canonical_iface_uri}."""
269 if not valid_name
.match(name
):
273 raise SafeException("Invalid application name '{name}'".format(name
= name
))
274 app_dir
= basedir
.load_first_config(namespaces
.config_site
, "apps", name
)
276 return App(self
.config
, app_dir
)
280 raise SafeException("No such application '{name}'".format(name
= name
))