JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
74d7a5c4db7ebd349ae5ced95c4ee81b72840727
[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                 old_info: (cb) => @api 'app_info', old_app, cb
58                 new_info: (cb) => @api 'app_info', new_app, cb
59                 push: (cb) => @api 'app_update_files', new_app, zip_file, cb
60                 copy_uris: ['push', 'old_info', 'new_info', (cb, args) =>
61                         # There's a bug in the server where you can't set new uris and
62                         # start the app in the same app_set_info call
63                         for u in args.old_info.uris
64                                 args.new_info.uris.push u unless u.substr(-6) is '.af.cm'
65                         @api 'app_set_info', new_app, args.new_info, cb
66                 ]
67                 new_info_again: ['copy_uris', (cb, args) =>
68                         @api 'app_info', new_app, cb
69                 ]
70                 start_new: ['new_info_again', (cb, args) =>
71                         args.new_info_again.state = 'STARTED'
72                         @api 'app_set_info', new_app, args.new_info_again, cb
73                 ]
74                 hide_old: ['start_new', 'old_info', (cb, args) =>
75                         just_af = []
76                         for u in args.old_info.uris
77                                 just_af.push u if u.substr(-6) is '.af.cm'
78                         args.old_info.uris = just_af
79                         @api 'app_set_info', old_app, args.old_info, cb
80                 ]
81                 wait_for_old_connections: ['hide_old', (cb) =>
82                         seconds = 10
83                         log_id = @log_start "waiting #{seconds} seconds for connections to old instance to finish"
84                         timeout seconds * 1000, =>
85                                 @log_end(log_id)
86                                 cb()
87                 ]
88                 old_info_again: ['hide_old', (cb) =>
89                         @api 'app_info', old_app, cb
90                 ]
91                 stop_old: ['wait_for_old_connections', 'old_info_again', (cb, args) =>
92                         args.old_info_again.state = 'STOPPED'
93                         @api 'app_set_info', old_app, args.old_info_again, cb
94                 ]
95                 # TODO when we get into sending manifests, we may need to update_files to old_app too
96         }, callback
97
98 app_set_state = (token, app_name, state, callback) ->
99         async.waterfall [
100                 (callback) =>
101                         @api 'app_info', app_name, callback
102                 (info, callback) =>
103                         info.state = state
104                         @api 'app_set_info', app_name, info, callback
105         ], callback
106
107 commands.app_start = (token, app_name, callback) ->
108         app_set_state.call this, token, app_name, 'STARTED', callback
109
110 commands.app_stop = (token, app_name, callback) ->
111         app_set_state.call this, token, app_name, 'STOPPED', callback
112
113
114 commands.app_restart = (token, app_name, callback) ->
115         # Server requires you to fetch the app state before each call to change
116         # it, so there's no quicker way than just calling app_stop then app_start
117         async.waterfall [
118                 (callback) =>      @api 'app_stop',  app_name, callback
119                 (res, callback) => @api 'app_start', app_name, callback
120         ], callback
121
122
123
124 class Session
125         constructor: ->
126                 @token = 0
127                 @verbose = true
128                 @log_nest = 0
129                 @log_mid = 0
130                 @log_id = 0
131
132         log_whitespace: ->
133                 out = ''
134                 out += '\n' if @log_mid
135                 for i in [0...@log_nest]
136                         out += '\t'
137                 return out
138
139         log_start: (msg) ->
140                 return unless @verbose
141                 @log_id += 1
142                 process.stdout.write "#{@log_whitespace()}#{@log_id}: #{msg}"
143                 @log_nest += 1
144                 @log_mid = @log_id
145                 return @log_id
146
147         log_end: (start_id) ->
148                 return unless @verbose
149                 @log_nest -= 1
150                 if @log_mid is start_id
151                         process.stdout.write "... done\n"
152                 else
153                         process.stdout.write "#{@log_whitespace()}#{start_id} done\n"
154                 @log_mid = 0
155
156         api: (call, args..., callback) ->
157                 async.waterfall [
158                         (callback) =>
159                                 switch @token
160                                         when 0
161                                                 get_token callback
162                                         when -1
163                                                 login.call this, callback
164                                         else
165                                                 callback null, @token
166                         (token, callback) =>
167                                 @token = token
168                                 log_id = @log_start [call, args...].join ' '
169                                 # commands implemented in client.coffee need "this" pointing to the session
170                                 commands[call].call this, @token, args..., (err, the_rest...) =>
171                                         @log_end(log_id) unless err?
172                                         callback err, the_rest...
173                 ], (err, result) =>
174                         # eg /app/xxx/stats sometimes returns 404 with wrong auth token
175                         if err?.code is 403 or err?.code is 404
176                                 @token = -1
177                                 @api(call, args..., callback)
178                         else
179                                 callback err, result
180
181         ask: (opts, callback) ->
182                 process.stdout.write @log_whitespace() + opts.prompt
183                 process.stdin.setEncoding 'utf8'
184                 process.stdin.resume()
185                 process.stdin.once 'data', (line) =>
186                         if opts.silent
187                                 # send ^[[A^[[2K to move the cursor up one line, then clear that line
188                                 process.stdout.write new Buffer [27, 91, 65, 27, 91, 50, 75]
189                                 process.stdout.write @log_whitespace() + opts.prompt + "***\n"
190                         process.stdin.pause()
191                         @log_mid = 0
192                         callback null, (line.substr 0, line.length - 1)
193
194 get_token = (callback) ->
195         fs.readFile token_file, 'utf8', (err, token) ->
196                 if err?
197                         login callback
198                 else
199                         callback null, token
200
201 login = (callback) ->
202         async.waterfall [
203                 (callback) => async.series [
204                         (callback) => @ask prompt: 'username: ', callback
205                         (callback) => @ask prompt: 'password: ', silent: true, callback
206                 ], callback
207                 ([username, password], callback) ->
208                         af.login username, password, callback
209                 (token, callback) ->
210                         # wait for file write so there's no race condition if get_token gets called soon
211                         fs.writeFile token_file, token, (err) ->
212                                 if err
213                                         process.stderr.write "Warning: couldn't cache auth token in #{token_file}: #{err}\n"
214                                 # don't pass on error, it's ok if we can't cache it
215                                 callback null, token
216         ], callback
217
218
219 exports.new_session = ->
220         return new Session()
221
222 usage = ->
223         process.stderr.write "usage: #{process.argv[0]} #{process.argv[1]} command [args...]\n"
224         process.stderr.write "valid commands are:\n\t#{(k for k, v of commands).join '\n\t'}\n"
225
226 # parse and act on commandline arguments unless we were require()d as a module
227 if require.main is module
228         args = process.argv[2..]
229         if args.length is 0
230                 usage()
231         else if not commands[args[0]]
232                 process.stderr.write "unknown command \"#{args[0]}\"\n"
233                 usage()
234         else
235                 session = new Session()
236                 session.api args[0], args[1..]..., (err, result) ->
237                         if err?
238                                 process.stderr.write "Error: #{JSON.stringify err}\n"
239                         if result?
240                                 if typeof result is 'string'
241                                         process.stdout.write result
242                                 else
243                                         process.stdout.write JSON.stringify result