JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
work around server bug to fix publish_seamless
[af-coffee.git] / client.coffee
1 #!/usr/bin/coffee
2
3 fs = require 'fs'
4 async = require 'async'
5 af = require './api.coffee'
6
7 token_file = "#{process.env.HOME}/.af-coffee-token"
8
9 timeout = (ms, f) -> setTimeout f, ms
10
11 # a session caches the api access token and prompts for the username and
12 # password if it goes stale. It re-tries API calls that fail due to
13 # invalid/expired token
14
15 commands = {}
16 for k, v of af
17         commands[k] = v unless k is 'login'
18
19 # this is the simple one that updates the files then restarts the app.
20 # to update without severing current connections or downtime, see app_publish_seamless
21 commands.app_publish = (token, app_name, zip_file, callback) ->
22         async.waterfall [
23                 (callback) =>      @api 'app_update_files', app_name, zip_file, callback
24                 (res, callback) => @api 'app_restart',      app_name, callback
25         ], callback
26
27
28 # This uses a pair of apps to get a seamless upgrades. ie the site is never
29 # down, and connections that are open at the time of upgrade are given 10
30 # seconds to close.
31 #
32 # Requirements:
33 #
34 # 1.    There must be two apps with the same name except one has an underscore at
35 #       the end and the other doesn't.
36 #
37 # 2.    One of these apps must be running, and must have the domain names mapped
38 #       to it.
39 #
40 # 3.    The other must be stopped, and must not have the domain names mapped  to
41 #       it. (just it's *.af.com address.)
42 #
43 # For now, pass only the name of the app which is currently stopped.
44 commands.app_publish_seamless = (token, app_name, zip_file, callback) ->
45         # FIXME auto-detect which one is new by checking app_info.urls.length
46         # (should happen for all api calls?)
47         #
48         # for now, we assume that the passed app_name is the currently dormant one
49         if app_name.substr(-1) is '_'
50                 old_app = app_name.substr 0, app_name.length - 1
51                 new_app = app_name
52         else
53                 old_app = app_name + '_'
54                 new_app = app_name
55
56         async.auto {
57                 push: (cb) => @api 'app_update_files', new_app, zip_file, cb
58                 # TODO find out if app_update_files increments app_info.version
59                 # if not, drop new_info's dependency on push
60                 old_info: (cb) => @api 'app_info', old_app, cb
61                 new_info: ['push', (cb) => @api 'app_info', new_app, cb ]
62                 copy_uris: ['push', 'old_info', 'new_info', (cb, args) =>
63                         # There's a bug in the server where you can't set new uris and
64                         # start the app in the same app_set_info call
65                         for u in args.old_info.uris
66                                 args.new_info.uris.push u unless u.substr(-6) is '.af.cm'
67                         @api 'app_set_info', new_app, args.new_info, cb
68                 ]
69                 new_info_again: ['copy_uris', (cb, args) =>
70                         @api 'app_info', new_app, cb
71                 ]
72                 start_new: ['new_info_again', (cb, args) =>
73                         args.new_info_again.state = 'STARTED'
74                         @api 'app_set_info', new_app, args.new_info_again, cb
75                 ]
76                 hide_old: ['start_new', 'old_info', (cb, args) =>
77                         just_af = []
78                         for u in args.old_info.uris
79                                 just_af.push u if u.substr(-6) is '.af.cm'
80                         args.old_info.uris = just_af
81                         @api 'app_set_info', old_app, args.old_info, cb
82                 ]
83                 wait_for_old_connections: ['hide_old', (cb) =>
84                         seconds = 10
85                         log_id = @log_start "waiting #{seconds} seconds for connections to old instance to finish"
86                         timeout seconds * 1000, =>
87                                 @log_end(log_id)
88                                 cb()
89                 ]
90                 old_info_again: ['hide_old', (cb) =>
91                         @api 'app_info', old_app, cb
92                 ]
93                 stop_old: ['wait_for_old_connections', 'old_info_again', (cb, args) =>
94                         args.old_info_again.state = 'STOPPED'
95                         @api 'app_set_info', old_app, args.old_info_again, cb
96                 ]
97                 # TODO when we get into sending manifests, we may need to update_files to old_app too
98         }, callback
99
100 app_set_state = (token, app_name, state, callback) ->
101         async.waterfall [
102                 (callback) =>
103                         @api 'app_info', app_name, callback
104                 (info, callback) =>
105                         info.state = state
106                         @api 'app_set_info', app_name, info, callback
107         ], callback
108
109 commands.app_start = (token, app_name, callback) ->
110         app_set_state.call this, token, app_name, 'STARTED', callback
111
112 commands.app_stop = (token, app_name, callback) ->
113         app_set_state.call this, token, app_name, 'STOPPED', callback
114
115
116 commands.app_restart = (token, app_name, callback) ->
117         # Server requires you to fetch the app state before each call to change
118         # it, so there's no quicker way than just calling app_stop then app_start
119         async.waterfall [
120                 (callback) =>      @api 'app_stop',  app_name, callback
121                 (res, callback) => @api 'app_start', app_name, callback
122         ], callback
123
124
125
126 class Session
127         constructor: ->
128                 @token = 0
129                 @verbose = true
130                 @log_nest = 0
131                 @log_mid = 0
132                 @log_id = 0
133
134         log_whitespace: ->
135                 out = ''
136                 out += '\n' if @log_mid
137                 for i in [0...@log_nest]
138                         out += '\t'
139                 return out
140
141         log_start: (msg) ->
142                 return unless @verbose
143                 @log_id += 1
144                 process.stdout.write "#{@log_whitespace()}#{@log_id}: #{msg}"
145                 @log_nest += 1
146                 @log_mid = @log_id
147                 return @log_id
148
149         log_end: (start_id) ->
150                 return unless @verbose
151                 @log_nest -= 1
152                 if @log_mid is start_id
153                         process.stdout.write "... done\n"
154                 else
155                         process.stdout.write "#{@log_whitespace()}#{start_id} done\n"
156                 @log_mid = 0
157
158         api: (call, args..., callback) ->
159                 async.waterfall [
160                         (callback) =>
161                                 switch @token
162                                         when 0
163                                                 get_token callback
164                                         when -1
165                                                 login.call this, callback
166                                         else
167                                                 callback null, @token
168                         (token, callback) =>
169                                 @token = token
170                                 log_id = @log_start [call, args...].join ' '
171                                 # commands implemented in client.coffee need "this" pointing to the session
172                                 commands[call].call this, @token, args..., (err, the_rest...) =>
173                                         @log_end(log_id) unless err?
174                                         callback err, the_rest...
175                 ], (err, result) =>
176                         # eg /app/xxx/stats sometimes returns 404 with wrong auth token
177                         if err?.code is 403 or err?.code is 404
178                                 @token = -1
179                                 @api(call, args..., callback)
180                         else
181                                 callback err, result
182
183         ask: (opts, callback) ->
184                 process.stdout.write @log_whitespace() + opts.prompt
185                 process.stdin.setEncoding 'utf8'
186                 process.stdin.resume()
187                 process.stdin.once 'data', (line) =>
188                         if opts.silent
189                                 # send ^[[A^[[2K to move the cursor up one line, then clear that line
190                                 process.stdout.write new Buffer [27, 91, 65, 27, 91, 50, 75]
191                                 process.stdout.write @log_whitespace() + opts.prompt + "***\n"
192                         process.stdin.pause()
193                         @log_mid = 0
194                         callback null, (line.substr 0, line.length - 1)
195
196 get_token = (callback) ->
197         fs.readFile token_file, 'utf8', (err, token) ->
198                 if err?
199                         login callback
200                 else
201                         callback null, token
202
203 login = (callback) ->
204         async.waterfall [
205                 (callback) => async.series [
206                         (callback) => @ask prompt: 'username: ', callback
207                         (callback) => @ask prompt: 'password: ', silent: true, callback
208                 ], callback
209                 ([username, password], callback) ->
210                         af.login username, password, callback
211                 (token, callback) ->
212                         # wait for file write so there's no race condition if get_token gets called soon
213                         fs.writeFile token_file, token, (err) ->
214                                 if err
215                                         process.stderr.write "Warning: couldn't cache auth token in #{token_file}: #{err}\n"
216                                 # don't pass on error, it's ok if we can't cache it
217                                 callback null, token
218         ], callback
219
220
221 exports.new_session = ->
222         return new Session()
223
224 usage = ->
225         process.stderr.write "usage: #{process.argv[0]} #{process.argv[1]} command [args...]\n"
226         process.stderr.write "valid commands are:\n\t#{(k for k, v of commands).join '\n\t'}\n"
227
228 # parse and act on commandline arguments unless we were require()d as a module
229 if require.main is module
230         args = process.argv[2..]
231         if args.length is 0
232                 usage()
233         else if not commands[args[0]]
234                 process.stderr.write "unknown command \"#{args[0]}\"\n"
235                 usage()
236         else
237                 session = new Session()
238                 session.api args[0], args[1..]..., (err, result) ->
239                         if err?
240                                 process.stderr.write "Error: #{JSON.stringify err}\n"
241                         if result?
242                                 if typeof result is 'string'
243                                         process.stdout.write result
244                                 else
245                                         process.stdout.write JSON.stringify result